<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="项目编号" prop="projectCode">
              <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类别" prop="projectCategory">
              <el-select v-model="queryParams.projectCategory" placeholder="请选择项目类别" clearable>
                <el-option v-for="dict in project_category" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!--                                    <el-form-item label="变更次数" prop="changeNumber">
                                        <el-input v-model="queryParams.changeNumber" placeholder="请输入变更次数" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目经理ID" prop="projectManagerId">
                                        <el-input v-model="queryParams.projectManagerId" placeholder="请输入项目经理ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目经理姓名" prop="projectManagerName">
                                        <el-input v-model="queryParams.projectManagerName" placeholder="请输入项目经理姓名" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="部门负责人ID" prop="deptHeadId">
                                        <el-input v-model="queryParams.deptHeadId" placeholder="请输入部门负责人ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="部门负责人姓名" prop="deptHeadName">
                                        <el-input v-model="queryParams.deptHeadName" placeholder="请输入部门负责人姓名" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="分管副总ID" prop="responsibleVpId">
                                        <el-input v-model="queryParams.responsibleVpId" placeholder="请输入分管副总ID" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="分管副总姓名" prop="responsibleVpName">
                                        <el-input v-model="queryParams.responsibleVpName" placeholder="请输入分管副总姓名" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="申请变更时间" prop="applyChangeDate">
                                        <el-date-picker clearable
                                                        v-model="queryParams.applyChangeDate"
                                                        type="date"
                                                        value-format="YYYY-MM-DD"
                                                        placeholder="请选择申请变更时间"
                                        />
                                    </el-form-item>
                                    <el-form-item label="项目合同额" prop="contractAmount">
                                        <el-input v-model="queryParams.contractAmount" placeholder="请输入项目合同额" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目合同净额" prop="contractNetAmount">
                                        <el-input v-model="queryParams.contractNetAmount" placeholder="请输入项目合同净额" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="变更原因" prop="changeReason">
                                        <el-input v-model="queryParams.changeReason" placeholder="请输入变更原因" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="后续工作" prop="followUpWork">
                                        <el-input v-model="queryParams.followUpWork" placeholder="请输入后续工作" clearable @keyup.enter="handleQuery" />
                                    </el-form-item>
                                    <el-form-item label="项目变更状态" prop="projectChangeStatus">
                                        <el-select v-model="queryParams.projectChangeStatus" placeholder="请选择项目变更状态" clearable >
                                            <el-option v-for="dict in project_change_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
                                        </el-select>
                                    </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:erpProjectChange: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:erpProjectChange: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:erpProjectChange:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:erpProjectChange: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="erpProjectChangeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" v-if="columns[0].visible" />
        <el-table-column label="项目变更编号" align="center" prop="projectChangeCode" width="180" v-if="columns[1].visible" />
        <el-table-column label="项目ID" align="center" prop="projectId" width="120" v-if="columns[2].visible" />
        <el-table-column label="项目编号" align="center" prop="projectCode" width="150" v-if="columns[3].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" width="200" show-overflow-tooltip v-if="columns[4].visible" />
        <el-table-column label="项目类别" align="center" prop="projectCategory" width="150" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="project_category" :value="scope.row.projectCategory" />
          </template>
        </el-table-column>
        <el-table-column label="变更类型" align="center" prop="changeType" width="100" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="change_type" :value="scope.row.changeType ? scope.row.changeType.split(',') : []" />
          </template>
        </el-table-column>
        <el-table-column label="变更次数" align="center" prop="changeNumber" width="80" v-if="columns[7].visible" />
        <el-table-column label="项目经理ID" align="center" prop="projectManagerId" width="80" v-if="columns[8].visible" />
        <el-table-column label="项目经理" align="center" prop="projectManagerName" width="100" show-overflow-tooltip v-if="columns[9].visible" />
        <el-table-column label="部门负责人ID" align="center" prop="deptHeadId" width="140" v-if="columns[10].visible" />
        <el-table-column label="部门负责人" align="center" prop="deptHeadName" width="140" show-overflow-tooltip v-if="columns[11].visible" />
        <el-table-column label="分管副总ID" align="center" prop="responsibleVpId" width="140" v-if="columns[12].visible" />
        <el-table-column label="分管副总姓名" align="center" prop="responsibleVpName" width="160" show-overflow-tooltip v-if="columns[13].visible" />
        <el-table-column label="申请变更时间" align="center" prop="applyChangeDate" width="180" v-if="columns[14].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyChangeDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目合同额" align="center" prop="contractAmount" width="150" v-if="columns[15].visible" />
        <el-table-column label="项目合同净额" align="center" prop="contractNetAmount" width="150" v-if="columns[16].visible" />
        <el-table-column label="项目当前情况" align="center" prop="currentStatus" min-width="200" show-overflow-tooltip v-if="columns[17].visible" />
        <el-table-column label="变更原因" align="center" prop="changeReason" min-width="200" show-overflow-tooltip v-if="columns[18].visible" />
        <el-table-column label="后续工作" align="center" prop="followUpWork" min-width="200" show-overflow-tooltip v-if="columns[19].visible" />
        <el-table-column label="项目变更状态" align="center" prop="projectChangeStatus" width="140" v-if="columns[20].visible">
          <template #default="scope">
            <dict-tag :options="project_change_status" :value="scope.row.projectChangeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" width="140" v-if="columns[21].visible">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="180" show-overflow-tooltip v-if="columns[22].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" width="120" v-if="columns[23].visible">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag" />
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createName" width="140" v-if="columns[26].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[27].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" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- 查看按钮：非草稿状态显示 -->
            <el-tooltip v-if="scope.row.projectChangeStatus !== '1'" content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <!-- 修改按钮：仅草稿状态显示 -->
            <el-tooltip v-if="scope.row.projectChangeStatus === '1'" content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:erpProjectChange:edit']"></el-button>
            </el-tooltip>
            <!-- 新增变更按钮：仅在该项目最新且已完成的变更记录上显示 -->
            <el-tooltip v-if="isLatestCompletedChange(scope.row)" content="新增变更" placement="top">
              <el-button link type="success" icon="Plus" @click="handleAddChange(scope.row)" v-hasPermi="['oa/erp:erpProjectChange:add']"></el-button>
            </el-tooltip>
            <!-- 审批记录按钮：审批中或完成状态显示 -->
            <el-tooltip v-if="scope.row.projectChangeStatus === '2' || scope.row.projectChangeStatus === '3'" content="审批记录" placement="top">
              <el-button link type="info" icon="DocumentCopy" @click="handleApprovalRecord(scope.row)"></el-button>
            </el-tooltip>
            <!-- 删除按钮：仅草稿状态显示 -->
            <el-tooltip v-if="scope.row.projectChangeStatus === '1'" content="删除" placement="top">
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa/erp:erpProjectChange: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>
  </div>
