<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="purchaseCode">
              <el-input v-model="queryParams.purchaseCode" placeholder="请输入采购编号" 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="managerName">
              <el-input v-model="queryParams.managerName" placeholder="请输入项目经理" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目采购状态" prop="projectPurchaseStatus">
              <el-select v-model="queryParams.projectPurchaseStatus" placeholder="请选择项目采购状态" clearable>
                <el-option v-for="dict in project_purchase_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:projectPurchase: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:projectPurchase: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:projectPurchase:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:projectPurchase: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="projectPurchaseList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目采购ID" align="center" prop="projectPurchaseId" width="120" v-if="columns[0].visible" />
        <el-table-column label="项目ID" align="center" prop="projectId" width="120" v-if="columns[2].visible" />
        <el-table-column label="采购编号" align="center" prop="purchaseCode" width="150" v-if="columns[26].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="managerName" width="120" v-if="columns[5].visible" />
        <el-table-column label="部门负责人" align="center" prop="chargeName" width="120" v-if="columns[6].visible" />
        <el-table-column label="分管副总" align="center" prop="deputyName" width="120" v-if="columns[7].visible" />
        <el-table-column label="版本" align="center" prop="version" width="100" v-if="columns[8].visible">
          <template #default="scope">
            <span>v{{ scope.row.version }}.0</span>
          </template>
        </el-table-column>
        <el-table-column label="提报人" align="center" prop="reporterName" width="120" v-if="columns[9].visible" />
        <el-table-column label="收货人" align="center" prop="consigneeUser" width="120" v-if="columns[10].visible" />
        <el-table-column label="收货地址" align="center" prop="consigneeAddress" width="200" show-overflow-tooltip v-if="columns[11].visible" />
        <el-table-column label="收货人联系方式" align="center" prop="consigneeContact" width="150" v-if="columns[12].visible" />
        <el-table-column label="项目采购状态" align="center" prop="projectPurchaseStatus" width="140" v-if="columns[13].visible">
          <template #default="scope">
            <dict-tag :options="project_purchase_status" :value="scope.row.projectPurchaseStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" width="120" v-if="columns[14].visible" />
        <el-table-column label="排序号" align="center" prop="sortOrder" width="100" v-if="columns[15].visible" />
        <el-table-column label="合同/预算ID" align="center" prop="relationId" width="130" v-if="columns[16].visible" />
        <el-table-column label="备注" align="center" prop="remark" width="180" show-overflow-tooltip v-if="columns[17].visible" />
        <el-table-column label="是否备件类" align="center" prop="spareFlag" width="120" v-if="columns[18].visible">
          <template #default="scope">
            <dict-tag :options="spare_flag" :value="scope.row.spareFlag" />
          </template>
        </el-table-column>
        <el-table-column label="激活标识" align="center" prop="activeFlag" width="120" 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" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip v-if="!canEdit(scope.row)" content="查看详情" placement="top">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="canEdit(scope.row)" content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:projectPurchase:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="导出采购明细" placement="top">
              <el-button
                link
                type="warning"
                icon="Download"
                @click="handleExportSingle(scope.row)"
                v-hasPermi="['oa/erp:projectPurchase:export']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="审批单导出" placement="top" v-if="scope.row.projectPurchaseStatus == 3">
              <el-button
                link
                type="primary"
                icon="Tickets"
                @click="handleExportApprovalPdf(scope.row)"
                v-hasPermi="['oa/erp:projectPurchase:export']"
              ></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="删除" placement="top">-->
            <!--              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/erp:projectPurchase: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="ProjectPurchase" lang="ts">
import { reactive, ref, toRefs, getCurrentInstance, onMounted } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { listProjectPurchase, delProjectPurchase, exportProjectPurchaseApprovalPdf } from '@/api/oa/erp/projectPurchase';
import type { ProjectPurchaseVO, ProjectPurchaseQuery } from '@/api/oa/erp/projectPurchase/types';

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

const projectPurchaseList = ref<ProjectPurchaseVO[]>([]);
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<FormInstance>();

const columns = ref<FieldOption[]>([
  { key: 0, label: `项目采购ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { 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: `版本`, 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: false },
  { key: 16, label: `合同/预算ID`, visible: false },
  { key: 17, label: `备注`, visible: false },
  { key: 18, label: `是否备件类`, visible: false },
  { key: 19, label: `激活标识`, visible: false },
  { 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 },
  { key: 25, label: `更新时间`, visible: false },
  { key: 26, label: `采购编号`, visible: true }
]);

const data = reactive<{ queryParams: ProjectPurchaseQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: undefined,
    projectCode: undefined,
    purchaseCode: undefined,
    projectName: undefined,
    managerId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    reporterId: undefined,
    consigneeUser: undefined,
    consigneeAddress: undefined,
    consigneeContact: undefined,
    projectPurchaseStatus: undefined,
    flowStatus: undefined,
    sortOrder: undefined,
    relationId: undefined,
    spareFlag: undefined,
    activeFlag: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);

const getList = async () => {
  loading.value = true;
  const res = await listProjectPurchase(queryParams.value);
  projectPurchaseList.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: ProjectPurchaseVO[]) => {
  ids.value = selection.map((item) => item.projectPurchaseId);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

const handleAdd = () => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/purchase/projectPurchase/edit',
    query: { type: 'add' }
  });
};

const canEdit = (row?: ProjectPurchaseVO) => {
  return row.projectPurchaseStatus === '1';
};

const handleUpdate = (row?: ProjectPurchaseVO) => {
  const projectPurchaseId = row?.projectPurchaseId || ids.value[0];
  if (!projectPurchaseId) {
    return;
  }
  proxy?.$tab.closePage(route);
  router.push({
    path: '/purchase/projectPurchase/edit',
    query: { id: projectPurchaseId, type: 'update' }
  });
};

const handleView = (row: ProjectPurchaseVO) => {
  proxy?.$tab.closePage(route);
  router.push({
    path: '/purchase/projectPurchase/edit',
    query: { id: row.projectPurchaseId, type: 'view' }
  });
};

const handleDelete = async (row?: ProjectPurchaseVO) => {
  const projectPurchaseIds = row?.projectPurchaseId || ids.value;
  await proxy?.$modal.confirm(`是否确认删除项目采购信息编号为"${projectPurchaseIds}"的数据项？`).finally(() => {
    loading.value = false;
  });
  await delProjectPurchase(projectPurchaseIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  proxy?.download(
    'oa/erp/projectPurchase/export',
    {
      ...queryParams.value
    },
    `projectPurchase_${new Date().getTime()}.xlsx`
  );
};

const handleExportSingle = (row: ProjectPurchaseVO) => {
  proxy?.download(
    `oa/erp/projectPurchase/exportSingle/${row.projectPurchaseId}`,
    {},
    `projectPurchase_${row.projectCode}_${new Date().getTime()}.xlsx`
  );
};

const handleExportApprovalPdf = async (row: ProjectPurchaseVO) => {
  try {
    const res = await exportProjectPurchaseApprovalPdf(row.projectPurchaseId);
    const blob = new Blob([res as unknown as BlobPart], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `采购审批单_${row.projectCode}_${row.purchaseCode}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    proxy?.$modal.msgSuccess('审批单导出成功');
  } catch {
    proxy?.$modal.msgError('审批单导出失败，请确认采购单已审批完成');
  }
};

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