<template>
    <!-- 对话框表单 -->
    <el-dialog
        custom-class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="baTable.form.operate ? true : false"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? baTable.form.operate == 'edit' ? '编辑' : '添加' : '无标题' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    ref="formRef"
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    label-position="right"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                    v-if="!baTable.form.loading"
                >
                    <el-form-item prop="motto" label="部门">
                        <el-cascader
                            ref="deparmentSelect"
                            :options="options.datas"
                            :props="propsOrg"
                            style="width: 100%"
                            @change="onCascaderChange"
                            v-model="baTable.form.items!.departmentPids"
                            :disabled="baTable.form.operate=='edit'"
                        />
                    </el-form-item>
                    <el-form-item prop="empId" label="员工">
                        <el-select v-model="baTable.form.items!.empId" placeholder="请选择企业员工" style="width: 100%"
                                   clearable :disabled="baTable.form.operate=='edit'">
                            <el-option v-for="item in options.empSelect" :key="item.id" :label="item.trueName"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                    <FormItem
                        label="账号"
                        v-model="baTable.form.items!.accountName"
                        type="string"
                        prop="accountName"
                        placeholder="请输入账号名称"
                    />
                    <FormItem
                        label="角色"
                        v-model="baTable.form.items!.roleArr"
                        type="remoteSelect"
                        prop="roleArr"
                        :input-attr="{
                            multiple: true,
                            params: { isTree: true },
                            field: 'name',
                            'remote-url': authGroup + 'select',
                            placeholder: '请选择角色组',
                            showRefresh: false,
                        }"
                    />
                    <FormItem label="头像" type="image" v-model="baTable.form.items!.avatar"/>
                    <FormItem
                        label="密码"
                        prop="password"
                        v-model="baTable.form.items!.password"
                        type="password"
                        :placeholder="
                            baTable.form.operate == 'add'
                                ? '请输入密码'
                                : '不修改请留空'
                        "
                    />
                    <el-form-item prop="motto" label="个性签名">
                        <el-input
                            @keyup.enter.stop=""
                            @keyup.ctrl.enter="baTable.onSubmit(formRef)"
                            v-model="baTable.form.items!.motto"
                            type="textarea"
                            placeholder="请输入个性签名"
                        ></el-input>
                    </el-form-item>
                    <FormItem
                        label="状态"
                        v-model="baTable.form.items!.status"
                        type="radio"
                        :data="{ content: { '0': '禁用', '1': '启用' }, childrenAttr: { border: true } }"
                    />
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">取消</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)"
                           type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? '保存并编辑下一项' : '保存' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, inject, onMounted, watch} from 'vue'

import type baTableClass from '/@/utils/baTable'
import {regularPassword, validatorAccount, validatorMobile} from '/@/utils/validate'
import type {ElForm, FormItemRule} from 'element-plus'
import FormItem from '/@/components/formItem/index.vue'
import {getOrgTree, getEmployees} from '/@/api/backend/auth/account'
import {authGroup} from '/@/api/controllerUrls'

const formRef = ref<InstanceType<typeof ElForm>>()
const baTable = inject('baTable') as baTableClass


const deparmentSelect = ref()

const propsOrg = {
    checkStrictly: true,
    multiple: false,
    value: 'id',
}
let isBind: boolean = false
let options = reactive({datas: [], empSelect: []})

const initialOrgTree = () => {
    getOrgTree().then((res) => {
        if (res.code == 1) {
            options.datas = res.data.trees
        }
    })
}

const onCascaderChange = (value: Array<Number>) => {
    let data = {pids: ''}
    data.pids = value.join(',')
    getEmployees(data).then((res) => {
        if (res.code == 1) {
            baTable.form.items!.empId = null
            options.empSelect = []
            options.empSelect = res.data.list
        }
    })
}

watch(
    () => baTable.form.items!.departmentPids,
    (newVal) => {
        if (!isBind && baTable.form.operate == 'edit') {
            let data = {pids: ''}
            data.pids = baTable.form.items!.departmentPids.join(',')
            getEmployees(data).then((res) => {
                if (res.code == 1) {
                    options.empSelect = res.data.list
                }
            })
            isBind = true
        }
    }
)

onMounted(() => {
    initialOrgTree()
    if (baTable.form.operate == 'edit') {
        baTable.form.operate
    }
})

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    accountName: [
        {
            required: true,
            message: '请输入账号名称',
            trigger: 'blur',
        },
        {
            validator: validatorAccount,
            trigger: 'blur',
        },
    ],
    empId: [
        {
            required: true,
            message: '请选择企业员工',
            trigger: 'blur',
        },
    ],
    roleArr: [
        {
            required: true,
            message: '请选择角色组',
            trigger: 'blur',
        },
    ],
    password: [
        {
            validator: (rule: any, val: string, callback: Function) => {
                if (baTable.form.operate == 'add') {
                    if (!val) {
                        return callback(new Error('请输入密码'))
                    }
                } else {
                    if (!val) {
                        return callback()
                    }
                }
                if (!regularPassword(val)) {
                    return callback(new Error('请输入正确的密码'))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
})
</script>

<style scoped lang="scss">
.avatar-uploader {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    border-radius: var(--el-border-radius-small);
    box-shadow: var(--el-box-shadow-light);
    border: 1px dashed var(--color-sub-1);
    cursor: pointer;
    overflow: hidden;
    width: 110px;
    height: 110px;
}

.avatar-uploader:hover {
    border-color: var(--color-primary);
}

.avatar {
    width: 110px;
    height: 110px;
    display: block;
}

.image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}
</style>
