<template>
    <HcCard>
        <template #header>
            <div class="w-40">
                <el-select v-model="searchForm.deptId" placeholder="选择岗位类型" clearable size="large">
                    <el-option v-for="item in searchOrganization" :label="item.deptName" :value="item.id"/>
                </el-select>
            </div>
            <div class="w-64 ml-3">
                <el-input v-model="searchForm.realName" size="large" placeholder="请输入名称搜索" clearable/>
            </div>
            <div class="ml-3">
                <el-button type="primary" @click="searchClick" size="large">
                    <HcIcon name="search-2"/>
                    <span>搜索</span>
                </el-button>
            </div>
        </template>
        <template #extra>
            <el-button type="primary" @click="addUserClick" size="large">
                <HcIcon name="add"/>
                <span>创建账户</span>
            </el-button>
            <el-button type="danger" @click="delClick" size="large" :disabled="tableCheckedKeys.length <= 0">
                <HcIcon name="delete-bin-2"/>
                <span>注销账户</span>
            </el-button>
        </template>
        <HcTable :column="tableColumn" :datas="tableData" isCheck @selection-change="tableSelectionChange" :loading="tableLoaing">
            <template #status="{row}">
                <span>{{row.status === 1 ? '启用': '停用'}}</span>
            </template>
            <template #action="{row}">
                <el-button size="small" type="primary" @click="rowEidtClick(row)">编辑</el-button>
            </template>
        </HcTable>
        <template #action>
            <HcPages :pages="searchForm" @change="pageChange"></HcPages>
        </template>

        <!--用户信息弹窗-->
        <HcDialog bgColor="#ffffff" isToBody isTable :show="formModal" :saveText="formModel.id ? '提交保存' : '确定创建'" :title="formModel.id ? '编辑账户' : '创建账户'"
                  @save="formModalSave" @close="formModalClose" widths="51rem"
        >
            <HcCardItem ui="hac-bg-grey" class="h-auto">
                <template #header>
                    <div class="hac-card-title">基础信息</div>
                </template>
                <template #extra>
                    <span class="text-sm text-orange" v-if="formModel.id">如果不需要修改密码，就请不要填写密码信息</span>
                </template>
                <el-form ref="formRef" :model="formModel" :rules="formRules" size="large" label-width="auto" label-position="left">
                    <el-form-item label="登录账号:" prop="account">
                        <el-input v-model="formModel.account" placeholder="仅支持英文或拼音" autocomplete="new-password" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')" :disabled="!!formModel.id"/>
                    </el-form-item>
                    <el-form-item label="登录密码:" :prop="formModel.id?'':'password'">
                        <el-input v-model="formModel.password" placeholder="请输入英文开头可包含数字的密码" autocomplete="new-password" show-password type="password" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"/>
                    </el-form-item>
                    <el-form-item label="确认密码:" :prop="formModel.id?'':'password1'">
                        <el-input v-model="formModel.password1" placeholder="请再次输入密码" autocomplete="new-password" show-password type="password" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')"/>
                    </el-form-item>
                </el-form>
            </HcCardItem>
            <HcCardItem ui="hac-bg-grey" class="h-auto mt-4">
                <template #header>
                    <div class="hac-card-title">机构信息</div>
                </template>
                <template v-for="(item, index) in formModel.deptList">
                    <el-form :ref="(el) => setFormItemRefs(el, index)" class="mt-4" :model="item" :rules="formRules" label-position="top" size="large">
                        <el-row :gutter="10">
                            <el-col :span="7">
                                <el-form-item prop="deptId">
                                    <el-select v-model="item.deptId" placeholder="选择部门" @change="initPostData($event, index)">
                                        <el-option v-for="item in sectionData" :label="item.deptName" :value="item.id"/>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item prop="postId" :getPostId="initPostData(item.deptId, index)">
                                    <el-select v-model="item.postId" placeholder="选择岗位">
                                        <el-option v-for="item in postData[index]" :label="item.deptName" :value="item.id"/>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item prop="principal">
                                    <el-select v-model="item.isLeader" placeholder="是否为部门负责人" :disabled="item.isLeaderDisabled" @change="isLeaderChange($event, index)">
                                        <el-option label="是" :value="1"/>
                                        <el-option label="否" :value="0"/>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="3">
                                <div class="form-organization-row-btn">
                                    <el-button type="primary" :icon="Plus" circle size="small" @click="addOrganizationClick(item)"/>
                                    <el-button type="danger" :icon="Delete" circle size="small" :disabled="index===0" @click="delOrganizationClick(index)"/>
                                </div>
                            </el-col>
                        </el-row>
                    </el-form>
                </template>
            </HcCardItem>

            <HcCardItem ui="hac-bg-grey" class="h-auto mt-4">
                <template #header>
                    <div class="hac-card-title">详细信息</div>
                </template>
                <el-form ref="formRef1" :model="formModel" :rules="formRules" label-position="left" label-width="auto" size="large">
                    <el-form-item label="用户姓名:" prop="realName">
                        <el-input v-model="formModel.realName"/>
                    </el-form-item>
                    <el-form-item label="手机号码:" prop="phone">
                        <el-input v-model="formModel.phone" placeholder="请输入绑定手机"/>
                    </el-form-item>
                    <el-form-item label="身份证号:">
                        <el-input v-model="formModel.idNumber"/>
                    </el-form-item>
                    <el-form-item label="日单价:" prop="oneMoney">
                        <el-input v-model="formModel.oneMoney"/>
                    </el-form-item>
                    <el-form-item label="启用状态:" prop="status">
                        <el-select v-model="formModel.status" class="block">
                            <el-option label="启用" :value="1"/>
                            <el-option label="停用" :value="0"/>
                        </el-select>
                    </el-form-item>
                </el-form>
            </HcCardItem>
        </HcDialog>

    </HcCard>
