<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="contractCode">
              <el-input v-model="queryParams.contractCode" placeholder="请输入合同编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="业务方向" prop="businessDirection">-->
            <!--              <el-select v-model="queryParams.businessDirection" placeholder="请选择业务方向" clearable>-->
            <!--                <el-option v-for="dict in business_direction" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </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="spareFlag">-->
            <!--              <el-select v-model="queryParams.spareFlag" placeholder="请选择备件标识" clearable>-->
            <!--                <el-option v-for="dict in spare_flag" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="订单状态" prop="projectStatus">
              <el-select v-model="queryParams.projectStatus" placeholder="请选择订单状态" clearable>
                <el-option v-for="dict in project_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-dropdown trigger="click" @command="handleAdd">-->
      <!--              <el-button type="primary" plain icon="Plus" v-hasPermi="['oa/erp:projectInfo:add']">-->
      <!--                新增-->
      <!--                <el-icon class="el-icon&#45;&#45;right">-->
      <!--                  <arrow-down />-->
      <!--                </el-icon>-->
      <!--              </el-button>-->
      <!--              <template #dropdown>-->
      <!--                <el-dropdown-menu>-->
      <!--                  <el-dropdown-item v-for="dict in project_category" :key="dict.value" :command="dict.value">-->
      <!--                    {{ dict.label }}-->
      <!--                  </el-dropdown-item>-->
      <!--                </el-dropdown-menu>-->
      <!--              </template>-->
      <!--            </el-dropdown>-->
      <!--          </el-col>-->
      <!--          <el-col :span="1.5">-->
      <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:projectInfo: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:projectInfo:remove']"-->
      <!--              >删除-->
      <!--            </el-button>-->
      <!--          </el-col>-->
      <!--          <el-col :span="1.5">-->
      <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:projectInfo: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="projectInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="订单ID" align="center" prop="projectId" v-if="columns[0].visible" />
        <el-table-column label="有无合同" align="center" prop="contractFlag" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="contract_flag" :value="scope.row.contractFlag" />
          </template>
        </el-table-column>
        <el-table-column label="订单编号" align="center" prop="projectCode" width="140" v-if="columns[3].visible">
          <!--          <template #default="scope">-->
          <!--            <el-link type="primary" underline @click="handleLedger(scope.row)">-->
          <!--              {{ scope.row.projectCode }}-->
          <!--            </el-link>-->
          <!--          </template>-->
        </el-table-column>
        <el-table-column label="订单名称" align="center" prop="projectName" width="200" v-if="columns[4].visible">
          <template #default="scope">
            <el-link type="primary" underline @click="handleOrderLedger(scope.row)">
              {{ scope.row.projectName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="合同编号" align="center" prop="contractCode" width="140" v-if="columns[27].visible" />
        <el-table-column label="合同名称" align="center" prop="contractName" width="200" v-if="columns[28].visible" />
        <el-table-column label="业务方向" align="center" prop="businessDirection" width="100" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
          </template>
        </el-table-column>
        <el-table-column label="订单类别" align="center" prop="projectCategory" width="150" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="project_category" :value="scope.row.projectCategory" />
          </template>
        </el-table-column>
        <el-table-column label="备件标识" align="center" prop="spareFlag" v-if="columns[7].visible">
          <template #default="scope">
            <dict-tag :options="spare_flag" :value="scope.row.spareFlag" />
          </template>
        </el-table-column>
        <el-table-column label="订单类型" align="center" prop="orderType" width="130" v-if="columns[8].visible">
          <template #default="scope">
            <dict-tag :options="erp_order_type" :value="scope.row.orderType" />
          </template>
        </el-table-column>
        <el-table-column label="付款方式" align="center" prop="paymentMethod" width="120" v-if="columns[9].visible" />
        <el-table-column label="部门" align="center" prop="deptName" width="120" v-if="columns[10].visible" />
        <el-table-column label="项目经理" align="center" prop="managerName" width="100" v-if="columns[11].visible" />
        <el-table-column label="部门负责人" align="center" prop="chargeName" width="120" v-if="columns[12].visible" />
        <el-table-column label="分管副总" align="center" prop="deputyName" width="100" v-if="columns[13].visible" />
        <el-table-column label="抄送人员" align="center" prop="peopleId" v-if="columns[14].visible" />
        <el-table-column label="订单状态" align="center" prop="projectStatus" v-if="columns[15].visible">
          <template #default="scope">
            <dict-tag :options="project_status" :value="scope.row.projectStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[16].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="orderPurchaseStatus" width="110" v-if="columns[29].visible">
          <template #default="scope">
            <dict-tag :options="order_purchase_status" :value="scope.row.orderPurchaseStatus" />
          </template>
        </el-table-column>
        <el-table-column label="发货状态" align="center" prop="orderDeliveryStatus" width="110" v-if="columns[30].visible">
          <template #default="scope">
            <dict-tag :options="order_delivery_status" :value="scope.row.orderDeliveryStatus" />
          </template>
        </el-table-column>
        <el-table-column label="开票状态" align="center" prop="orderInvoiceStatus" width="110" v-if="columns[31].visible">
          <template #default="scope">
            <dict-tag :options="order_invoice_status" :value="scope.row.orderInvoiceStatus" />
          </template>
        </el-table-column>
        <el-table-column label="回款百分比" align="center" prop="orderPaymentRate" width="120" v-if="columns[32].visible">
          <template #default="scope">
            {{ scope.row.orderPaymentRate ?? 0 }}%
          </template>
        </el-table-column>
        <el-table-column label="排序号" align="center" prop="sortOrder" v-if="columns[17].visible" />
        <el-table-column label="合同ID(预留)" align="center" prop="contractId" v-if="columns[18].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[19].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" v-if="columns[20].visible">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top" v-if="scope.row.flowStatus === 'draft' || scope.row.flowStatus === 'back'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:projectInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看详情" placement="top" v-if="scope.row.flowStatus !== 'draft'">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <!--            <el-col :span="1.5" v-if="scope.row.flowStatus === 'waiting'">-->
            <!--              <el-button-->
            <!--                size="small"-->
            <!--                type="warning"-->
            <!--                icon="Notification"-->
            <!--                @click="handleCancelProcessApply(scope.row.projectId)"-->
            <!--              >撤销</el-button-->
            <!--              >-->
            <!--            </el-col>-->
          </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>
    <!-- 审批记录 -->
    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="ProjectInfo" lang="ts">
import { listContractOrder } from '@/api/oa/erp/contractOrder';
import { listProjectInfo, delProjectInfo } from '@/api/oa/erp/projectInfo';
import { ProjectInfoVO, ProjectInfoQuery } from '@/api/oa/erp/projectInfo/types';
import { cancelProcessApply } from '@/api/workflow/instance';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const { business_direction, project_status, active_flag, contract_flag, project_category, spare_flag, wf_business_status, order_purchase_status, order_delivery_status, order_invoice_status, erp_order_type } = toRefs<any>(
  proxy?.useDict(
    'business_direction',
    'project_status',
    'active_flag',
    'contract_flag',
    'project_category',
    'spare_flag',
    'wf_business_status',
    'order_purchase_status',
    'order_delivery_status',
    'order_invoice_status',
    'erp_order_type'
  )
);

const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const projectInfoList = ref<ProjectInfoVO[]>([]);
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: `订单ID`, 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: false },
  { key: 7, label: `备件标识`, visible: false },
  { key: 8, label: `订单类型`, visible: true },
  { key: 9, label: `付款方式`, visible: false },
  { key: 10, label: `部门`, visible: false },
  { key: 11, label: `项目经理`, visible: false },
  { key: 12, label: `部门负责人`, visible: false },
  { key: 13, label: `分管副总`, visible: false },
  { key: 14, label: `抄送人员`, visible: false },
  { key: 15, label: `订单状态`, visible: true },
  { key: 16, label: `流程状态`, visible: true },
  { key: 17, label: `排序号`, visible: false },
  { key: 18, label: `合同ID(预留)`, 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 },
  { key: 25, label: `更新人`, visible: false },
  { key: 26, label: `更新时间`, visible: false },
  { key: 27, label: `合同编号`, visible: true },
  { key: 28, label: `合同名称`, visible: true },
  { key: 29, label: `采购状态`, visible: true },
  { key: 30, label: `发货状态`, visible: true },
  { key: 31, label: `开票状态`, visible: true },
  { key: 32, label: `回款百分比`, visible: true }
]);

