<template>
    <div class="hc-page-box">
        <HcNewCard>
            <template #header>
                <div class="w-72">
                    <el-input v-model="searchForm.queryValue" clearable placeholder="请输入人员名称查询" @keyup="keyUpEvent" />
                </div>
                <div class="ml-2">
                    <el-button :disabled="tableData.length < 1" type="primary" @click="searchClick">
                        <HcIcon name="search-2" />
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <template #extra>
                <HcTooltip keys="tentative_laboratory_user_add">
                    <el-button hc-btn type="primary" @click="addFormModalClick">
                        <HcIcon name="add-circle" />
                        <span>新增</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_parameter_density_edit">
                    <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn type="primary" color="#12C060" style="color: white;" @click="editFormModalClick">
                        <HcIcon name="edit" />
                        <span>编辑</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="tentative_laboratory_user_del">
                    <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn color="#e03997" @click="delModalClick">
                        <HcIcon name="delete-bin-2" />
                        <span>删除</span>
                    </el-button>
                </HcTooltip>
            </template>
            <HcTable
                ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
                is-new :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                @selection-change="tableSelection"
            >
                <template #sex="{ row }">
                    <span>{{ row.sex === 1 ? '男' : '女' }}</span>
                </template>
                <template #status="{ row }">
                    <span>{{ row.status === 1 ? '在职' : '离职' }}</span>
                </template>
                <template #education="{ row }">
                    <span>{{ arrKeyValue(educationData, 'dictKey', 'dictValue', row.education) }}</span>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>
        </HcNewCard>

        <!-- 新增/编辑 -->
        <hc-new-dialog
            v-model="addEditFormModal" :is-close="false" :loading="addEditFormLoading"
            :title="`${addEditFormModel.id ? '编辑' : '新增'}人员档案`" widths="70rem" @close="addEditFormModalClose"
            @save="addEditFormClick"
        >
            <template #extra>
                <HcNewSwitch :datas="tabTypeTab" :keys="tabTypeKey" size="default" @change="tabTypeChange" />
            </template>
            <el-form
                ref="addEditFormRef" :model="addEditFormModel" :rules="addEditFormRules" label-width="auto"
                size="large"
            >
                <template v-if="tabTypeKey === 'tab1'">
                    <div class="hc-form-item">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="addEditFormModel.name" />
                        </el-form-item>
                        <el-form-item label="身份证" prop="idCard">
                            <el-input v-model="addEditFormModel.idCard" />
                        </el-form-item>
                        <el-form-item label="出生日期" prop="birthday">
                            <el-date-picker
                                v-model="addEditFormModel.birthday" :clearable="false" class="block"
                                type="date" value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                    </div>
                    <div class="hc-form-item">
                        <el-form-item label="性别">
                            <el-select v-model="addEditFormModel.sex" block>
                                <el-option :value="1" label="男" />
                                <el-option :value="2" label="女" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="毕业院校">
                            <el-input v-model="addEditFormModel.graduationSchool" />
                        </el-form-item>
                        <el-form-item label="专业">
                            <el-input v-model="addEditFormModel.major" />
                        </el-form-item>
                    </div>
                    <div class="hc-form-item">
                        <el-form-item label="学历">
                            <el-select v-model="addEditFormModel.education" block>
                                <el-option
                                    v-for="item in educationData" :label="item.dictValue"
                                    :value="item.dictKey"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="毕业日期">
                            <el-date-picker
                                v-model="addEditFormModel.graduationDate" :clearable="false" class="block"
                                type="date" value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                        <el-form-item label="入职时间">
                            <el-date-picker
                                v-model="addEditFormModel.entryTime" :clearable="false" class="block"
                                type="date" value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                    </div>
                    <div class="hc-form-item">
                        <el-form-item label="就职状态">
                            <el-select v-model="addEditFormModel.status" block>
                                <el-option :value="1" label="在职" />
                                <el-option :value="0" label="离职" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="职称">
                            <el-input v-model="addEditFormModel.jobTitleName" />
                        </el-form-item>
                        <el-form-item label="工作职务">
                            <el-input v-model="addEditFormModel.jobTitlePost" />
                        </el-form-item>
                    </div>
                    <div class="hc-form-item">
                        <el-form-item label="进场时间">
                            <el-date-picker
                                v-model="addEditFormModel.mobilizationTime" :clearable="false" class="block"
                                type="date" value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                        <el-form-item label="部门">
                            <el-input v-model="addEditFormModel.department" />
                        </el-form-item>
                        <el-form-item label="从事检测工作时间(月)">
                            <el-input v-model="addEditFormModel.workingTime" />
                        </el-form-item>
                    </div>
                    <div class="hc-form-item">
                        <el-form-item label="退场时间">
                            <el-date-picker
                                v-model="addEditFormModel.exitTime" :clearable="false" class="block"
                                type="date" value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                        <el-form-item label="劳动合同开始日期">
                            <el-date-picker
                                v-model="addEditFormModel.laborContractStartDate" :clearable="false" class="block"
                                type="date" value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                        <el-form-item label="劳动合同终止日期">
                            <el-date-picker
                                v-model="addEditFormModel.laborContractEndDate" :clearable="false" class="block"
                                type="date" value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                    </div>
                </template>
                <template v-if="tabTypeKey === 'tab2'">
                    <el-form-item label="证书编号">
                        <el-input v-model="addEditFormModel.certificateNo" />
                    </el-form-item>
                    <el-form-item label="持证类型">
                        <el-select v-model="addEditFormModel.certificateType" block>
                            <el-option label="检测员" value="1" />
                            <el-option label="检测工程师" value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="持证专业">
                        <el-select v-model="addEditFormModel.certificateMajor" block>
                            <el-option label="水运结构与地基" value="1" />
                            <el-option label="交通工具" value="2" />
                            <el-option label="水运材料" value="3" />
                            <el-option label="桥梁隧道工程" value="4" />
                            <el-option label="道路工程" value="5" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证书文件">
                        <FormItemUpload v-model="addEditFormModel.certificateUrl" />
                    </el-form-item>
                </template>
                <template v-if="tabTypeKey === 'tab3'">
                    <el-form-item label="记录日期">
                        <el-date-picker
                            v-model="addEditFormModel.workRecordDate" :clearable="false" class="block"
                            type="date" value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                    <el-form-item label="内容">
                        <el-input v-model="addEditFormModel.workContent" :autosize="{ minRows: 8 }" type="textarea" />
                    </el-form-item>
                </template>
            </el-form>
        </hc-new-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import dataApi from '~api/tentative/laboratory/user'