</template>

<script setup>
import {ref, onMounted} from "vue";
import mainApi from '~api/system/user';
import organizationApi from '~api/system/organization';
import {arrIndex, arrToId, formValidate, isPhone, getArrValue, isIdCard} from "js-fast-way"
import {Plus, Delete} from '@element-plus/icons-vue'
import {delMessage} from "~uti/tools";
import {useAppStore} from "~src/store";
const useAppState = useAppStore();

onMounted(() => {
    getTableData()
    getOrganization()
})

//获取搜索时的组织结构节点
const searchOrganization = ref([])
const getOrganization = async () => {
    const { error, code, data } = await organizationApi.getList({
        deptType: 3
    })
    if (!error && code === 200) {
        searchOrganization.value = getArrValue(data)
    } else {
        searchOrganization.value = []
    }
}

const searchForm = ref({deptId: null, realName: '', current: 1, size: 20, total: 0})

//分页被点击
const pageChange = ({current, size}) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//表格数据
const tableColumn = [
    {key: 'name', name: '用户名称'},
    {key: 'account', name: '账号ID'},
    {key: 'plaintextPassword', name: '密码'},
    {key: 'deptName', name: '所属部门'},
    {key: 'postName', name: '岗位'},
    {key: 'createTime', name: '创建日期'},
    {key: 'status', name: '启用状态'},
    {key: 'action', name: '操作', width: 100}
]
const tableData = ref([])

//获取表格数据
const tableLoaing = ref(false)
const getTableData = async()=>{
    tableLoaing.value = true
    const { error, code, data } = await mainApi.page(searchForm.value)
    tableLoaing.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total']
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

const tableCheckedKeys = ref([]);
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows
}

//用户信息弹窗
const formModal = ref(false)

//用户信息表单
const formRef = ref(null)
const formRef1 = ref(null)

//循环表单的ref
const formRefs = ref([])
const setFormItemRefs = (el, index) => {
    if (el) {
        let indexs = arrIndex(formRefs.value, 'index', index)
        if (indexs !== -1) {
            formRefs.value[index].ref = el
        } else {
            formRefs.value.push({index: index, ref: el});
        }
    }
}
//获取表单的ref
const getFormRef = async (index) => {
    const indexs = arrIndex(formRefs.value, 'index', index)
    return formRefs.value[indexs].ref
}

const formModel = ref({
    deptList: [{isLeader: 0}], status: 1
})
const formRules = {
    account: [{required: true, message: '请输入登录账号', trigger: 'blur'}],
    password: [{required: true, message: '请输入密码', trigger: 'blur'}],
    password1: [{required: true, message: '请输入确认密码', trigger: 'blur'}],
    deptId: [{required: true, message: '请选择选择部门', trigger: 'change'}],
    postId: [{required: true, message: '请选择选择岗位', trigger: 'change'}],
    isLeader: [{required: true, message: '请选择是否为部门负责人', trigger: 'change'}],
    oneMoney: [{required: true, message: '请输入日单价', trigger: 'blur'}],
    status: [{required: true, message: '请选择启用状态', trigger: 'change'}],
    phone: {
        required: true,
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入手机号'))
            } else if (!isPhone(value)) {
                callback(new Error('手机号码格式错误'))
            } else {
                callback()
            }
        },
        trigger: "blur"
    },
}

//添加用户
const addUserClick = () => {
    formModel.value = {
        deptList: [{isLeader: 0}],
        tenantId: useAppState.tenantId,
        status: 1,
        userType: 5
    }
    postData.value = [{}]
    formModal.value = true
    getSectionData()
}