</template>

<script setup name="ErpProjectChange" lang="ts">
import { delErpProjectChange, listErpProjectChange } from '@/api/oa/erp/erpProjectChange';
import { ErpProjectChangeQuery, ErpProjectChangeVO } from '@/api/oa/erp/erpProjectChange/types';
import { useRouter } from 'vue-router';

const router = useRouter();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { active_flag, change_type, project_change_status, project_category, wf_business_status } = toRefs<any>(
  proxy?.useDict('active_flag', 'change_type', 'project_change_status', 'project_category', 'wf_business_status')
);

// 项目变更列表数据（表格数据源）
const erpProjectChangeList = ref<ErpProjectChangeVO[]>([]);
// 记录每个项目最新且已完成的变更次数，用于控制“新增变更”按钮显示
const latestCompletedChangeMap = ref<Record<string, number>>({});
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 columns = ref<FieldOption[]>([
  { key: 0, label: `序号`, visible: true },
  { key: 1, label: `项目变更编号`, visible: true },
  { key: 2, label: `项目ID`, visible: false },
  { key: 3, label: `项目编号`, 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: `项目经理ID`, visible: false },
  { key: 9, label: `项目经理`, visible: true },
  { key: 10, label: `部门负责人ID`, visible: false },
  { key: 11, label: `部门负责人`, visible: true },
  { key: 12, label: `分管副总ID`, visible: false },
  { key: 13, label: `分管副总姓名`, visible: false },
  { key: 14, label: `申请变更时间`, visible: true },
  { key: 15, label: `项目合同额`, visible: false },
  { key: 16, label: `项目合同净额`, visible: false },
  { key: 17, label: `项目当前情况`, visible: false },
  { key: 18, label: `变更原因`, visible: false },
  { key: 19, label: `后续工作`, visible: false },
  { key: 20, label: `项目变更状态`, visible: true },
  { key: 21, label: `流程状态`, visible: false },
  { key: 22, label: `备注`, visible: false },
  { key: 23, label: `激活标识`, visible: false },
  { key: 24, label: `删除标志`, visible: false },
  { key: 25, label: `创建部门`, visible: false },
  { key: 26, label: `创建人`, visible: true },
  { key: 27, label: `创建时间`, visible: true },
  { key: 28, label: `更新人`, visible: false },
  { key: 29, label: `更新时间`, visible: false }
]);