import FormItemUpload from './components/FormItemUpload.vue'
import { arrKeyValue, arrToId, formValidate, getArrValue, isIdCard } from 'js-fast-way'
import { getDictionary } from '~api/other'
import { HcDelMsg } from 'hc-vue3-ui'

//初始变量
const useAppState = useAppStore()

//全局变量
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)

//渲染完成
onMounted(() => {
    getTableData()
    getEducationType()
})

//获取学历类型
const educationData = ref([])
const getEducationType = async () => {
    const { data } = await getDictionary({
        code: 'trial_user_education',
    })
    const arrData = getArrValue(data)
    arrData.forEach(item => {
        item.dictKey = Number(item.dictKey)
    })
    educationData.value = arrData
}

//持证类型、持证专业


//搜索表单
const searchForm = ref({
    queryValue: null, current: 1, size: 20, total: 0,
})

//回车搜索
const keyUpEvent = (e) => {
    if (e.key === 'Enter') {
        searchForm.value.current = 1
        getTableData()
    }
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

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

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'name', name: '姓名', width: 100 },
    { key: 'department', name: '部门', width: 120 },
    { key: 'jobTitleName', name: '职称', width: 100 },
    { key: 'status', name: '就职状态', width: 80 },
    { key: 'entryTime', name: '入职时间', width: 140 },
    { key: 'workingTime', name: '从事检测工作（月）', width: 150 },
    { key: 'jobTitlePost', name: '工作职务', width: 120 },
    { key: 'idCard', name: '身份证号码', width: 180 },
    { key: 'birthday', name: '出生日期', width: 140 },
    { key: 'sex', name: '性别', width: 80 },
    { key: 'graduationSchool', name: '毕业院校' },
    { key: 'education', name: '学历', width: 120 },
    { key: 'major', name: '专业', width: 150 },
    { key: 'graduationDate', name: '毕业时间', width: 140 },
    { key: 'laborContractEndDate', name: '劳动合同终止日期', width: 140 },
    { key: 'mobilizationTime', name: '进场时间', width: 140 },
    { key: 'exitTime', name: '退场时间', width: 140 },
])