//编辑用户信息
const rowEidtClick = (row) => {
    const deptList = getArrValue(row.deptList)
    //设置表单数据
    const form = {
        id: row.id,
        account: row.account,
        password: '',
        deptList: deptList,
        tenantId: useAppState.tenantId,
        realName: row.realName,
        phone: row.phone,
        idNumber: row.idNumber,
        oneMoney: row.oneMoney,
        status: row.status,
        userType: row.userType || 5
    }
    //如果部门列表为空，就添加一个空对象
    if (deptList.length > 0){
        deptList.forEach(() => {
            postData.value.push({})
        })
    } else {
        form.deptList = [{isLeader: 0}]
        postData.value = [{}]
    }
    //设置表单数据
    formModel.value = form
    formModal.value = true
    getSectionData()
}

//部门下拉数据
const sectionData = ref([])
const getSectionData = async () => {
    const { error, code, data } = await organizationApi.getList({deptType: 2})
    if (!error && code === 200) {
        sectionData.value = getArrValue(data)
    } else {
        sectionData.value = []
    }
}

//获取岗位数据
const postData = ref([])
const initPostData = async (id, index) => {
    if (id) {
        //获取岗位数据
        const { error, code, data } = await organizationApi.getList({parentId: id})
        if (!error && code === 200) {
            postData.value[index] = getArrValue(data)
        } else {
            postData.value[index] = []
        }
        //处理负责人限制
        let isLeader = 0;
        const deptList = formModel.value.deptList
        deptList.forEach((item, indexs) => {
            if (item.deptId === id) {
                //如果当前相同部门项的负责人存在，就全局存在
                if (item.isLeader === 1) {
                    isLeader = 1
                }
                //设置其它相同部门项的负责人
                if (indexs !== index) {
                    item.isLeader = isLeader
                    item.isLeaderDisabled = true
                }
            }
        })
        //设置当前项的负责人
        deptList[index].isLeader = isLeader
        deptList[index].isLeaderDisabled = false
    }
}

//是否为部门负责人
const isLeaderChange = (id, index) => {
    const deptList = formModel.value.deptList
    const deptId = deptList[index].deptId
    deptList.forEach((item) => {
        if (item.deptId === deptId) {
            item.isLeader = id
        }
    })
}

//新增组织
const addOrganizationClick = () => {
    formModel.value.deptList.push({isLeader: 0})
    postData.value.push({})
}

//删除组织
const delOrganizationClick = (index) => {
    formModel.value.deptList.splice(index, 1)
    postData.value.splice(index, 1)
}


//保存
const formModalSave = async () => {
    const isForm = await formValidate(formRef.value)
    const isForm1 = await formValidate(formRef1.value)
    if (!isForm || !isForm1) {
        window.$message?.error('请先完善表单信息')
        return
    }
    const form = formModel.value
    for (let i = 0; i < form.deptList.length; i++) {
        const refs = await getFormRef(i)
        const isRefs = await formValidate(refs)
        if (!isRefs) {
            window.$message?.error('请先完善表单信息')
            return
        }
    }
    //判断密码是否一致
    if (form.password && !form.password1) {
        window.$message?.error('请输入确认密码')
        return
    }
    if (!form.password && form.password1) {
        window.$message?.error('请输入登录密码')
        return
    }
    if (form.password && form.password1) {
        if (form.password !== form.password1) {
            window.$message?.error('密码不一致')
            return
        } else {
            form.plaintextPassword = form.password
        }
    }
    //效验身份证号码
    if (form.idNumber && !isIdCard(form.idNumber)) {
        window.$message?.error('身份证号码格式错误')
        return
    }
    //发起请求
    if (form.id) {
        formUpdateApi(form).then()
    } else {
        formSubmitApi(form).then()
    }
}

//新增用户
const formSubmitApi = async (form) => {
    const {error, code, msg} = await mainApi.submit({
        ...form,
        name: form.realName,
    })
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('提交成功')
        getTableData().then()
        formModalClose()
    } else {
        window.$message?.error(msg)
    }
}

//修改用户
const formUpdateApi = async (form) => {
    const {error, code, msg} = await mainApi.update({
        ...form,
        name: form.realName,
    })
    //判断状态
    if (!error && code === 200) {
        window.$message?.success('提交成功')
        getTableData().then()
        formModalClose()
    } else {
        window.$message?.error(msg)
    }
}

//关闭用户信息弹窗
const formModalClose = () => {
    formModal.value = false
    formModel.value = {}
}

//删除用户
const delClick = () => {
    delMessage(async () => {
        const ids = arrToId(tableCheckedKeys.value)
        const { error, code, msg } = await mainApi.remove(ids)
        if (!error && code === 200) {
            window?.$message?.success(msg)
            getTableData().then()
        } else {
            window?.$message?.error(msg)
        }
    })
}
</script>

<style lang="scss">
.hc-card-item-box.h-auto {
    height: auto;
}
.form-organization-row-btn {
    position: relative;
    margin-left: 8px;
    top: 7px;
    .el-button + .el-button {
        margin-left: 18px;
    }
}
</style>
