<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="项目ID" prop="projectId">
                                        <el-input v-model="queryParams.projectId" placeholder="请输入项目ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目计划ID" prop="projectPlanId">
                                        <el-input v-model="queryParams.projectPlanId" placeholder="请输入项目计划ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目阶段" prop="projectPhases">
                                        <el-input v-model="queryParams.projectPhases" placeholder="请输入项目阶段" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="计划开始时间" prop="planStartTime">
                                        <el-date-picker clearable
                                                        v-model="queryParams.planStartTime"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择计划开始时间"
                                        />
                                    </el-form-item>
                                    <el-form-item label="计划结束时间" prop="planEndTime">
                                        <el-date-picker clearable
                                                        v-model="queryParams.planEndTime"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择计划结束时间"
                                        />
                                    </el-form-item>
                                    <el-form-item label="付款节点ID" prop="paymentStageId">
                                        <el-input v-model="queryParams.paymentStageId" placeholder="请输入付款节点ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="预计回款比例(%)" prop="repaymentRate">
                                        <el-input v-model="queryParams.repaymentRate" placeholder="请输入预计回款比例(%)" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="预计回款金额" prop="repaymentAmount">
                                        <el-input v-model="queryParams.repaymentAmount" placeholder="请输入预计回款金额" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="预计回款时间" prop="repaymentTime">
                                        <el-date-picker clearable
                                                        v-model="queryParams.repaymentTime"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择预计回款时间"
                                        />
                                    </el-form-item>
                                    <el-form-item label="回款延期天数" prop="delayDay">
                                        <el-input v-model="queryParams.delayDay" placeholder="请输入回款延期天数" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="应收款日期" prop="receivableDate">
                                        <el-date-picker clearable
                                                        v-model="queryParams.receivableDate"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择应收款日期"
                                        />
                                    </el-form-item>
                                    <el-form-item label="原因说明" prop="reasonsExplanation">
                                        <el-input v-model="queryParams.reasonsExplanation" placeholder="请输入原因说明" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="进度备注" prop="scheduleRemark">
                                        <el-input v-model="queryParams.scheduleRemark" placeholder="请输入进度备注" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="实际开始时间" prop="realStartTime">
                                        <el-date-picker clearable
                                                        v-model="queryParams.realStartTime"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择实际开始时间"
                                        />
                                    </el-form-item>
                                    <el-form-item label="实际结束时间" prop="realEndTime">
                                        <el-date-picker clearable
                                                        v-model="queryParams.realEndTime"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择实际结束时间"
                                        />
                                    </el-form-item>
                                    <el-form-item label="排序号" prop="sortOrder">
                                        <el-input v-model="queryParams.sortOrder" placeholder="请输入排序号" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="激活标识" prop="activeFlag">
                                        <el-select v-model="queryParams.activeFlag" placeholder="请选择激活标识" clearable >
                                            <el-option v-for="dict in active_flag" :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:erpProjectPlanStage: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:erpProjectPlanStage: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:erpProjectPlanStage:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:erpProjectPlanStage: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="erpProjectPlanStageList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                        <el-table-column label="计划阶段ID" align="center" prop="planStageId" v-if="columns[0].visible"/>
                        <el-table-column label="项目ID" align="center" prop="projectId" v-if="columns[2].visible"/>
                        <el-table-column label="项目计划ID" align="center" prop="projectPlanId" v-if="columns[3].visible"/>
                        <el-table-column label="项目阶段" align="center" prop="projectPhases" v-if="columns[4].visible"/>
                        <el-table-column label="计划开始时间" align="center" prop="planStartTime" width="180" v-if="columns[5].visible">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.planStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="180" v-if="columns[6].visible">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="回款阶段" align="center" prop="paymentStageName" min-width="140" v-if="columns[7].visible">
                            <template #default="scope">
                                <span>{{ scope.row.paymentStageName || scope.row.paymentStageId || '-' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="预计回款比例(%)" align="center" prop="repaymentRate" v-if="columns[8].visible"/>
                        <el-table-column label="预计回款金额" align="center" prop="repaymentAmount" v-if="columns[9].visible"/>
                        <el-table-column label="预计回款时间" align="center" prop="repaymentTime" width="180" v-if="columns[10].visible">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.repaymentTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="回款延期天数" align="center" prop="delayDay" v-if="columns[11].visible"/>
                        <el-table-column label="应收款日期" align="center" prop="receivableDate" width="180" v-if="columns[12].visible">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.receivableDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="原因说明" align="center" prop="reasonsExplanation" v-if="columns[13].visible"/>
                        <el-table-column label="进度备注" align="center" prop="scheduleRemark" v-if="columns[14].visible"/>
                        <el-table-column label="实际开始时间" align="center" prop="realStartTime" width="180" v-if="columns[15].visible">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.realStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="实际结束时间" align="center" prop="realEndTime" width="180" v-if="columns[16].visible">
                            <template #default="scope">
                                <span>{{ parseTime(scope.row.realEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="排序号" align="center" prop="sortOrder" v-if="columns[17].visible"/>
                        <el-table-column label="备注" align="center" prop="remark" v-if="columns[18].visible"/>
                        <el-table-column label="激活标识" align="center" prop="activeFlag" v-if="columns[19].visible">
                            <template #default="scope">
                                    <dict-tag :options="active_flag" :value="scope.row.activeFlag"/>
                            </template>
                        </el-table-column>
                <el-table-column label="操作" align="center" fixed="right"  class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-tooltip content="修改" placement="top">
                            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:erpProjectPlanStage:edit']"></el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/erp:erpProjectPlanStage:remove']"></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>
        <!-- 添加或修改项目计划阶段对话框 -->
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
            <el-form ref="erpProjectPlanStageFormRef" :model="form" :rules="rules" label-width="120px">
                            <el-form-item label="项目ID" prop="projectId">
                                <el-input v-model="form.projectId" placeholder="请输入项目ID" />
                            </el-form-item>
                            <el-form-item label="项目计划ID" prop="projectPlanId">
                                <el-input v-model="form.projectPlanId" placeholder="请输入项目计划ID" />
                            </el-form-item>
                            <el-form-item label="项目阶段" prop="projectPhases">
                                <el-select v-model="form.projectPhases" placeholder="请选择项目阶段" clearable style="width: 100%">
                                    <el-option v-for="dict in project_phases" :key="dict.value" :label="dict.label" :value="dict.value"/>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="计划开始时间" prop="planStartTime">
                                <el-date-picker clearable
                                                v-model="form.planStartTime"
                                                type="datetime"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="请选择计划开始时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="计划结束时间" prop="planEndTime">
                                <el-date-picker clearable
                                                v-model="form.planEndTime"
                                                type="datetime"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="请选择计划结束时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="回款阶段" prop="paymentStageId">
                                <el-select v-model="form.paymentStageId" placeholder="请选择回款阶段" clearable filterable style="width: 100%">
                                    <el-option v-for="stage in paymentStageOptions" :key="stage.paymentStageId" :label="stage.stageName" :value="stage.paymentStageId"/>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="预计回款比例(%)" prop="repaymentRate">
                                <el-input v-model="form.repaymentRate" placeholder="请输入预计回款比例(%)" />
                            </el-form-item>
                            <el-form-item label="预计回款金额" prop="repaymentAmount">
                                <el-input v-model="form.repaymentAmount" placeholder="请输入预计回款金额" />
                            </el-form-item>
                            <el-form-item label="预计回款时间" prop="repaymentTime">
                                <el-date-picker clearable
                                                v-model="form.repaymentTime"
                                                type="datetime"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="请选择预计回款时间"
                                                @change="recalcReceivableDate(form)">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="回款延期天数" prop="delayDay">
                                <el-input v-model="form.delayDay" placeholder="请输入回款延期天数" @change="recalcReceivableDate(form)" />
                            </el-form-item>
                            <el-form-item label="应收款日期" prop="receivableDate">
                                <el-date-picker clearable
                                                v-model="form.receivableDate"
                                                type="datetime"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="请选择应收款日期">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="原因说明" prop="reasonsExplanation">
                                <el-input v-model="form.reasonsExplanation" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                            <el-form-item label="进度备注" prop="scheduleRemark">
                                <el-input v-model="form.scheduleRemark" placeholder="请输入进度备注" />
                            </el-form-item>
                            <el-form-item label="实际开始时间" prop="realStartTime">
                                <el-date-picker clearable
                                                v-model="form.realStartTime"
                                                type="datetime"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="请选择实际开始时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="实际结束时间" prop="realEndTime">
                                <el-date-picker clearable
                                                v-model="form.realEndTime"
                                                type="datetime"
                                                value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="请选择实际结束时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="排序号" prop="sortOrder">
                                <el-input v-model="form.sortOrder" placeholder="请输入排序号" />
                            </el-form-item>
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" placeholder="请输入备注" />
                            </el-form-item>
                            <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-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="ErpProjectPlanStage" lang="ts">
    import { listErpProjectPlanStage, getErpProjectPlanStage, delErpProjectPlanStage, addErpProjectPlanStage, updateErpProjectPlanStage } from '@/api/oa/erp/erpProjectPlanStage';
    import { ErpProjectPlanStageVO, ErpProjectPlanStageQuery, ErpProjectPlanStageForm } from '@/api/oa/erp/erpProjectPlanStage/types';
    import { getBasePaymentStageList } from '@/api/oa/base/paymentStage';
    import type { PaymentStageVO } from '@/api/oa/base/paymentStage/types';

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

    const paymentStageOptions = ref<PaymentStageVO[]>([]);

    const erpProjectPlanStageList = ref<ErpProjectPlanStageVO[]>([]);
    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 erpProjectPlanStageFormRef = ref<ElFormInstance>();

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

    // 列显隐信息
    const columns = ref<FieldOption[]>([
            { key: 0, label: `计划阶段ID`, visible: true },
            { key: 1, label: `租户编号`, visible: true },
            { key: 2, label: `项目ID`, visible: true },
            { key: 3, label: `项目计划ID`, visible: true },
            { key: 4, label: `项目阶段`, visible: true },
            { key: 5, label: `计划开始时间`, visible: true },
            { key: 6, label: `计划结束时间`, visible: true },
            { key: 7, label: `回款阶段`, visible: true },
            { key: 8, label: `预计回款比例(%)`, visible: true },
            { key: 9, label: `预计回款金额`, visible: true },
            { key: 10, label: `预计回款时间`, visible: true },
            { key: 11, label: `回款延期天数`, visible: true },
            { key: 12, label: `应收款日期`, visible: true },
            { key: 13, label: `原因说明`, visible: true },
            { key: 14, label: `进度备注`, visible: true },
            { key: 15, label: `实际开始时间`, visible: true },
            { key: 16, label: `实际结束时间`, visible: true },
            { key: 17, label: `排序号`, visible: true },
            { key: 18, label: `备注`, visible: true },
            { key: 19, label: `激活标识`, visible: true },
            { key: 20, label: `删除标志`, visible: true },
            { key: 21, label: `创建部门`, visible: true },
            { key: 22, label: `创建人`, visible: true },
            { key: 23, label: `创建时间`, visible: true },
            { key: 24, label: `更新人`, visible: true },
            { key: 25, label: `更新时间`, visible: true },
    ]);

    const initFormData: ErpProjectPlanStageForm = {
                        planStageId: undefined,
                        projectId: undefined,
                        projectPlanId: undefined,
                        projectPhases: undefined,
                        planStartTime: undefined,
                        planEndTime: undefined,
                        paymentStageId: undefined,
                        repaymentRate: undefined,
                        repaymentAmount: undefined,
                        repaymentTime: undefined,
                        delayDay: undefined,
                        receivableDate: undefined,
                        reasonsExplanation: undefined,
                        scheduleRemark: undefined,
                        realStartTime: undefined,
                        realEndTime: undefined,
                        sortOrder: undefined,
                        remark: undefined,
                        activeFlag: undefined,
    }
    const data = reactive<PageData<ErpProjectPlanStageForm, ErpProjectPlanStageQuery>>({
        form: {...initFormData},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
                            projectId: undefined,
                            projectPlanId: undefined,
                            projectPhases: undefined,
                            planStartTime: undefined,
                            planEndTime: undefined,
                            paymentStageId: undefined,
                            repaymentRate: undefined,
                            repaymentAmount: undefined,
                            repaymentTime: undefined,
                            delayDay: undefined,
                            receivableDate: undefined,
                            reasonsExplanation: undefined,
                            scheduleRemark: undefined,
                            realStartTime: undefined,
                            realEndTime: undefined,
                            sortOrder: undefined,
                            activeFlag: undefined,
            params: {
            }
        },
        rules: {
                            planStageId: [
                            { required: true, message: "计划阶段ID不能为空", trigger: "blur" }
                        ],
        }
    });

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

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

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

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

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

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

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

    /** 新增按钮操作 */
    const handleAdd = () => {
        reset();
        dialog.visible = true;
        dialog.title = "添加项目计划阶段";
    }

    /** 修改按钮操作 */
    const handleUpdate = async (row?: ErpProjectPlanStageVO) => {
        reset();
        const _planStageId = row?.planStageId || ids.value[0]
        const res = await getErpProjectPlanStage(_planStageId);
        Object.assign(form.value, res.data);
        dialog.visible = true;
        dialog.title = "修改项目计划阶段";
    }

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

    /** 根据回款时间与延期天数生成应收款日期 */
    const recalcReceivableDate = (row: any) => {
        if (!row) return;
        const time = row.repaymentTime;
        const delay = Number(row.delayDay || 0);
        if (!time) {
            row.receivableDate = undefined;
            return;
        }
        const base = new Date(time as string);
        if (isNaN(base.getTime())) {
            row.receivableDate = undefined;
            return;
        }
        const target = new Date(base.getTime());
        target.setDate(target.getDate() + delay);
        row.receivableDate = proxy?.parseTime ? proxy.parseTime(target, '{y}-{m}-{d} {h}:{i}:{s}') : target.toISOString().slice(0, 19).replace('T', ' ');
    }

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

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

    const loadPaymentStageOptions = async () => {
        try {
            const res = await getBasePaymentStageList({ pageNum: 1, pageSize: 9999 });
            paymentStageOptions.value = res.data || [];
        } catch {
            paymentStageOptions.value = [];
        }
    };

    onMounted(() => {
        loadPaymentStageOptions();
        getList();
    });
</script>
