<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="changeCode">
              <el-input v-model="queryParams.changeCode" placeholder="请输入变更单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="变更类型" prop="changeType">
              <el-select v-model="queryParams.changeType" placeholder="请选择变更类型" clearable>
                <el-option v-for="dict in contract_change_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="原合同编号" prop="contractCode">
              <el-input v-model="queryParams.contractCode" placeholder="请输入原合同编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="变更状态" prop="changeStatus">
              <el-select v-model="queryParams.changeStatus" placeholder="请选择变更状态" clearable>
                <el-option v-for="dict in contract_change_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:contractChange: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:contractChange: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:contractChange:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:contractChange: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="contractChangeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="合同变更ID" align="center" prop="contractChangeId" width="100" v-if="columns[0].visible" />
        <el-table-column label="变更单编号" align="center" prop="changeCode" width="140" v-if="columns[1].visible" />
        <el-table-column label="变更类型" align="center" prop="changeType" width="100" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="contract_change_type" :value="scope.row.changeType" />
          </template>
        </el-table-column>
        <el-table-column label="原合同ID" align="center" prop="contractId" width="100" v-if="columns[3].visible" />
        <el-table-column label="原合同编号" align="center" prop="contractCode" width="140" v-if="columns[4].visible" />
        <el-table-column label="原合同名称" align="center" prop="contractName" min-width="160" show-overflow-tooltip v-if="columns[5].visible" />
        <el-table-column label="原客户名称" align="center" prop="originalCustomerName" min-width="120" show-overflow-tooltip v-if="columns[6].visible" />
        <el-table-column label="原合同金额" align="center" prop="originalContractAmount" width="120" v-if="columns[7].visible" />
        <el-table-column label="变更后合同编号" align="center" prop="changeContractCode" width="140" v-if="columns[8].visible" />
        <el-table-column label="变更后合同名称" align="center" prop="changeContractName" min-width="160" show-overflow-tooltip v-if="columns[9].visible" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="180" show-overflow-tooltip v-if="columns[10].visible" />
        <el-table-column label="变更后合同金额" align="center" prop="changeContractAmount" width="120" v-if="columns[11].visible" />
        <el-table-column label="变更原因" align="center" prop="changeReason" min-width="160" show-overflow-tooltip v-if="columns[12].visible" />
        <el-table-column label="申请时间" align="center" prop="applyTime" width="160" v-if="columns[13].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="业务方向" align="center" prop="businessDirection" width="120" v-if="columns[14].visible">
          <template #default="scope">
            <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
          </template>
        </el-table-column>
        <el-table-column label="承办部门" align="center" prop="undertakeDeptName" width="120" v-if="columns[15].visible" />
        <el-table-column label="承办人" align="center" prop="undertakeByName" width="100" v-if="columns[16].visible" />
        <el-table-column label="行业/大区" align="center" prop="industryRegion" width="100" v-if="columns[17].visible" />
        <el-table-column label="印章法人单位" align="center" prop="sealLegalEntity" width="120" v-if="columns[18].visible" />
        <el-table-column label="变更状态" align="center" prop="changeStatus" width="100" v-if="columns[19].visible">
          <template #default="scope">
            <dict-tag :options="contract_change_status" :value="scope.row.changeStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" width="100" v-if="columns[20].visible" />
        <el-table-column label="是否回写" align="center" prop="writeBackFlag" width="90" v-if="columns[21].visible">
          <template #default="scope">
            <dict-tag :options="write_back_flag" :value="scope.row.writeBackFlag" />
          </template>
        </el-table-column>
        <el-table-column label="回写时间" align="center" prop="writeBackTime" width="160" v-if="columns[22].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.writeBackTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="120" show-overflow-tooltip v-if="columns[23].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" width="90" v-if="columns[24].visible" />
        <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top" v-if="canViewDetail(scope.row)">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)" v-hasPermi="['oa/erp:contractChange:query']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看原合同" placement="top" v-if="canViewOriginalContract(scope.row)">
              <el-button
                link
                type="success"
                icon="Tickets"
                @click="handleViewOriginalContract(scope.row)"
                v-hasPermi="['oa/erp:contractInfo:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="!canViewDetail(scope.row)">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:contractChange:edit']"></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="ContractChange" lang="ts">