//获取数据
const tableLoading = ref(false)
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await dataApi.queryPage({
        projectId: projectId.value,
        contractId: contractId.value,
        ...searchForm.value,
    })
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        tableData.value.forEach((item) => {
            if (item?.workingTime == -1) {
                item.workingTime = ''
            }
        })
        searchForm.value.total = data.total || 0
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//新增表单
const addEditFormModal = ref(false)
const addFormModalClick = () => {
    addEditFormModel.value = {
        status: 1, sex: 1, certificateType: '1', certificateMajor: '1', education: 1,
    }
    addEditFormModal.value = true
}

//编辑表单
const editFormModalClick = () => {
    const keys = tableCheckedKeys.value
    if (keys.length === 1) {
        addEditFormModel.value = keys[0]
        addEditFormModel.value.certificateType = addEditFormModel.value.certificateType + ''
        addEditFormModel.value.certificateMajor = addEditFormModel.value.certificateMajor + ''
        addEditFormModal.value = true
    } else if (keys.length > 1) {
        window?.$message?.warning('只能选择一条数据编辑')
    }
}

//关闭表单
const addEditFormModalClose = () => {
    addEditFormModal.value = false
    addEditFormModel.value = {}
}

//类型tab数据和相关处理
const tabTypeKey = ref('tab1')
const tabTypeTab = ref([
    { key: 'tab1', name: '基本信息' },
    { key: 'tab2', name: '证书信息' },
    { key: 'tab3', name: '工作记录' },
])
const tabTypeChange = (item) => {
    tabTypeKey.value = item?.key
}

//新增/编辑 表单
const addEditFormRef = ref(null)
const addEditFormModel = ref({})
const addEditFormRules = {
    name: {
        required: true,
        trigger: 'blur',
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入姓名'))
            } else if (value.length > 5 || value.length < 2) {
                callback(new Error('姓名长度必须大于等于2并且小于等于5'))
            } else {
                callback()
            }
        },
    },
    idCard: {
        required: true,
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入身份证号码'))
            } else if (!isIdCard(value)) {
                callback(new Error('身份证号码格式错误'))
            } else {
                callback()
            }
        },
        trigger: 'blur',
    },
    birthday: {
        required: true,
        trigger: 'blur',
        message: '请选择出生日期',
    },
}

//新增/编辑 保存
const addEditFormLoading = ref(false)
const addEditFormClick = async () => {
    const validate = await formValidate(addEditFormRef.value)
    if (validate) {
        addEditFormLoading.value = true
        addEditFormModel.value.workingTime = Number(addEditFormModel.value.workingTime)
        const { error, code } = await dataApi.submitForm({
            ...addEditFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value,
        })
        //处理数据

        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            addEditFormModal.value = false
            addEditFormLoading.value = false
            await getTableData()
        }
        addEditFormModal.value = false
        addEditFormLoading.value = false
    }
}

//删除
const delModalClick = () => {
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                tableRemoveData()
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
    })

}

//批量删除
const tableRemoveData = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        const ids = arrToId(rows)
        //删除请求
        const { error, code } = await dataApi.removeData({
            projectId: projectId.value,
            contractId: contractId.value,
            ids: ids,
        })
        //处理数据
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            searchClick()
        }
    }
}
</script>

<style lang="scss" scoped>

</style>
