<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="确定创建" :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>
                <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"/>
                    </el-form-item>
                    <el-form-item label="登录密码:" prop="password">
                        <el-input v-model="formModel.password" placeholder="请输入密码" autocomplete="new-password" show-password type="password"/>
                    </el-form-item>
                    <el-form-item label="确认密码:" prop="password1">
                        <el-input v-model="formModel.password1" placeholder="请输入确认密码" autocomplete="new-password" show-password type="password"/>
                    </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">
                                    <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.isLader" placeholder="是否为部门负责人">
                                        <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 prop="phone" label="手机号码:">
                        <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="日单价:">
                        <el-input v-model="formModel.key2"/>
                    </el-form-item>
                    <el-form-item label="启用状态:">
                        <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 {arrIndex, arrToId, isPhone} from "js-fast-way"
import mainApi from '~api/system/user';
import organizationApi from '~api/system/organization';
import {getArrValue} from "js-fast-way"
import {Plus, Delete} from '@element-plus/icons-vue'
import {delMessage} from "~uti/tools";

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: [{}],
})
const formRules = {
    projectId: [{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"
    },
    account: {
        required: true,
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入登录账号'))
            } else {
                callback()
            }
        },
        trigger: "blur"
    },
    password: {
        required: true,
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入新密码'))
            } else {
                callback()
            }
        },
        trigger: "blur"
    },
    password1: {
        required: true,
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请确认新密码'))
            } else {
                callback()
            }
        },
        trigger: "blur"
    },
}

//添加用户
const addUserClick = () => {
    formModel.value = {
        deptList: [{}],
    }
    postData.value = [{}]
    formModal.value = true
    getSectionData()
}

//编辑用户信息
const rowEidtClick = (row) => {
    row.password = ''
    const deptList = getArrValue(row.deptList)
    row.deptList = deptList
    if (deptList.length > 0){
        deptList.forEach(() => {
            postData.value.push({})
        })
    } else {
        row.deptList = [{}]
        postData.value = [{}]
    }
    formModel.value = row
    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] = []
        }
    }
}


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

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


//保存
const formModalSave = () => {
    console.log(formModel.value)
}

//关闭用户信息弹窗
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>
