<template>
    <hc-card>
        <template #header>
            <div class="w-32">
                <el-select v-model="searchForm.category" placeholder="选择岗位类型" filterable clearable block>
                    <el-option v-for="item in categoryType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="ml-2 w-32">
                <el-select v-model="searchType" placeholder="选择搜索类型" filterable block>
                    <el-option label="岗位编号" value="postCode" />
                    <el-option label="岗位名称" value="postName" />
                </el-select>
            </div>
            <div class="ml-2 w-60">
                <hc-search-input v-model="searchName" placeholder="请输入关键词" @search="searchClick" />
            </div>
        </template>
        <template #extra>
            <el-button hc-btn type="primary" @click="addClick">新增</el-button>
            <el-button hc-btn type="danger" @click="delClick">删除</el-button>
        </template>
        <hc-table
            ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check
            :check-style="{ width: 29 }" :index-style="{ width: 60 }" @selection-change="tableCheckChange"
        >
            <template #tenantId="{ row }">
                {{ getTenantNmae(row.tenantId) }}
            </template>
            <template #category="{ row }">
                {{ getCategoryType(row.category) }}
            </template>
            <template #action="{ row }">
                <el-link type="warning" @click="editRowClick(row)">修改</el-link>
                <el-link v-del-com:[delRowClick]="row" type="danger">删除</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 新增/修改 -->
        <hc-dialog v-model="isDialogShow" widths="600px" is-footer-center :title="dialogTitle" @close="dialogClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="岗位类型：" prop="category">
                            <el-select v-model="formModel.category" placeholder="选择岗位类型" filterable clearable block>
                                <el-option v-for="item in categoryType" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="岗位编号：" prop="postCode">
                            <el-input v-model="formModel.postCode" clearable placeholder="请输入岗位编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="岗位名称：" prop="postName">
                            <el-input v-model="formModel.postName" clearable placeholder="请输入岗位名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="岗位排序：" prop="sort">
                            <el-input-number v-model="formModel.sort" :min="1" block controls-position="right" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="岗位描述：">
                            <el-input v-model="formModel.remark" :autosize="{ minRows: 4, maxRows: 8 }" type="textarea" placeholder="请输入岗位描述" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <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>
    </hc-card>
</template>

<script setup>
import { nextTick, onActivated, ref } from 'vue'
import { arrToId, formValidate, getArrValue } from 'js-fast-way'
import { getDictionaryData } from '~uti/tools'
import { HcDelMsg } from 'hc-vue3-ui'
import tenantApi from '~api/system/tenant'
import mainApi from '~api/system/post'

//激活
onActivated(() => {
    searchForm.value.current = 1
    getDataApi()
})

const getDataApi = async () => {
    await getPostCategory()
    await getTenantList()
    getTableData().then()
}

//搜索表单
const searchType = ref('postCode')
const searchName = ref('')
const searchForm = ref({ current: 1, size: 30, total: 0 })

//获取岗位类型
const categoryType = ref([])
const getPostCategory = async () => {
    categoryType.value = await getDictionaryData('post_category')
}
const getCategoryType = (id) => {
    const item = categoryType.value.find((item) => item.value === id)
    return item ? item.label : id
}

//获取租户列表
const tenantList = ref([])
const getTenantList = async () => {
    const { data } = await tenantApi.getSelect()
    tenantList.value = getArrValue(data)
}
const getTenantNmae = (id) => {
    const item = tenantList.value.find((item) => item.tenantId === id)
    return item ? item.tenantName : id
}

//搜索
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: 'tenantId', name: '所属租户' },
    { key: 'category', name: '岗位类型' },
    { key: 'postCode', name: '岗位编号' },
    { key: 'postName', name: '岗位名称' },
    { key: 'sort', name: '岗位排序', width: 80, align: 'center' },
    { key: 'action', name: '操作', width: 100, align: 'center' },
])

//获取表格数据
const tableLoading = ref(true)
const tableData = ref([{}])
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const form = {
        ...searchForm.value,
        total: null,
    }
    if (searchName.value) {
        form[searchType.value] = searchName.value
    }
    const { data } = await mainApi.page(form)
    tableLoading.value = false
    tableData.value = getArrValue(data?.records)
    searchForm.value.total = data?.total ?? 0
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheckChange = (rows) => {
    tableCheckKeys.value = rows
}

//新增/修改 弹窗
const isDialogShow = ref(false)
const dialogTitle = ref('')

//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    category: {
        required: true,
        trigger: 'blur',
        message: '请选择岗位类型',
    },
    postCode: {
        required: true,
        trigger: 'blur',
        message: '请输入岗位编号',
    },
    postName: {
        required: true,
        trigger: 'blur',
        message: '请输入岗位名称',
    },
    sort: {
        required: true,
        trigger: 'blur',
        message: '请输入字典排序',
    },
}

//新增
const addClick = () => {
    dialogTitle.value = '新增岗位'
    formModel.value = { sort: 1 }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//修改
const editRowClick = (row) => {
    formModel.value = {}
    dialogTitle.value = '修改岗位'
    formModel.value = { ...row }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//删除
const delRowClick = async ({ item }, resolve) => {
    const { isRes } = await mainApi.del(item.id)
    resolve() //关闭弹窗
    if (!isRes) return
    window.$message.success('删除成功')
    getTableData().then()
}

//批量删除
const delClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请选择要删除的数据')
        return false
    }
    //确认删除
    HcDelMsg(async (resolve) => {
        //发起请求
        const ids = arrToId(rows)
        const { isRes } = await mainApi.del(ids)
        resolve() //关闭弹窗
        if (!isRes) return
        window.$message.success('删除成功')
        getTableData().then()
    })
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const formRes = await formValidate(formRef.value)
    if (!formRes) return false
    submitLoading.value = true
    //发起请求
    const { isRes } = await mainApi.submit(formModel.value)
    submitLoading.value = false
    if (!isRes) return
    dialogClose()
    window?.$message?.success('操作成功')
    getTableData().then()
}

//关闭弹窗
const dialogClose = () => {
    isDialogShow.value = false
    submitLoading.value = false
    formModel.value = {}
}
</script>