// 查询表单参数（分页+筛选条件），与页面搜索区域绑定
const data = reactive<{ queryParams: ErpProjectChangeQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: undefined,
    projectCode: undefined,
    projectName: undefined,
    projectCategory: undefined,
    changeType: undefined,
    changeNumber: undefined,
    projectManagerId: undefined,
    projectManagerName: undefined,
    deptHeadId: undefined,
    deptHeadName: undefined,
    responsibleVpId: undefined,
    responsibleVpName: undefined,
    applyChangeDate: undefined,
    contractAmount: undefined,
    contractNetAmount: undefined,
    currentStatus: undefined,
    changeReason: undefined,
    followUpWork: undefined,
    projectChangeStatus: undefined,
    flowStatus: undefined,
    activeFlag: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);

/** 查询项目变更申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listErpProjectChange(queryParams.value);
  erpProjectChangeList.value = res.rows;
  total.value = res.total;
  // 先按项目统计每个项目最新的变更次数（changeNumber 最大值）
  const latestNumberMap: Record<string, number> = {};
  erpProjectChangeList.value.forEach((item) => {
    const pid = String(item.projectId);
    const num = item.changeNumber ?? 0;
    if (!latestNumberMap[pid] || num > latestNumberMap[pid]) {
      latestNumberMap[pid] = num;
    }
  });
  // 再从中筛选出“状态为已完成(3)且为最新一次变更”的记录，用于控制是否允许继续新增变更
  const completedMap: Record<string, number> = {};
  erpProjectChangeList.value.forEach((item) => {
    if (item.projectChangeStatus === '3') {
      const pid = String(item.projectId);
      const num = item.changeNumber ?? 0;
      if (latestNumberMap[pid] === num) {
        completedMap[pid] = num;
      }
    }
  });
  latestCompletedChangeMap.value = completedMap;
  loading.value = false;
};

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  // 跳转到编辑页面（新增模式）
  router.push('/oa/erp/erpProjectChange/edit/0');
};

/** 修改按钮操作 */
const handleUpdate = (row?: ErpProjectChangeVO) => {
  const _projectChangeId = row?.projectChangeId || ids.value[0];
  // 跳转到编辑页面（编辑模式）
  router.push(`/oa/erp/erpProjectChange/edit/${_projectChangeId}`);
};

/** 查看按钮操作 */
const handleView = (row: ErpProjectChangeVO) => {
  // 跳转到查看页面（查看模式）
  router.push(`/oa/erp/erpProjectChange/edit/${row.projectChangeId}?type=view`);
};

// 判断当前行是否为该项目“最新且已审批完成”的变更记录
// 只有满足该条件时，列表中才显示“新增变更”按钮
const isLatestCompletedChange = (row: ErpProjectChangeVO) => {
  if (row.projectChangeStatus !== '3') {
    return false;
  }
  const pid = String(row.projectId);
  return latestCompletedChangeMap.value[pid] === row.changeNumber;
};

/** 新增变更按钮操作 */
const handleAddChange = (row: ErpProjectChangeVO) => {
  // 从完成状态的变更记录新增变更，传递projectId
  router.push(`/oa/erp/erpProjectChange/edit/0?projectId=${row.projectId}`);
};

/** 审批记录按钮操作 */
const handleApprovalRecord = (row: ErpProjectChangeVO) => {
  // 跳转到查看页面并显示审批记录
  router.push(`/oa/erp/erpProjectChange/edit/${row.projectChangeId}?type=view`);
};

/** 删除按钮操作 */
const handleDelete = async (row?: ErpProjectChangeVO) => {
  const _projectChangeIds = row?.projectChangeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目变更申请编号为"' + _projectChangeIds + '"的数据项？').finally(() => (loading.value = false));
  await delErpProjectChange(_projectChangeIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

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