import { listContractChange, delContractChange } from '@/api/oa/erp/contractChange';
import { ContractChangeVO, ContractChangeQuery } from '@/api/oa/erp/contractChange/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const { contract_change_status, contract_change_type, write_back_flag, business_direction } = toRefs<any>(
  proxy?.useDict('contract_change_status', 'contract_change_type', 'write_back_flag', 'business_direction')
);

const contractChangeList = ref<ContractChangeVO[]>([]);
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 queryParams = ref<ContractChangeQuery>({
  pageNum: 1,
  pageSize: 10,
  changeCode: undefined,
  changeType: undefined,
  contractCode: undefined,
  changeStatus: undefined,
  applyTime: undefined,
  params: {}
});

// 列显隐信息（与表格列顺序一致）
const columns = ref<FieldOption[]>([
  { key: 0, label: '合同变更ID', visible: false },
  { key: 1, label: '变更单编号', visible: true },
  { key: 2, label: '变更类型', visible: true },
  { key: 3, label: '原合同ID', visible: false },
  { key: 4, label: '原合同编号', visible: true },
  { key: 5, label: '原合同名称', visible: true },
  { key: 6, label: '原客户名称', visible: false },
  { key: 7, label: '原合同金额', visible: false },
  { key: 8, label: '变更后合同编号', visible: true },
  { key: 9, label: '变更后合同名称', visible: true },
  { key: 10, label: '客户名称', visible: true },
  { key: 11, label: '变更后合同金额', visible: false },
  { key: 12, label: '变更原因', visible: false },
  { key: 13, label: '申请时间', visible: true },
  { key: 14, label: '业务方向', visible: true },
  { key: 15, label: '承办部门', visible: false },
  { key: 16, label: '承办人', visible: true },
  { key: 17, label: '行业/大区', visible: false },
  { key: 18, label: '印章法人单位', visible: false },
  { key: 19, label: '变更状态', visible: true },
  { key: 20, label: '流程状态', visible: false },
  { key: 21, label: '是否回写', visible: false },
  { key: 22, label: '回写时间', visible: false },
  { key: 23, label: '备注', visible: false },
  { key: 24, label: '激活标识', visible: false }
]);

/** 查询合同变更列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContractChange(queryParams.value);
  contractChangeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

/** 新增按钮操作：跳转合同变更申请页 */
const handleAdd = () => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/contract/contractChange/edit',
    query: { type: 'add' }
  });
};

/** 状态不为1（草稿）时可查看详情 */
const canViewDetail = (row: ContractChangeVO) => {
  const status = row?.changeStatus;
  return status != null && Number(status) !== 1;
};

/** 变更状态为 3 时可查看原合同（合同编辑页-只读） */
const canViewOriginalContract = (row: ContractChangeVO) => {
  const status = row?.changeStatus;
  const hasContractId = row?.contractId != null && String(row.contractId).trim() !== '';
  return hasContractId && status != null && Number(status) === 3;
};

/** 查看原合同：跳转合同信息编辑页（查看模式） */
const handleViewOriginalContract = (row: ContractChangeVO) => {
  const id = row?.contractId;
  if (id == null || String(id).trim() === '') {
    proxy?.$modal.msgWarning('未找到原合同ID');
    return;
  }
  proxy?.$tab.closePage(route);
  router.push({
    path: '/contract/contractInfo/edit',
    query: {
      id: String(id),
      type: 'view'
    }
  });
};

/** 查看详情：使用菜单路由打开 */
const handleView = (row?: ContractChangeVO) => {
  const _contractChangeId = row?.contractChangeId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: '/contract/contractChange/edit',
    query: {
      id: _contractChangeId,
      type: 'view'
    }
  });
};

/** 修改按钮操作：跳转合同变更申请页（编辑） */
const handleUpdate = (row?: ContractChangeVO) => {
  const _contractChangeId = row?.contractChangeId || ids.value[0];
  proxy?.$tab.closePage(route);
  router.push({
    path: '/contract/contractChange/edit',
    query: {
      id: _contractChangeId,
      type: 'update'
    }
  });
};

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

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

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