<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-->
                  <!--                    v-for="dict in project_category"-->
                  <!--                    :key="dict.value"-->
                  <!--                    :command="dict.value"-->
                  <!--                  >-->
                  <!--                    {{ dict.label }}-->
                  <!--                  </el-dropdown-item>-->
                  <el-dropdown-item command="1">销售项目</el-dropdown-item>
                  <el-dropdown-item command="3">研发项目</el-dropdown-item>
                  <el-dropdown-item command="4" :disabled="!isBmjl">预投项目</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="primary"
              plain
              icon="Setting"
              :disabled="single"
              @click="openMaintainFromSelection()"
              v-hasPermi="['oa/erp:projectInfo:update']"
              >项目信息维护
            </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="160" 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" />
        <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="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="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" 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="amount" width="110" v-if="columns[15].visible" />
        <el-table-column label="产品数量" align="center" prop="productQty" width="100" v-if="columns[28].visible" />
        <el-table-column
          label="项目进度状态"
          align="center"
          prop="projectProgressStatus"
          min-width="120"
          show-overflow-tooltip
          v-if="columns[32].visible"
        />
        <el-table-column label="项目阶段" align="center" prop="projectPhase" min-width="120" show-overflow-tooltip v-if="columns[29].visible" />
        <el-table-column label="情况说明" align="center" prop="situationDesc" min-width="140" show-overflow-tooltip v-if="columns[30].visible" />
        <el-table-column label="需要开展工作" align="center" prop="requiredWork" min-width="140" show-overflow-tooltip v-if="columns[31].visible" />
        <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="!isRdSubProject(scope.row) && (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="!isRdSubProject(scope.row) && 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" />

    <el-dialog v-model="maintainOpen" title="项目信息维护（项目台账使用）" width="560px" append-to-body destroy-on-close @closed="resetMaintainForm">
      <el-form ref="maintainFormRef" :model="maintainForm" :rules="maintainRules" label-width="110px">
        <el-form-item label="项目编号">
          <el-input v-model="maintainForm.projectCode" disabled />
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input v-model="maintainForm.projectName" disabled />
        </el-form-item>
        <el-form-item label="产品数量" prop="productQty">
          <el-input-number v-model="maintainForm.productQty" :min="0" :precision="0" controls-position="right" class="w-full" placeholder="产品数量" />
        </el-form-item>
        <el-form-item label="项目进度状态" prop="projectProgressStatus">
          <el-input
            v-model="maintainForm.projectProgressStatus"
            maxlength="500"
            show-word-limit
            placeholder="请输入项目进度状态"
            clearable
          />
        </el-form-item>
        <el-form-item label="项目阶段" prop="projectPhase">
          <el-input v-model="maintainForm.projectPhase" maxlength="500" show-word-limit placeholder="请输入项目阶段" clearable />
        </el-form-item>
        <el-form-item label="情况说明" prop="situationDesc">
          <el-input v-model="maintainForm.situationDesc" type="textarea" :rows="3" maxlength="2000" show-word-limit placeholder="请输入情况说明" />
        </el-form-item>
        <el-form-item label="需要开展工作" prop="requiredWork">
          <el-input v-model="maintainForm.requiredWork" type="textarea" :rows="3" maxlength="2000" show-word-limit placeholder="请输入需要开展工作" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="maintainOpen = false">取 消</el-button>
        <el-button type="primary" :loading="maintainSubmitting" @click="submitMaintain">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const isBmjl = computed(() => {
  const roles = userStore.roles || [];
  return roles.includes('BMJL');
});
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: false },
  { 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: false },
  { 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 },
  { 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,
    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 maintainOpen = ref(false);
const maintainSubmitting = ref(false);
const maintainFormRef = ref<ElFormInstance>();

type MaintainFormModel = ProjectInfoForm & { projectCode?: string; projectName?: string };

const maintainForm = reactive<MaintainFormModel>({
  projectId: '',
  projectCode: '',
  projectName: '',
  productQty: undefined,
  projectProgressStatus: '',
  projectPhase: '',
  situationDesc: '',
  requiredWork: ''
});

const maintainRules = {
  projectPhase: [{ required: true, message: '请输入项目阶段', trigger: 'blur' }],
  situationDesc: [{ required: true, message: '请输入情况说明', trigger: 'blur' }]
};

const resetMaintainForm = () => {
  maintainForm.projectId = '';
  maintainForm.projectCode = '';
  maintainForm.projectName = '';
  maintainForm.productQty = undefined;
  maintainForm.projectProgressStatus = '';
  maintainForm.projectPhase = '';
  maintainForm.situationDesc = '';
  maintainForm.requiredWork = '';
};

/** 研发子项目（挂在主项目下）：列表不提供编辑/查看/维护入口 */
const isRdSubProject = (row: ProjectInfoVO) => {
  return row.projectCategory === '3' && row.parentProjectId != null;
};

const openMaintainFromSelection = () => {
  const id = ids.value[0];
  const row = projectInfoList.value.find((item) => item.projectId === id);
  if (row) {
    openMaintain(row);
  }
};

const openMaintain = async (row: ProjectInfoVO) => {
  proxy?.$modal.loading('加载中...');
  try {
    const res = await getProjectInfo(row.projectId);
    const data = res.data as ProjectInfoVO;
    maintainForm.projectId = data.projectId;
    maintainForm.projectCode = data.projectCode;
    maintainForm.projectName = data.projectName;
    maintainForm.productQty = data.productQty ?? undefined;
    maintainForm.projectProgressStatus = data.projectProgressStatus ?? '';
    maintainForm.projectPhase = data.projectPhase ?? '';
    maintainForm.situationDesc = data.situationDesc ?? '';
    maintainForm.requiredWork = data.requiredWork ?? '';
    maintainOpen.value = true;
    nextTick(() => maintainFormRef.value?.clearValidate());
  } finally {
    proxy?.$modal.closeLoading();
  }
};

const submitMaintain = () => {
  maintainFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    maintainSubmitting.value = true;
    try {
      const payload: ProjectInfoForm = {
        projectId: maintainForm.projectId,
        productQty: maintainForm.productQty ?? null,
        projectProgressStatus: maintainForm.projectProgressStatus,
        projectPhase: maintainForm.projectPhase,
        situationDesc: maintainForm.situationDesc,
        requiredWork: maintainForm.requiredWork
      };
      await maintainProjectInfo(payload);
      proxy?.$modal.msgSuccess('保存成功');
      maintainOpen.value = false;
      await getList();
    } finally {
      maintainSubmitting.value = false;
    }
  });
};

/** 查询项目信息列表 */
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 getEditPathByCategory = (projectCategory?: string) => {
  if (projectCategory === '3') {
    // 研发项目
    return '/project/projectInfo/devEdit';
  } else if (projectCategory === '4') {
    // 预投项目
    return '/project/projectInfo/preEdit';
  } else {
    // 其他项目（销售项目等）
    return '/project/projectInfo/edit';
  }
};

/** 新增按钮操作 */
const handleAdd = (projectCategory: string) => {
  if (projectCategory === '4' && !isBmjl.value) {
    proxy?.$modal.msgWarning('仅部门经理（BMJL 角色）可以申请预投项目');
    return;
  }
  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 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>
