<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="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="acceptanceDate">
              <el-date-picker
                v-model="acceptanceDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
              />
            </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:projectAcceptance: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:projectAcceptance: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:projectAcceptance:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:projectAcceptance: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="projectAcceptanceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" v-if="columns[0].visible" />
        <el-table-column label="验收确认编号" align="center" prop="acceptanceCode" width="150" show-overflow-tooltip v-if="columns[1].visible" />
        <el-table-column label="项目号" align="center" prop="projectCode" width="130" show-overflow-tooltip v-if="columns[2].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="160" show-overflow-tooltip v-if="columns[3].visible" />
        <el-table-column label="项目经理" align="center" prop="projectManagerName" width="100" show-overflow-tooltip v-if="columns[4].visible">
          <template #default="scope">
            <span>{{ scope.row.projectManagerName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="验收日期" align="center" prop="acceptanceDate" width="112" v-if="columns[5].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.acceptanceDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="验收单附件" align="center" width="108" v-if="columns[6].visible">
          <template #default="scope">
            <el-button v-if="scope.row.ossId" link type="primary" icon="Download" @click="downloadOss(scope.row.ossId)"></el-button>
            <span v-else style="color: #999">暂无附件</span>
          </template>
        </el-table-column>
        <el-table-column label="部门负责人" align="center" prop="chargeName" width="110" show-overflow-tooltip v-if="columns[7].visible" />
        <el-table-column label="分管副总" align="center" prop="deputyName" width="100" show-overflow-tooltip v-if="columns[8].visible" />
        <el-table-column label="业务状态" align="center" prop="acceptanceStatus" width="104" v-if="columns[10].visible">
          <template #default="scope">
            <dict-tag :options="acceptance_status" :value="scope.row.acceptanceStatus || ''" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" width="104" v-if="columns[11].visible">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus || 'draft'" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="140" show-overflow-tooltip v-if="columns[9].visible" />
        <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="isAcceptanceDraft(scope.row)">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:projectAcceptance:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看" placement="top" v-if="isAcceptanceNotDraft(scope.row)">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="审批记录" placement="top" v-if="isAcceptanceNotDraft(scope.row)">
              <el-button link type="warning" icon="Histogram" @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>
    <!-- 对话框逻辑已切换为编辑页流程
        <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>...</el-dialog>
        -->

    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="ProjectAcceptance" lang="ts">
import { delProjectAcceptance, listProjectAcceptance } from '@/api/oa/erp/projectAcceptance';
import { ProjectAcceptanceForm, ProjectAcceptanceQuery, ProjectAcceptanceVO } from '@/api/oa/erp/projectAcceptance/types';

import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { useRoute, useRouter } from 'vue-router';
import { onActivated } from 'vue';

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

const projectAcceptanceList = ref<ProjectAcceptanceVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const selectedRow = ref<ProjectAcceptanceVO | null>(null);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

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

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

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `序号`, visible: false },
  { key: 1, label: `验收确认编号`, visible: true },
  { key: 2, label: `项目号`, 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: `分管副总`, visible: true },
  { key: 9, label: `备注`, visible: true },
  { key: 10, label: `业务状态`, visible: true },
  { key: 11, label: `流程状态`, visible: false }
]);

const initFormData: ProjectAcceptanceForm = {
  acceptanceId: undefined,
  projectId: undefined,
  projectCode: undefined,
  projectName: undefined,
  managerId: undefined,
  acceptanceDate: undefined,
  ossId: undefined,
  chargeId: undefined,
  deputyId: undefined,
  remark: undefined
};
const data = reactive<PageData<ProjectAcceptanceForm, ProjectAcceptanceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: undefined,
    projectCode: undefined,
    projectName: undefined,
    managerId: undefined,
    acceptanceDate: undefined,
    ossId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    params: {}
  },
  rules: {
    projectCode: [{ required: true, message: '项目号不能为空', trigger: 'blur' }],
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    acceptanceDate: [{ required: true, message: '验收日期不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const acceptanceDateRange = ref<string[]>();

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

/** 业务状态为暂存（1）或未赋值：可修改、删除（与字典 acceptance_status 一致） */
const isAcceptanceDraft = (row: ProjectAcceptanceVO) => {
  const s = row.acceptanceStatus;
  return s === undefined || s === null || s === '' || s === '1';
};

/** 已非暂存（审批中、可用等）：仅查看、审批记录 */
const isAcceptanceNotDraft = (row: ProjectAcceptanceVO) => {
  const s = row.acceptanceStatus;
  return s !== undefined && s !== null && s !== '' && s !== '1';
};

/** 查询项目验收确认列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProjectAcceptance(queryParams.value);
  projectAcceptanceList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (acceptanceDateRange.value && acceptanceDateRange.value.length === 2) {
    queryParams.value.params.beginTime = acceptanceDateRange.value[0];
    queryParams.value.params.endTime = acceptanceDateRange.value[1];
  } else {
    if (queryParams.value.params) {
      queryParams.value.params.beginTime = undefined as any;
      queryParams.value.params.endTime = undefined as any;
    }
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  acceptanceDateRange.value = undefined; // 清空日期范围
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProjectAcceptanceVO[]) => {
  ids.value = selection.map((item) => item.acceptanceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectedRow.value = selection.length === 1 ? selection[0] : null;
};

/** 新增按钮操作（与项目信息保持一致） */
const handleAdd = () => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/projectAcceptance/edit',
    query: { type: 'add' }
  });
};

/** 修改按钮操作（与项目信息保持一致） */
const handleUpdate = async (row?: ProjectAcceptanceVO) => {
  const target = row || (selectedRow.value as any);
  if (!target) return;
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/projectAcceptance/edit',
    query: { id: target.acceptanceId, type: 'update' }
  });
};

/** 查看按钮操作（与项目信息保持一致） */
const handleView = (row: ProjectAcceptanceVO) => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/project/projectAcceptance/edit',
    query: { id: row.acceptanceId, type: 'view' }
  });
};

/** 提交按钮 */
// const submitForm = () => { /* 对话框流程已停用，改用编辑页 */ }

// const submitAndStartFlow = async () => { /* 对话框流程已停用，改用编辑页 */ }

/** 删除按钮操作 */
const handleDelete = async (row?: ProjectAcceptanceVO) => {
  if (row) {
    if (!isAcceptanceDraft(row)) {
      proxy?.$modal.msgWarning('仅暂存状态可删除');
      return;
    }
  } else {
    const rows = projectAcceptanceList.value.filter((r) => ids.value.includes(r.acceptanceId as any));
    if (rows.some((r) => !isAcceptanceDraft(r))) {
      proxy?.$modal.msgWarning('仅暂存状态的记录可删除，请重新选择');
      return;
    }
    if (!ids.value.length) return;
  }
  const _acceptanceIds = row?.acceptanceId || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目验收确认编号为"' + _acceptanceIds + '"的数据项？').finally(() => (loading.value = false));
  await delProjectAcceptance(_acceptanceIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

/** 检查是否需要刷新列表 */
const checkShouldRefresh = () => {
  const flag = sessionStorage.getItem(refreshFlagKey);
  if (flag) {
    sessionStorage.removeItem(refreshFlagKey);
    handleQuery();
  }
};

onMounted(() => {
  getList();
  checkShouldRefresh();
});

onActivated(() => {
  checkShouldRefresh();
});

const downloadOss = (ossId: string | number) => {
  proxy?.$download.oss(ossId as any);
};

const handleApprovalRecord = (row: ProjectAcceptanceVO) => {
  approvalRecordRef.value?.init(row.acceptanceId as any);
};
</script>
