<template>
    <a-modal :visible="true" :maskClosable="false" centered :destroyOnClose="true" :title="title"
        :wrapClassName="wrapClassName" :width="width" @cancel="onClose" @ok="onSubmit">
        <div class="content">
            <a-form ref="formRef" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                <div class="basic-info">
                    <div class="small-title">基础信息</div>
                    <a-form-item label="登录名" name="loginName">
                        <a-input v-model:value="form.loginName" style="width: 100%" placeholder="请输入登录名" />
                    </a-form-item>
                    <a-form-item label="用户姓名" name="userName">
                        <a-input v-model:value="form.userName" style="width: 100%" placeholder="请输入姓名" />
                    </a-form-item>
                    <a-form-item label="手机号" name="mobile">
                        <a-input v-model:value="form.mobile" style="width: 100%" placeholder="请输入手机号" />
                    </a-form-item>
                    <a-form-item label="密码" name="pwd">
                        <a-input-password v-model:value="form.pwd" style="width: 100%" placeholder="请输入密码" />
                    </a-form-item>
                    <a-form-item label="性别" name="sex">
                        <a-select v-model:value="form.sex" style="width: 100%">
                            <a-select-option value="0">女</a-select-option>
                            <a-select-option value="1">男</a-select-option>
                        </a-select>
                    </a-form-item>
                </div>
                <div class="basic-info">
                    <div class="small-title">岗位信息</div>
                    <a-form-item label="所属机构" name="ssjg">
                        <a-tree-select v-model:value="form.ssjg" style="width: 100%"
                            :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }" :tree-data="treeData"
                            placeholder="请选择机构"
                            :replaceFields="{ children: 'children', title: 'name', key: 'departid', value: 'departid' }">
                        </a-tree-select>
                    </a-form-item>
                    <a-form-item label="所属职位" name="sszw">
                        <a-select v-model:value="form.sszw" style="width: 100%" placeholder="请选择职位" :options="zwOption"
                            :dropdown-style="{ maxHeight: '150px', overflow: 'auto' }">
                        </a-select>
                    </a-form-item>
                    <a-form-item label="所属岗位" name="ssgw">
                        <a-select v-model:value="form.ssgw" style="width: 100%" placeholder="请选择岗位" :options="gwOption"
                            :dropdown-style="{ maxHeight: '150px', overflow: 'auto' }">
                        </a-select>
                    </a-form-item>
                    <a-form-item label="角色" name="userjsArr">
                        <a-select v-model:value="form.userjsArr" mode="multiple" style="width: 100%" placeholder="请选择角色"
                            :dropdown-style="{ maxHeight: '150px', overflow: 'auto' }" :options="jsOption" :maxTagCount="4">
                        </a-select>
                    </a-form-item>
                </div>
            </a-form>
        </div>
        <template #footer>
            <div class="btns" style="display: flex;justify-content: center;">
                <a-button class="btn" @click="onClose"
                    style="width: 64px;height: 34px;margin-right: 25px;color: #333333;">取消</a-button>
                <a-button class="btn" @click="onSubmit"
                    style="width: 64px;height: 34px;background: #0671DD;color: #ffffff;">确定</a-button>
            </div>
        </template>
    </a-modal>
</template>
<script>
import { defineComponent, reactive, ref, onMounted, watch, toRefs } from 'vue';
import { message } from 'ant-design-vue';
import moment from 'moment';
import { v4 as uuidv4 } from 'uuid';
import md5 from 'js-md5';
import { savePosts } from '/@/api/sys/zhiwei';
// 正则表达式验证
import { ChineseRegexp, EmailRegexp, phoneRegexp } from '/@/utils/rules';
// 验证手机号与登录名重复性
import { isAccountExist, IsPhoneExist, SaveOrUpdateUserInfo } from '/@/api/system/system';
// 导入接口
import { structureList, getPostsList, getPositionList } from '/@/api/sys/position';
//角色列表api
import { roleList } from '/@/api/sys/user';

