<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="contractFlag">
              <el-select v-model="queryParams.contractFlag" placeholder="请选择有无合同" clearable>
                <el-option v-for="dict in contract_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </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="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 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-dropdown trigger="click" @command="handleAdd">
              <el-button type="primary" plain icon="Plus" v-hasPermi="['oa/erp:projectInfo:add']">
                新增
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1">销售项目（实施、物流）</el-dropdown-item>
                  <el-dropdown-item command="2">销售项目（备件）</el-dropdown-item>
                  <el-dropdown-item command="3">研发项目</el-dropdown-item>
                  <el-dropdown-item command="4">预投项目</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="120" v-if="columns[3].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" width="140" v-if="columns[4].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="typeName" width="130" v-if="columns[8].visible" />
        <el-table-column label="付款方式" align="center" prop="paymentMethod" v-if="columns[9].visible" />
        <el-table-column label="部门" align="center" prop="deptName" 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="amount" v-if="columns[15].visible" />
        <el-table-column label="项目状态" align="center" prop="projectStatus" v-if="columns[16].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[17].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="sortOrder" v-if="columns[18].visible" />
        <el-table-column label="合同ID(预留)" align="center" prop="contractId" v-if="columns[19].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[20].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" v-if="columns[21].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 { 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 } = toRefs<any>(
  proxy?.useDict('business_direction', 'project_status', 'active_flag', 'contract_flag', 'project_category', 'spare_flag', 'wf_business_status')
);

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: true },
  { 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: false },
  { key: 15, label: `金额`, visible: true },
  { key: 16, label: `项目状态`, visible: true },
  { key: 17, label: `流程状态`, visible: true },
  { key: 18, label: `排序号`, visible: true },
  { key: 19, label: `合同ID(预留)`, 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: false },
  { key: 27, label: `更新时间`, visible: false }
]);

const data = reactive<{ queryParams: ProjectInfoQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractFlag: undefined,
    projectCode: undefined,
    projectName: undefined,
    businessDirection: undefined,
    projectCategory: undefined,
    spareFlag: undefined,
    projectTypeId: 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,
    params: {}
  }
});

const { queryParams } = toRefs(data);

/** 查询项目信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProjectInfo(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 handleAdd = (projectCategory: string) => {
  proxy.$tab.closePage(route);
  router.push({
    path: '/project/projectInfo/edit',
    query: {
      type: 'add',
      projectCategory: projectCategory
    }
  });
};

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

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

/** 删除按钮操作 */
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>
