<template>
    <hc-dialog v-model="isShow" ui="hc-user-data-dialog-box" widths="800px" :padding="false" :title="`${isNullES(rowInfo.id) ? '新增' : '编辑'}用户信息`" is-footer-center @close="dialogClose">
        <el-tabs tab-position="left" class="hc-user-data-dialog h-full w-full">
            <el-tab-pane label="基础信息">
                <el-form ref="formRef1" :model="formModel" :rules="formRules1" label-position="top" label-width="auto">
                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="登录账号：" prop="account">
                                <el-input v-model="formModel.account" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="所属租户：" prop="tenantId">
                                <el-select v-model="formModel.tenantId" filterable block placeholder="选择所属租户" @change="tenantSelectChange">
                                    <el-option v-for="item in tenantSelect" :key="item.tenantId" :label="item.tenantName" :value="item.tenantId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="isNullES(formModel.id)" :span="12">
                            <el-form-item label="登录密码：" prop="password">
                                <el-input v-model="formModel.password" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="isNullES(formModel.id)" :span="12">
                            <el-form-item label="确认密码：" prop="password2">
                                <el-input v-model="formModel.password2" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="用户平台：" prop="userType">
                                <el-checkbox-group v-model="formUserType" @change="formUserTypeChange">
                                    <el-checkbox v-for="item in userTypeData" :key="item.value" :label="item.label" :value="item.value" border />
                                </el-checkbox-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="详细信息">
                <el-form ref="formRef2" :model="formModel" :rules="formRules2" label-position="top" label-width="auto">
                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="用户姓名：" prop="realName">
                                <el-input v-model="formModel.realName" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="手机号码：" prop="phone">
                                <el-input v-model="formModel.phone" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="身份证号码：">
                                <el-input v-model="formModel.idNumber" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="所属部门：" prop="deptId">
                                <el-tree-select
                                    v-model="formModel.deptId" placeholder="选择所属部门" :data="deptTreeData" :props="deptTreeProps"
                                    clearable filterable check-strictly block :render-after-expand="false" @node-click="deptTreeClick"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="证书编号：">
                                <el-input v-model="formModel.accCode" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="允许登录：" prop="status">
                                <el-select v-model="formModel.status" block placeholder="是否允许登录">
                                    <el-option label="是" :value="1" />
                                    <el-option label="否" :value="0" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="单位名称：">
                                <el-input v-model="formModel.companyName" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="职位：">
                                <el-input v-model="formModel.position" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="职能描述">
                <div class="relative overflow-hidden">
                    <el-row :gutter="14">
                        <el-col :span="7">
                            <el-select v-model="relatedProjectForm.projectId" filterable clearable block placeholder="项目" @change="projectChange" @clear="projectClear">
                                <el-option v-for="(item) in projectList" :key="item.id" :label="item.projectName" :value="item.id" />
                            </el-select>
                        </el-col>
                        <el-col :span="7">
                            <el-select v-model="relatedProjectForm.contractId" filterable clearable block placeholder="合同段">
                                <el-option v-for="(item) in contractList" :key="item.id" :label="item.contractName" :value="item.id" />
                            </el-select>
                        </el-col>
                        <el-col :span="6">
                            <el-select v-model="relatedProjectForm.roleId" filterable clearable block placeholder="角色类型">
                                <el-option v-for="(item) in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
                            </el-select>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="success" @click="addRelatedProject">确认添加</el-button>
                        </el-col>
                    </el-row>
                </div>
                <el-divider border-style="dashed" />
                <div v-for="(item, index) in userProjectContract" :key="index" class="relative mb-[14px] overflow-hidden">
                    <el-row :gutter="14">
                        <el-col :span="7">
                            <el-input v-model="item.projectName" disabled />
                        </el-col>
                        <el-col :span="7">
                            <el-select :model-value="item.userContractId" popper-class="user-project-contract" filterable block>
                                <el-option v-for="(items, indexs) in item.dataInfo" :key="indexs" :label="items.contractName" :value="items.id">
                                    <div class="hc-flex" @click.stop="userContractClick(items, index)">
                                        <div class="name flex-1 text-truncate">{{ items.contractName }}</div>
                                        <div class="del ml-10px text-red" @click.stop="delContractClick(items, index)">删除</div>
                                    </div>
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="6">
                            <el-input v-model="item.userRoleName" disabled />
                        </el-col>
                        <el-col :span="4">
                            <el-button type="danger" @click="delRelatedProject(item)">确定删除</el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-tab-pane>
        </el-tabs>
        <template #footer>
            <el-button hc-btn @click="dialogClose">取消</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
        </template>
    </hc-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { getDictionaryData } from '~uti/tools'
