<template>
    <div class="app-container">
        <!-- 工作量类别管理 -->
        <ComTable
            ref="comTableRef"
            :form-columns="formColumns"
            :table-columns="tableColumns"
            :load-data="listWorkloadCategoryAPI"
            :show-toolbar="true"
            :show-action="true"
            :action-columns="actionColumns"
        >
            <!-- 工具栏插槽 -->
            <template #toolbar>
                <ComButton type="primary" icon="Plus" @click="onHandleAdd">
                    新建工作量类别
                </ComButton>
            </template>
            <!-- 绩效单价列插槽 -->
            <template #unitPrice="{ row }">
                <span>￥{{ fenToYuan(row.unitPrice) }}</span>
            </template>
            <!-- 结算单价列插槽 -->
            <template #settlementUnitPrice="{ row }">
                <span>￥{{ fenToYuan(row.settlementUnitPrice) }}</span>
            </template>
        </ComTable>

        <ComDialog :dialog-config="dialogConfig" @closeDialogOuter="onCloseDialogOuter">
            <template #outerContent>
                <el-form
                    size="large"
                    label-width="auto"
                    :model="addAndEditForm"
                    ref="addAndEditFormRef"
                    :rules="addAndEditRules"
                >
                    <el-form-item label="工作量类别名称" prop="workloadCategoryName">
                        <el-input
                            clearable
                            maxlength="50"
                            show-word-limit
                            placeholder="请输入工作量类别名称"
                            v-model.trim="addAndEditForm.workloadCategoryName"
                        />
                    </el-form-item>
                    <el-form-item label="绩效单价" prop="unitPrice">
                        <el-input-number
                            style="width: 100%"
                            :min="0.1"
                            :max="10000"
                            :precision="2"
                            :step="10"
                            v-model="addAndEditForm.unitPrice"
                        >
                            <template #prefix>
                                <span>￥</span>
                            </template>
                        </el-input-number>
                    </el-form-item>

                    <el-form-item label="结算单价" prop="settlementUnitPrice">
                        <el-input-number
                            style="width: 100%"
                            :min="0.1"
                            :max="10000"
                            :precision="2"
                            :step="10"
                            v-model="addAndEditForm.settlementUnitPrice"
                        >
                            <template #prefix>
                                <span>￥</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input
                            type="textarea"
                            maxlength="200"
                            show-word-limit
                            placeholder="请输入备注"
                            v-model="addAndEditForm.remark"
                            :autosize="{ minRows: 4, maxRows: 8 }"
                        />
                    </el-form-item>
                </el-form>

                <el-row class="common-btn-row">
                    <ComButton plain type="info" @click="onHandleCancel">取消</ComButton>
                    <ComButton @click="onHandleSave">保存</ComButton>
                </el-row>
            </template>
        </ComDialog>
    </div>
</template>

<script setup name="Position">
import { ref, nextTick } from 'vue'
import {
    listWorkloadCategoryAPI,
    addWorkloadCategoryAPI,
    delWorkloadCategoryAPI,
    updateWorkloadCategoryAPI,
} from '@/api/basicManage/workloadCategory.js'
import { yuanToFen, fenToYuan } from '@/utils/ruoyi'
import { bus, BUS_EVENTS } from '@/utils/bus'
import config from './config'
import ComTable from '@/components/ComTable/index.vue'
import ComButton from '@/components/ComButton/index.vue'
import ComDialog from '@/components/ComDialog/index.vue'

const { formColumns, tableColumns, dialogConfig } = config
const { proxy } = getCurrentInstance()

const addAndEditFormRef = ref(null)
const comTableRef = ref(null)
const editId = ref(null)

// 定义初始表单数据函数
const getInitFormData = () => ({
    workloadCategoryName: '',
    unitPrice: 0.1,
    settlementUnitPrice: 0.1,
    remark: '',
})

const addAndEditForm = ref(getInitFormData())

const addAndEditRules = ref({
    workloadCategoryName: [{ required: true, message: '请输入工作量类别名称', trigger: 'blur' }],
    unitPrice: [{ required: true, message: '请输入绩效单价', trigger: 'blur' }],
    settlementUnitPrice: [{ required: true, message: '请输入结算单价', trigger: 'blur' }],
})

const actionColumns = [
    {
        label: '编辑',
        type: 'primary',
        link: true,
        handler: (row) => {
            const {
                remark,
                unitPrice,
                workloadCategoryId,
                workloadCategoryName,
                settlementUnitPrice,
            } = row
            editId.value = workloadCategoryId
            dialogConfig.outerTitle = '编辑工作量类别'
            dialogConfig.outerVisible = true
            // 使用 nextTick 确保在弹框渲染、表单组件挂载后再赋值
            nextTick(() => {
                addAndEditForm.value.workloadCategoryName = workloadCategoryName
                addAndEditForm.value.unitPrice = fenToYuan(unitPrice) // 分转元回显
                addAndEditForm.value.settlementUnitPrice = fenToYuan(settlementUnitPrice) // 分转元回显
                addAndEditForm.value.remark = remark
            })
        },
    },
    {
        label: '删除',
        type: 'danger',
        link: true,
        handler: (row) => {
            proxy.$modal.confirm('是否确认删除该工作量类别？').then(async () => {
                const result = await delWorkloadCategoryAPI({
                    workloadCategoryId: row.workloadCategoryId,
                })
                if (result.code === 200) {
                    proxy.$modal.msgSuccess('删除成功')
                    comTableRef.value?.refresh() // 刷新表格
                    bus.emit(BUS_EVENTS.REFRESH_OPTIONS, 'planWorkLoadCategoryOptions') // 刷新工作量类别下拉缓存
                }
            })
        },
    },
]

// 新增
const onHandleAdd = () => {
    editId.value = null
    dialogConfig.outerTitle = '新建工作量类别'
    dialogConfig.outerVisible = true
    // 重置表单数据
    addAndEditForm.value = getInitFormData()
    // 清除之前的校验信息
    nextTick(() => {
        addAndEditFormRef.value?.clearValidate()
    })
}

// 取消
const onHandleCancel = () => {
    addAndEditFormRef?.value?.resetFields() // 重置表单
    dialogConfig.outerVisible = false
}

// 保存
const onHandleSave = async () => {
    try {
        await addAndEditFormRef.value.validate()
        const API = editId.value ? updateWorkloadCategoryAPI : addWorkloadCategoryAPI
        const params = JSON.parse(JSON.stringify(addAndEditForm.value))
        params.unitPrice = yuanToFen(params.unitPrice) // 元转分提交
        params.settlementUnitPrice = yuanToFen(params.settlementUnitPrice) // 元转分提交
        editId.value ? (params.workloadCategoryId = editId.value) : null

        const result = await API(params)
        if (result.code === 200) {
            proxy.$modal.msgSuccess(editId.value ? '编辑成功' : '新增成功')
            addAndEditFormRef.value.resetFields() // 重置表单
            dialogConfig.outerVisible = false
            comTableRef.value?.refresh() // 刷新表格
            bus.emit(BUS_EVENTS.REFRESH_OPTIONS, 'planWorkLoadCategoryOptions') // 刷新工作量类别下拉缓存
        }
    } catch (error) {
        console.error('表单校验失败或请求错误:', error)
        return Promise.reject(error)
    }
}

const onCloseDialogOuter = (visible) => {
    dialogConfig.outerVisible = visible
    if (!visible) {
        addAndEditFormRef.value?.resetFields()
    }
}
</script>
