<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                    <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width='100px'>
                                    <el-form-item label="项目名称" prop="projectId">
                                        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable filterable>
                                            <el-option v-for="item in projectInfoList" :key="item.projectId" :label="item.projectName" :value="item.projectId"/>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="项目经理" prop="managerId">
                                        <el-select v-model="queryParams.managerId" placeholder="请选择项目经理" clearable filterable>
                                            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"/>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="项目计划状态" prop="projectPlanStatus">
                                        <el-select v-model="queryParams.projectPlanStatus" placeholder="请选择项目计划状态" clearable >
                                            <el-option v-for="dict in project_plan_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
                                        </el-select>
                                    </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>
        </transition>

        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/erp:erpProjectPlan:add']">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:erpProjectPlan:edit']">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/erp:erpProjectPlan:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:erpProjectPlan:export']">导出</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
                </el-row>
            </template>

            <el-table v-loading="loading" border :data="erpProjectPlanList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                        <el-table-column label="项目计划ID" align="center" prop="projectPlanId" v-if="columns[0].visible"/>
                        <el-table-column label="项目名称" align="center" prop="projectName" width="200" v-if="columns[2].visible"/>
                        <el-table-column label="项目经理" align="center" prop="managerName" v-if="columns[3].visible"/>
                        <el-table-column label="部门负责人" align="center" prop="chargeName" v-if="columns[4].visible"/>
                        <el-table-column label="付款方式" align="center" prop="paymentMethod" v-if="columns[5].visible"/>
                        <el-table-column label="项目计划状态" align="center" prop="projectPlanStatus" v-if="columns[6].visible">
                            <template #default="scope">
                                    <dict-tag :options="project_plan_status" :value="scope.row.projectPlanStatus"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[7].visible"/>
                        <el-table-column label="合同名称" align="center" prop="contractName" width="200" v-if="columns[8].visible"/>
                        <el-table-column label="排序号" align="center" prop="sortOrder" v-if="columns[9].visible"/>
                        <el-table-column label="备注" align="center" prop="remark" v-if="columns[10].visible"/>
                        <el-table-column label="激活标识" align="center" prop="activeFlag" v-if="columns[11].visible">
                            <template #default="scope">
                                    <dict-tag :options="active_flag" :value="scope.row.activeFlag"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="创建人" align="center" prop="createBy" v-if="columns[12].visible"/>
                        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[13].visible">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                            </template>
                        </el-table-column>
                <el-table-column label="操作" align="center" width="150" fixed="right"  class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-tooltip content="查看" placement="top" v-if="scope.row.projectPlanStatus !== '1'">
                            <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)" v-hasPermi="['oa/erp:erpProjectPlan:query']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="修改" placement="top" v-if="scope.row.projectPlanStatus === '1'">
                            <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)" v-hasPermi="['oa/erp:erpProjectPlan:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="审批记录" placement="top" v-if="scope.row.projectPlanStatus === '2' || scope.row.projectPlanStatus === '3'">
                            <el-button link type="info" icon="View" @click="handleApprovalRecord(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-card>
        <!-- 审批记录 -->
        <ApprovalRecord ref="approvalRecordRef" />
        <!-- 添加或修改项目计划对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
            <el-form ref="erpProjectPlanFormRef" :model="form" :rules="rules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="项目名称" prop="projectId">
                            <el-select v-model="form.projectId" placeholder="请选择项目" filterable @change="handleProjectChangeInDialog">
                                <el-option v-for="item in projectInfoList" :key="item.projectId" :label="item.projectName" :value="item.projectId"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目经理" prop="managerId">
                            <el-select v-model="form.managerId" placeholder="请选择项目经理" filterable disabled>
                                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="部门负责人" prop="chargeId">
                            <el-select v-model="form.chargeId" placeholder="请选择部门负责人" filterable disabled>
                                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合同" prop="contractId">
                            <el-select v-model="form.contractId" placeholder="请选择合同" filterable clearable>
                                <el-option v-for="item in contractInfoList" :key="item.contractId" :label="item.contractName" :value="item.contractId"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="付款方式" prop="paymentMethod">
                            <el-input v-model="form.paymentMethod" placeholder="（如：3-3-3-1）" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目计划状态" prop="projectPlanStatus">
                            <el-select v-model="form.projectPlanStatus" placeholder="请选择项目计划状态">
                                <el-option v-for="dict in project_plan_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="排序号" prop="sortOrder">
                            <el-input v-model="form.sortOrder" placeholder="请输入排序号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="激活标识" prop="activeFlag">
                            <el-radio-group v-model="form.activeFlag">
                                <el-radio v-for="dict in active_flag" :key="dict.value" :value="dict.value">{{dict.label}}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="ErpProjectPlan" lang="ts">
    import { listErpProjectPlan, getErpProjectPlan, delErpProjectPlan, addErpProjectPlan, updateErpProjectPlan } from '@/api/oa/erp/erpProjectPlan';
    import { ErpProjectPlanVO, ErpProjectPlanQuery, ErpProjectPlanForm } from '@/api/oa/erp/erpProjectPlan/types';
    import { listUser } from '@/api/system/user';
    import { getErpProjectInfoList } from '@/api/oa/erp/projectInfo';
    import { getErpContractInfoList } from '@/api/oa/erp/contractInfo';
    import { useRouter } from 'vue-router';
    import ApprovalRecord from '@/components/Process/approvalRecord.vue';

    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const router = useRouter();
        const { active_flag, project_plan_status , project_phases, collection_stage} = toRefs<any>(proxy?.useDict('active_flag', 'project_plan_status', 'project_phases', 'collection_stage'));

    const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

    const erpProjectPlanList = ref<ErpProjectPlanVO[]>([]);
    const projectInfoList = ref<any[]>([]);
    const userList = ref<any[]>([]);
    const contractInfoList = ref<any[]>([]);
    const buttonLoading = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref<Array<string | number>>([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);

    const queryFormRef = ref<ElFormInstance>();
    const erpProjectPlanFormRef = ref<ElFormInstance>();

    const dialog = reactive<DialogOption>({
        visible: false,
        title: ''
    });

    // 列显隐信息
    const columns = ref<FieldOption[]>([
            { key: 0, label: `项目计划ID`, visible: false },
            { key: 1, label: `租户编号`, visible: false },
            { key: 2, label: `项目名称`, visible: true },
            { key: 3, label: `项目经理`, visible: true },
            { key: 4, label: `部门负责人`, visible: true },
            { key: 5, label: `付款方式`, visible: true },
            { key: 6, label: `项目计划状态`, visible: true },
            { key: 7, label: `流程状态`, visible: false },
            { key: 8, label: `合同名称`, visible: true },
            { key: 9, label: `排序号`, visible: false },
            { key: 10, label: `备注`, visible: false },
            { key: 11, label: `激活标识`, visible: false },
            { key: 12, label: `创建人`, visible: true },
            { key: 13, label: `创建时间`, visible: true },
    ]);

    const initFormData: ErpProjectPlanForm = {
                        projectPlanId: undefined,
                        projectId: undefined,
                        managerId: undefined,
                        chargeId: undefined,
                        paymentMethod: undefined,
                        projectPlanStatus: undefined,
                        flowStatus: undefined,
                        sortOrder: undefined,
                        contractId: undefined,
                        remark: undefined,
                        activeFlag: undefined,
    }
    const data = reactive<PageData<ErpProjectPlanForm, ErpProjectPlanQuery>>({
        form: {...initFormData},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
                            projectId: undefined,
                            managerId: undefined,
                            chargeId: undefined,
                            paymentMethod: undefined,
                            projectPlanStatus: undefined,
                            flowStatus: undefined,
                            sortOrder: undefined,
                            contractId: undefined,
                            activeFlag: undefined,
            params: {
            }
        },
        rules: {
                            projectPlanId: [
                            { required: true, message: "项目计划ID不能为空", trigger: "blur" }
                        ],
        }
    });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询项目计划列表 */
    const getList = async () => {
        loading.value = true;
        const res = await listErpProjectPlan(queryParams.value);
            erpProjectPlanList.value = res.rows;
        total.value = res.total;
        loading.value = false;
    }

    /** 获取项目列表 */
    const getProjectInfoList = async () => {
        const res = await getErpProjectInfoList({});
        projectInfoList.value = res.data;
    }

    /** 获取用户列表 */
    const getUserList = async () => {
        const res = await listUser({ pageNum: 1, pageSize: 9999 });
        userList.value = res.rows;
    }

    /** 获取合同列表 */
    const getContractInfoList = async () => {
        const res = await getErpContractInfoList({});
        contractInfoList.value = res.data;
    }

    /** 取消按钮 */
    const cancel = () => {
        reset();
        dialog.visible = false;
    }

    /** 表单重置 */
    const reset = () => {
        form.value = {...initFormData};
            erpProjectPlanFormRef.value?.resetFields();
    }

    /** 搜索按钮操作 */
    const handleQuery = () => {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    const resetQuery = () => {
        queryFormRef.value?.resetFields();
        handleQuery();
    }

    /** 多选框选中数据 */
    const handleSelectionChange = (selection: ErpProjectPlanVO[]) => {
        ids.value = selection.map(item => item.projectPlanId);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 对话框中处理项目选择变化，自动填充项目经理和部门负责人 */
    const handleProjectChangeInDialog = (projectId: number) => {
        if (!projectId) {
            form.value.managerId = undefined;
            form.value.chargeId = undefined;
            return;
        }
        const project = projectInfoList.value.find(p => p.projectId === projectId);
        if (project) {
            form.value.managerId = project.managerId;
            form.value.chargeId = project.chargeId;
        }
    }

    /** 新增按钮操作 */
    const handleAdd = () => {
        router.push('/oa/erp/erpProjectPlan/edit/0');
    }

    /** 查看按钮操作 */
    const handleView = (row: ErpProjectPlanVO) => {
        router.push(`/oa/erp/erpProjectPlan/view/${row.projectPlanId}?type=view`);
    }

    /** 编辑按钮操作 */
    const handleEdit = (row: ErpProjectPlanVO) => {
        router.push(`/oa/erp/erpProjectPlan/edit/${row.projectPlanId}?type=edit`);
    }

    // 查看审批记录
    const handleApprovalRecord = (row: ErpProjectPlanVO) => {
        approvalRecordRef.value?.init(row.projectPlanId);
    }

    /** 修改按钮操作（保留用于对话框形式） */
    const handleUpdate = async (row?: ErpProjectPlanVO) => {
        reset();
        const _projectPlanId = row?.projectPlanId || ids.value[0]
        const res = await getErpProjectPlan(_projectPlanId);
        Object.assign(form.value, res.data);
        dialog.visible = true;
        dialog.title = "修改项目计划";
    }

    /** 提交按钮 */
    const submitForm = () => {
            erpProjectPlanFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                if (form.value.projectPlanId) {
                    await updateErpProjectPlan(form.value).finally(() =>  buttonLoading.value = false);
                } else {
                    await addErpProjectPlan(form.value).finally(() =>  buttonLoading.value = false);
                }
                proxy?.$modal.msgSuccess("操作成功");
                dialog.visible = false;
                await getList();
            }
        });
    }

    /** 删除按钮操作 */
    const handleDelete = async (row?: ErpProjectPlanVO) => {
        const _projectPlanIds = row?.projectPlanId || ids.value;
        await proxy?.$modal.confirm('是否确认删除项目计划编号为"' + _projectPlanIds + '"的数据项？').finally(() => loading.value = false);
        await delErpProjectPlan(_projectPlanIds);
        proxy?.$modal.msgSuccess("删除成功");
        await getList();
    }

    /** 导出按钮操作 */
    const handleExport = () => {
        proxy?.download('oa/erp/erpProjectPlan/export', {
            ...queryParams.value
        }, `erpProjectPlan_${new Date().getTime()}.xlsx`)
    }

    onMounted(() => {
        getList();
        getProjectInfoList();
        getUserList();
        getContractInfoList();
    });
</script>