import { formValidate, getArrValue, getObjValue, isNullES, isPhone } from 'js-fast-way'
import tenantApi from '~api/system/tenant'
import projectApi from '~api/project/project'
import contractApi from '~api/project/contract'
import roleApi from '~api/system/role'
import deptApi from '~api/system/dept'
import mainApi from '~api/system/user'

const props = defineProps({
    info: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['close', 'finish'])

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})

//监听内容
const rowInfo = ref(props.info)
watch(() => props.info, (data) => {
    rowInfo.value = getObjValue(data)
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) {
        getDataApi()
    }
})

//获取数据
const getDataApi = () => {
    const info = getObjValue(rowInfo.value)
    const { id, userType } = info
    getTenantSelect()
    getUserTypeData()
    getProjectDataList()
    getRoleDataList()
    if (isNullES(id)) return
    formModel.value = { ...info, password: null }
    //分割为数组
    formUserType.value = isNullES(userType) ? [] : userType.split(',').map((item) => {
        return parseInt(item, 10) // 使用基数10进行解析，保证正确性
    })
    getDeptTreeData()
    getProjectContractList()
    console.log(info)
}

//获取租户信息
const tenantSelect = ref([])
const getTenantSelect = async () => {
    const { data } = await tenantApi.getSelect()
    tenantSelect.value = getArrValue(data)
}
const tenantSelectChange = () => {
    const { tenantId } = formModel.value
    const { tenantName } = tenantSelect.value.find((item) => {
        return item.tenantId === tenantId
    })
    formModel.value.tenantName = tenantName
    getDeptTreeData()
}

//获取用户平台
const userTypeData = ref([])
const getUserTypeData = async () => {
    userTypeData.value = await getDictionaryData('user_type')
}

//用户平台多选
const formUserType = ref([])
const formUserTypeChange = () => {
    const arr = formUserType.value
    formModel.value.userType = arr.join(',')
    //获取名称
    let userTypeNames = []
    for (let i = 0; i < arr.length; i++) {
        // eslint-disable-next-line array-callback-return
        userTypeData.value.filter((item) => {
            if (item.value === arr[i]) {
                userTypeNames.push(item.label)
            }
        })
    }
    formModel.value.userTypeName = userTypeNames.join(',')
}

//获取所属部门
const deptTreeData = ref([])
const deptTreeProps = { label: 'title' }
const getDeptTreeData = async () => {
    const { tenantId } = formModel.value
    if (isNullES(tenantId)) {
        deptTreeData.value = []
        return
    }
    const { data } = await deptApi.getDeptTree(tenantId)
    deptTreeData.value = getArrValue(data)
}

//所属部门
const deptTreeClick = ({ id, title }) => {
    formModel.value.deptId = id
    formModel.value.deptName = title
}

//获取当前配置好的参建项目
const userProjectContract = ref([])
const getProjectContractList = async () => {
    const { id } = formModel.value
    const { data } = await mainApi.getProjectContractList(id)
    const res = getArrValue(data)
    for (let i = 0; i < res.length; i++) {
        const arr = getArrValue(res[i].dataInfo)
        res[i].dataInfo = arr
        if (arr.length > 0) {
            const roleTypes = isNullES(arr[0].roleType) ? '' : arr[0].roleType + '|'
            res[i].userContractId = arr[0].id
            res[i].userRoleName = roleTypes + arr[0].roleName
        }
    }
    userProjectContract.value = res
}

//已配置的合同段选择
const userContractClick = ({ id, roleType, roleName }, index) => {
    const form = userProjectContract.value[index]
    const roleTypes = isNullES(roleType) ? '' : roleType + '|'
    form.userContractId = id
    form.userRoleName = roleTypes + roleName
}

//已配置的合同段删除
const delContractClick = async ({ id }) => {
    const { isRes } = await mainApi.removeUsersByIds(id)
    if (!isRes) return
    window.$message.success('删除成功')
    await getProjectContractList()
}

//删除参建项目
const delRelatedProject = async ({ userContractId }) => {
    const { isRes } = await mainApi.removeUserProjectInfoAndRoleById(userContractId)
    if (!isRes) return
    window.$message.success('删除成功')
    await getProjectContractList()
}

//职能描述相关数据
const projectList = ref([])
const getProjectDataList = async () => {
    const { data } = await projectApi.page({ current: 1, size: 999 })
    projectList.value = getArrValue(data?.records)
}