const data = reactive<{ queryParams: ProjectInfoQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractFlag: undefined,
    projectCode: undefined,
    projectName: undefined,
    businessDirection: undefined,
    projectCategory: undefined,
    spareFlag: undefined,
    projectTypeId: undefined,
    orderType: undefined,
    paymentMethod: undefined,
    deptId: undefined,
    managerId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    peopleId: undefined,
    amount: undefined,
    projectStatus: undefined,
    flowStatus: undefined,
    sortOrder: undefined,
    contractId: undefined,
    activeFlag: undefined,
    contractCode: undefined,
    contractName: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);

/** 查询合同订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContractOrder(queryParams.value);
  projectInfoList.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: ProjectInfoVO[]) => {
  ids.value = selection.map((item) => item.projectId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 根据订单类别获取编辑页面路径 */
const getEditPathByCategory = (projectCategory?: string) => {
  return '/contract/contractInfo/orderActivate';
};

/** 新增按钮操作 */
const handleAdd = (projectCategory: string) => {
  proxy.$tab.closePage(route);
  router.push({
    path: getEditPathByCategory(projectCategory),
    query: {
      type: 'add',
      projectCategory: projectCategory
    }
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: ProjectInfoVO) => {
  const _projectId = row?.projectId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: getEditPathByCategory(row?.projectCategory),
    query: {
      id: _projectId,
      type: 'update'
    }
  });
};

/** 查看按钮操作 */
const handleView = (row?: ProjectInfoVO) => {
  const _projectId = row?.projectId;
  proxy.$tab.closePage(route);
  router.push({
    path: getEditPathByCategory(row?.projectCategory),
    query: {
      id: _projectId,
      type: 'view'
    }
  });
};

/** 订单台账页面 */
const handleLedger = (row: ProjectInfoVO) => {
  const _projectId = row?.projectId;
  if (!_projectId) return;
  proxy.$tab.closePage(route);
  router.push(`/oa/erp/projectLedger/${_projectId}`);
};

/** 订单管理台账 */
const handleOrderLedger = (row: ProjectInfoVO) => {
  const _projectId = row?.projectId;
  if (!_projectId) return;
  router.push(`/oa/erp/orderLedger/${_projectId}`);
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProjectInfoVO) => {
  const _projectIds = row?.projectId || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单信息编号为"' + _projectIds + '"的数据项？').finally(() => (loading.value = false));
  await delProjectInfo(_projectIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

/** 撤销按钮操作 */
const handleCancelProcessApply = async (id: string | number) => {
  await proxy?.$modal.confirm('是否确认撤销当前单据？');
  loading.value = true;
  const data = {
    businessId: id,
    message: '申请人撤销流程！'
  };
  await cancelProcessApply(data).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('撤销成功');
};

// 查看审批记录
const handleApprovalRecord = (row: ProjectInfoVO) => {
  approvalRecordRef.value?.init(row.projectId);
};

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