<template>
    <HcCard>
        <template #header>
            <div class="w-36 ml-2">
                <el-select v-model="searchForm.userId" block clearable filterable placeholder="员工姓名" size="large">
                    <el-option v-for="item in userList" :label="item.name" :value="item.id" />
                </el-select>
            </div>
            <div class="ml-4">
                <el-button type="primary" @click="searchClick" size="large">
                    <HcIcon name="search-2"/>
                    <span>搜索</span>
                </el-button>
            </div>
            <div class="ml-2">
                <el-button size="large" @click="resetClick">
                    <HcIcon name="close-circle"/>
                    <span>重置</span>
                </el-button>
            </div>
        </template>
        <template #extra>
            <el-button type="primary" @click="addRowClick" size="large">
                <HcIcon name="add"/>
                <span>新增</span>
            </el-button>
        </template>
        <HcTable :loading="tableLoading" :column="tableColumn" :datas="tableData">
            <template #conFileName="{row}">
                <div class="text-link text-blue" @click="viewPdf(row)">{{ row?.conFileName }}</div>
            </template>
            <template #action="{row, index}">
                <el-button type="primary" size="small" @click="editRowClick(row)">编辑</el-button>
                <el-button type="danger" size="small" @click="delRowClick(row)">删除</el-button>
            </template>
        </HcTable>
        <template #action>
            <HcPages :pages="searchForm" @change="pageChange"/>
        </template>

        <!--入职登记弹窗-->
        <HcDialog bgColor="#ffffff" isToBody widths="42rem" :show="formModal" title="入职登记"
                  :loading="formModalLoading" loadingText="保存中，请稍等" @close="formModalClose" @save="formModalSave"
        >
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="left" label-width="auto" size="large">
                <el-form-item label="员工姓名：" prop="userId">
                    <el-select v-model="formModel.userId" block filterable>
                        <el-option v-for="item in userList" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="离职时间：" prop="endDate">
                    <el-date-picker v-model="formModel.endDate" type="date" class="block" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                </el-form-item>
                <el-form-item label="离职原因：" prop="leReasion">
                    <el-input type="textarea" v-model="formModel.leReasion" :autosize="{ minRows: 4, maxRows: 6 }"/>
                </el-form-item>
                <el-form-item label="离职登记表：" v-if="formModel.fileUrl">
                    <HcFormUpload :src="formModel.fileUrl" @upload="formItemUpload"/>
                </el-form-item>
                <el-form-item label="离职登记表：" v-show="!formModel.fileUrl">
                    <HcUploadFile ref="uploadFileRef" drop :options="uploadOptions" @success="uploadFileSuccess" class="w-full"/>
                </el-form-item>
            </el-form>
        </HcDialog>

    </HcCard>
</template>

<script setup>
import {ref, onActivated} from 'vue'
import mainApi from "~api/people/contract";
import {getTokenHeader} from "~src/api/request/header";
import {getuserList} from "~api/other";
import {getObjValue, getArrValue, formValidate} from "js-fast-way"
import {delMessage} from "~uti/tools";

onActivated(() => {
    getuserListApi()
    getTableData()
})

//获取用户下拉数据
const userList = ref([])
const getuserListApi = async () => {
    const {data} = await getuserList()
    userList.value = getArrValue(data)
}

const searchForm = ref({
    type: 3, userId: null,
    current: 1, size: 20, total: 0
})

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

//重置搜索表单
const resetClick = () => {
    searchForm.value = {current: 1, size: 20, total: 0}
}

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

//表格参数
const tableLoading = ref(false)
const tableColumn = [
    {key: 'userName', name: '姓名'},
    {key: 'deptName', name: '部门'},
    {key: 'postName', name: '职位'},
    {key: 'endDate', name: '离职日期'},
    {key: 'leReasion', name: '离职原因'},
    {key: 'conFileName', name: '离职登记表'},
    {key: 'action', name: '操作', width: '150'}
]

//获取表格数据
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const {data} = await mainApi.page(searchForm.value)
    tableData.value = getArrValue(data['records'])
    searchForm.value.total = data['total'] || 0
    tableLoading.value = false
}

//删除
const delRowClick = (row) => {
    delMessage(async () => {
        const {error, code, msg} = await mainApi.remove({ids: row.id})
        if (!error && code === 200) {
            window.$message?.success(msg)
            getTableData().then()
        } else {
            window.$message?.error(msg)
        }
    })
}

//表单弹窗
const formModal = ref(false)
const formModalLoading = ref(false)

//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    userId: [{required: true, message: '请选择员工', trigger: 'change'}],
    endDate: [{required: true, message: '请选择离职日期', trigger: 'change'}],
    leReasion: [{required: true, message: '请输入离职原因', trigger: 'blur'}],
}

//新增
const addRowClick = () => {
    formModalLoading.value = false
    formModel.value = {type: 3}
    formModal.value = true
}

//编辑
const editRowClick = (row) => {
    formModalLoading.value = false
    formModel.value = row
    formModal.value = true
}

//上传配置
const uploadFileRef = ref(null)
const uploadOptions = {
    headers: getTokenHeader(),
    multiple: false,
    size: 50
}

//上传文件
const formItemUpload = () => {
    uploadFileRef.value?.selectFile();
}

// 文件上传成功的回调
const uploadFileSuccess = ({resData}) => {
    const { pdfUrl, originalName } = getObjValue(resData)
    formModel.value.fileUrl = pdfUrl
    formModel.value.conFileName = originalName
    uploadFileRef.value?.setModalShow(false);
}


//提交保存
const formModalSave = async () => {
    formModalLoading.value = true
    const isForm = await formValidate(formRef.value)
    if (!isForm) {
        formModalLoading.value = false
        return false
    }
    //发起请求
    const {error, code, msg} = await mainApi.submit({
        ...formModel.value,
        type: 3 //合同类型
    })
    //判断状态
    formModalLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('提交成功')
        formModalClose()
        getTableData().then()
    } else {
        window.$message?.error(msg)
    }
}

//关闭弹窗
const formModalClose = () => {
    formModal.value = false
    formModalLoading.value = false
}

//查看pdf
const viewPdf = ({fileUrl}) => {
    if (fileUrl) {
        window.open(fileUrl, '_blank')
    } else {
        window.$message.error('暂无文件')
    }
}
</script>