const props = {
    formData: {
        type: Object,
        default: {}
    },
    title: {
        type: String,
        default: "新增职位"
    }
}
export default defineComponent({
    name: 'modal',
    components: {},
    props,
    setup(props, { emit }) {
        const data = reactive({
            width: '440px',
            wrapClassName: 'modal-wrap',
            treeData: [],//机构树，初始化时就获取
            zwOption: [],//职位选择
            gwOption: [],//岗位选择
            jsOption: []//角色选择
        })
        const form = reactive({
            loginName: "",
            userName: "",
            pwd: '',
            mobile: "",
            sex: '0',
            ssjg: "",
            sszw: "",
            ssgw: "",
            userjsArr: [],
            userjs: "",
            userid: ""
        });
        const checkLoginName = (rule, value, callback) => {
            if (!value) {
                // callback(new Error("请输入用户名"));
                return Promise.reject("请输入用户名")
            } else {
                //如果字符串 string 中含有与 RegExpObject 匹配的文本，则返回 true，否则返回 false。
                if (ChineseRegexp.test(value)) {
                    // callback(new Error("不能输入中文"));
                    return Promise.reject("不能输入中文")
                } else if (EmailRegexp.test(value)) {
                    // callback(new Error("不能使用邮箱格式"));
                    return Promise.reject("不能使用邮箱格式")
                } else {
                    return Promise.resolve()
                    // isAccountExist(value).then(({ data }) => {
                    //     if (data != null) {
                    //         callback(new Error('用户名已存在'));
                    //     } else {
                    //         callback()
                    //     }
                    // });
                }
            }
        };
        const checkMobile = (rule, value, callback) => {
            if (!value) {
                // callback(new Error("请输入手机号"));
                return Promise.reject("请输入手机号")
            } else {
                //如果字符串 string 中含有与 RegExpObject 匹配的文本，则返回 true，否则返回 false。
                if (!phoneRegexp.test(value)) {
                    // callback(new Error("手机号格式不正确"));
                    return Promise.reject("手机号格式不正确")
                } else {
                    // callback();
                    return Promise.resolve()
                    // IsPhoneExist(value).then(({ data }) => {
                    //     if (data != null) {
                    //         callback(new Error("手机号已存在"));
                    //     } else {
                    //         callback();
                    //     }
                    // });
                }
            }
        };
        const checkRole = (rule, value, callback) => {
            if (!value.length) {
                // callback(new Error("请选择角色"));
                return Promise.reject("请选择角色")
            } else {
                // callback()
                return Promise.resolve()
            }
        };
        const rules = {
            loginName: [
                { validator: checkLoginName, trigger: "change" },
            ],
            userName: [{
                required: true,
                message: '请输入姓名',
                trigger: 'blur'
            }],
            pwd: [
                { required: true, message: '密码不能为空' },
                { pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*\W)[\S]{8,30}$/, message: '密码中必须包含大小写字母、数字、特殊字符，至少8个字符，最多30个字符' }
            ],
            mobile: [
                { validator: checkMobile, trigger: "change" },
            ],
            sex: [{
                required: true,
                message: '请选择性别',
                trigger: 'blur'
            }],
            sszw: [{
                required: true,
                message: '请选择职位',
                trigger: 'blur'
            }],
            ssgw: [{
                required: true,
                message: '请选择岗位',
                trigger: 'blur'
            }],
            userjsArr: [
                { validator: checkRole, trigger: "change" },
            ],
        };
        const title = ref(props.title)
        const formRef = ref()

        onMounted(() => {
            if (Object.keys(props.formData).length) {
                for (let key in form) {
                    form[key] = props.formData[key]
                }
            }
            structureList().then(res => {
                data.treeData = res
            })
            roleList().then(res => {
                if (res.length) {
                    res.forEach(item => {
                        data.jsOption.push({
                            label: item.groupName,
                            value: item.groupid
                        })
                    })
                } else {
                    message.error('角色数据查询失败')
                }
            })
            if (props.title === '修改用户') {
                let params1 = {
                    departmentId: form.ssjg
                }
                getPostsList(params1).then(res => {
                    if (res.datas && res.datas?.length) {
                        res.datas.forEach(item => {
                            data.zwOption.push({
                                label: item.departName,
                                value: item.departid
                            })
                        })
                    } else {
                        message.info('该部门下无职位数据')
                        data.zwOption = []
                    }
                })
                let params = {
                    zwId: form.sszw
                }
                getPositionList(params).then(res => {
                    if (res.datas && res.datas.length) {
                        res.datas.forEach(item => {
                            data.gwOption.push({
                                label: item.name,
                                value: item.id
                            })
                        })
                    } else {
                        message.info('该职位下无岗位数据')
                        data.gwOption = []
                    }
                })
            }
        })
        watch(
            () => [props.formData, props.title],
            ([newF, newD]) => {
                for (let key in form) {
                    form[key] = newF[key]
                }
                title.value = newD
            },
            {
                immediate: true,
                deep: true
            }
        )
        // 查职位
        watch(
            () => form.ssjg,
            (val) => {
                data.gwOption = []
                if (val !== '') {
                    //查询职位
                    let params = {
                        departmentId: val
                    }
                    getPostsList(params).then(res => {
                        if (res.datas && res.datas?.length) {
                            res.datas.forEach(item => {
                                data.zwOption.push({
                                    label: item.departName,
                                    value: item.departid
                                })
                            })
                        } else {
                            message.info('该部门下无职位数据')
                            data.zwOption = []
                        }
                    })
                } else {
                    data.zwOption = []
                }
            }
        )
        // 查岗位
        watch(
            () => form.sszw,
            (val) => {
                if (val !== '') {
                    //查询岗位
                    let params = {
                        zwId: val
                    }
                    getPositionList(params).then(res => {
                        if (res.datas && res.datas.length) {
                            res.datas.forEach(item => {
                                data.gwOption.push({
                                    label: item.name,
                                    value: item.id
                                })
                            })
                        } else {
                            message.info('该职位下无岗位数据')
                            data.gwOption = []
                        }
                    })
                } else {
                    data.gwOption = []
                }
            }
        )
        // 关闭请求弹窗
        const onClose = () => {
            emit('closeModal')
            resetForm()
        };
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                //此处调用新增
                if (title.value === '新增用户') {
                    form.userid = uuidv4();
                }
                form.loginName = form.loginName.toUpperCase();
                form.userjs = form.userjsArr.join(';');
                form.pwd = md5(form.pwd)
                SaveOrUpdateUserInfo(form).then(res => {
                    if (res) {
                        message.success('操作成功')
                        emit('onSubmit', true)
                    } else {
                        message.success('操作失败')
                        emit('onSubmit', false)
                    }
                })
            }).catch((error) => {
                console.log('error', error);
            });
        };
        const resetForm = () => {
            formRef.value.resetFields();
        };
        return {
            form,
            rules,
            title,
            formRef,
            ...toRefs(data),
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
            //func
            onClose,
            onSubmit
        };
    },
});
</script>
<style lang="less" scoped>
.modal-wrap {
    .content {
        padding: 20px 10px 10px 20px;
        margin-top: 10px;

        .basic-info {
            .small-title {
                margin-bottom: 10px;
                font-family: Source Han Sans CN;
                font-size: 14px;
                font-weight: bold;
                color: #333333;
            }
        }
    }

    ::v-deep .ant-modal-footer {
        .btn {
            width: 64px;
            height: 34px;
            background-color: red;
        }
    }
}
</style>