//获取合同段数据
const contractList = ref([])
const getContractDataList = async () => {
    const { projectId } = relatedProjectForm.value
    if (isNullES(projectId)) return
    const { data } = await contractApi.getList(projectId)
    contractList.value = getArrValue(data)
}

//获取角色
const roleList = ref([])
const getRoleDataList = async () => {
    const { data } = await roleApi.treeTow()
    roleList.value = getArrValue(data)
}

//职能描述，添加表单
const relatedProjectForm = ref({ projectId: '', contractId: '', roleId: '' })

//项目选择
const projectChange = () => {
    contractList.value = []
    relatedProjectForm.value.contractId = null
    getContractDataList()
}

//清空选择的项目
const projectClear = () => {
    relatedProjectForm.value.contractId = null
    contractList.value = []
}

//添加项目合同段
const addRelatedProject = async () => {
    const form = relatedProjectForm.value
    if (isNullES(form.projectId)) {
        window.$message.warning('请先选择项目')
    } else if (isNullES(form.contractId)) {
        window.$message.warning('请先选择合同段')
    } else if (isNullES(form.roleId)) {
        window.$message.warning('请先选择角色类型')
    } else {
        const { id } = formModel.value
        form.userId = id
        const { isRes } = await mainApi.saveUserInfoByProjectTow([form])
        if (!isRes) return
        window.$message.success('添加成功')
        relatedProjectForm.value = {}
        getProjectContractList().then()
    }
}

//表单
const formRef1 = ref(null)
const formRef2 = ref(null)
//表单内容
const formModel = ref({})
//表单效验
const formRules1 = {
    account: {
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入登录账号'))
            } else if (/^[a-z0-9]+$/i.test(value)) {
                callback()
            } else {
                callback(new Error('登录账号只能是字母和数字'))
            }
        },
    },
    tenantId: { required: true, trigger: 'blur', message: '请选择所属租户' },
    password: {
        trigger: 'blur',
        required: true,
        validator: (rule, value, callback) => {
            const { password2 } = formModel.value
            if (value === '') {
                callback(new Error('请输入密码'))
            } else if (value !== password2) {
                callback(new Error('两次输入密码不一致'))
            } else {
                callback()
            }
        },
    },
    password2: {
        required: true, trigger: 'blur',
        validator: (rule, value, callback) => {
            const { password } = formModel.value
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== password) {
                callback(new Error('两次输入密码不一致'))
            } else {
                callback()
            }
        },
    },
    userType: { required: true, trigger: 'blur', message: '请选择用户平台' },
}
const formRules2 = {
    realName: { required: true, trigger: 'blur', message: '请输入用户姓名' },
    phone: {
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入手机号'))
            } else if (isPhone(value)) {
                callback()
            } else {
                callback(new Error('请输入正确的手机号'))
            }
        },
    },
    idNumber: {
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (isNullES(value)) {
                callback()
            } else if (isPhone(value)) {
                callback()
            } else {
                callback(new Error('请输入正确的身份证号'))
            }
        },
    },
    deptId: { required: true, trigger: 'blur', message: '请选择所属部门' },
    status: { required: true, trigger: 'blur', message: '请选择是否允许登录' },
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const formRes1 = await formValidate(formRef1.value)
    const formRes2 = await formValidate(formRef2.value)
    if (!formRes1 || !formRes2) {
        window.$message.warning('请先完善表单')
        return false
    }
    submitLoading.value = true
    const form = formModel.value
    let res = {}
    if (isNullES(form.id)) {
        res = await mainApi.add(form)
    } else {
        delete form.password
        res = await mainApi.up(form)
    }
    const { isRes } = res
    submitLoading.value = false
    if (!isRes) return
    window.$message.success('操作成功')
    dialogClose()
    emit('finish')
}

//关闭弹窗
const dialogClose = () => {
    isShow.value = false
    formModel.value = {}
    userProjectContract.value = []
    submitLoading.value = false
    emit('close')
}
</script>

<style lang="scss">
.el-tabs.el-tabs--left.hc-user-data-dialog {
    position: relative;
    .el-tabs__header.is-left {
        margin-right: 0;
    }
    .el-tabs__content {
        position: relative;
        height: 100%;
        .el-tab-pane {
            position: relative;
            height: 100%;
            width: 100%;
            overflow: auto;
            padding: 10px 5px 10px 10px;
        }
    }
    .el-checkbox-group .el-checkbox.is-bordered {
        margin-right: 14px;
        margin-bottom: 14px;
    }
}
.user-project-contract .el-select-dropdown__item {
    padding: 0 20px;
}
.el-dialog.hc-new-dialog.hc-user-data-dialog-box {
    height: 500px;
    max-height: 500px;
}
</style>
