<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="版本，新版本+1" prop="budgetVersion">-->
            <!--              <el-input v-model="queryParams.budgetVersion" placeholder="请输入版本，新版本+1" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="预算编号" prop="budgetCode">
              <el-input v-model="queryParams.budgetCode" placeholder="请输入预算编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目类别" prop="projectCategory">
              <el-select v-model="queryParams.projectCategory" placeholder="请选择项目类别">
                <el-option v-for="dict in project_category" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </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="budgetVersion">
              <el-input-number
                v-model="queryParams.budgetVersion"
                :min="1"
                :precision="0"
                placeholder="版本"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="项目经理" prop="managerId">
              <el-select v-model="queryParams.managerId" filterable placeholder="请选择项目经理">
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预算状态" prop="budgetStatus">
              <el-select v-model="queryParams.budgetStatus" placeholder="请选择预算状态" clearable>
                <el-option v-for="dict in budget_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/budgetInfo:add']"> 新增市场项目预算 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAddRd" v-hasPermi="['oa:erp/budgetInfo: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/budgetInfo: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/budgetInfo:remove']"-->
<!--              >删除-->
<!--            </el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa:erp/budgetInfo: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="budgetInfoList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="center" />-->
        <!--        <el-table-column label="版本，新版本+1" align="center" prop="budgetVersion" v-if="columns[4].visible" />-->
        <el-table-column label="预算编号" align="center" prop="budgetCode" min-width="140" show-overflow-tooltip />
        <el-table-column label="项目类别" align="center" prop="projectCategory" v-if="columns[5].visible" min-width="140">
          <template #default="scope">
            <dict-tag :options="project_category" :value="scope.row.projectCategory" />
          </template>
        </el-table-column>
        <el-table-column label="项目号" align="center" prop="projectCode" v-if="columns[6].visible" min-width="120" show-overflow-tooltip />
        <el-table-column label="项目名称" align="center" prop="projectName" v-if="columns[7].visible" min-width="160" show-overflow-tooltip />
        <el-table-column label="版本" align="center" prop="budgetVersion" v-if="columns[34].visible" width="64" />
        <el-table-column label="项目经理" align="center" prop="managerName" v-if="columns[8].visible" min-width="100" show-overflow-tooltip />
        <el-table-column label="产品经理" align="center" prop="productManagerName" v-if="columns[10].visible" min-width="100" show-overflow-tooltip />
        <el-table-column label="合同额(元)" align="center" prop="contractAmount" v-if="columns[14].visible" min-width="120" />
        <el-table-column label="合同净额(元)" align="center" prop="netContractAmount" v-if="columns[15].visible" min-width="120" />
        <el-table-column label="预算成本(元)" align="center" prop="budgetCost" v-if="columns[16].visible" min-width="120" />
        <el-table-column label="预算毛利率" align="center" prop="budgetRate" v-if="columns[17].visible" min-width="108">
          <template #default="scope">
            {{ formatRate(scope.row.budgetRate) }}
          </template>
        </el-table-column>
        <el-table-column label="降成本后预算成本(元)" align="center" prop="reduceBudgetCost" v-if="columns[18].visible" min-width="152" />
        <el-table-column label="降成本后预算毛利率" align="center" prop="reduceBudgetRate" v-if="columns[19].visible" min-width="150">
          <template #default="scope">
            {{ formatRate(scope.row.reduceBudgetRate) }}
          </template>
        </el-table-column>
        <el-table-column label="项目预算期间" align="center" prop="duringOperation" v-if="columns[20].visible" min-width="130" show-overflow-tooltip />
        <el-table-column label="预算状态" align="center" prop="budgetStatus" v-if="columns[24].visible" width="100">
          <template #default="scope">
            <dict-tag :options="budget_status" :value="scope.row.budgetStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[25].visible" width="100">
          <template #default="scope">
            <dict-tag :options="wf_business_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top" v-if="scope.row.budgetStatus !== BUDGET_STATUS.DRAFT">
              <el-button
                link
                type="info"
                icon="DocumentChecked"
                @click="handleUpdate(scope.row, 'view')"
                v-hasPermi="['oa:erp/budgetInfo:view']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="scope.row.budgetStatus === BUDGET_STATUS.DRAFT">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row, 'update')"
                v-hasPermi="['oa:erp/budgetInfo:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button
                link
                type="warning"
                icon="Download"
                @click="handleExport(scope.row)"
                v-hasPermi="['oa:erp/budgetInfo:export']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="变更" placement="top" v-if="scope.row.budgetStatus === BUDGET_STATUS.AVAILABLE">
              <el-button
                link
                type="primary"
                icon="RefreshRight"
                @click="handleChange(scope.row)"
                v-hasPermi="['oa:erp/budgetInfo:change']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.budgetStatus === BUDGET_STATUS.DRAFT">
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oa:erp/budgetInfo: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="budgetInfo" lang="ts">
import { listErpBudgetInfo, delErpBudgetInfo } from '@/api/oa/erp/budgetInfo';
import { budgetInfoVO, budgetInfoQuery, budgetInfoForm } from '@/api/oa/erp/budgetInfo/types';
import router from '@/router';
import { getUserList } from '@/api/system/user';
import { UserVO } from '@/api/system/user/types';
import { reactive } from 'vue';
import { ProjectCategoryEnum } from '@/enums/OAEnum';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { project_category, budget_status, wf_business_status } = toRefs<any>(
  proxy?.useDict('project_category', 'budget_status', 'wf_business_status')
);

const route = useRoute();

const budgetInfoList = ref<budgetInfoVO[]>([]);
const userList = ref<UserVO[]>([]);
const buttonLoading = ref(false);
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 budgetInfoFormRef = ref<ElFormInstance>();

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

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `预算ID`, visible: true },
  { key: 1, label: `租户编号`, visible: true },
  { key: 2, label: `项目ID`, visible: true },
  { key: 3, label: `等同于项目ID，做唯一索引使用，在作废时此值要清空`, visible: true },
  { key: 4, label: `版本，新版本+1`, 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: `产品经理，关联sys_user`, visible: false },
  { key: 11, label: `产品经理姓名`, visible: true },
  { key: 12, label: `审核(评审组长)ID，关联sys_user`, visible: true },
  { key: 13, label: `审核(评审组长)姓名`, visible: true },
  { key: 14, label: `合同额(元)`, visible: true },
  { key: 15, label: `合同净额(元)`, visible: true },
  { key: 16, label: `预算成本(元)`, visible: true },
  { key: 17, label: `预算毛利率，乘以100保存`, visible: true },
  { key: 18, label: `降成本后预算成本(元)`, visible: true },
  { key: 19, label: `降成本后预算毛利率`, visible: true },
  { key: 20, label: `项目预算期间`, visible: true },
  { key: 21, label: `单位ID,关联base_unit_info`, visible: true },
  { key: 22, label: `单位名称`, visible: true },
  { key: 23, label: `是否出口`, visible: true },
  { key: 24, label: `预算状态(1暂存 2审批中 3可用)`, visible: true },
  { key: 25, label: `流程状态`, visible: true },
  { key: 26, label: `合同ID(预留)`, visible: true },
  { 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 },
  { key: 33, label: `更新时间`, visible: true },
  { key: 34, label: `版本`, visible: true }
]);

const initFormData: budgetInfoForm = {
  budgetId: undefined,
  projectId: undefined,
  approvedFlag: undefined,
  budgetVersion: undefined,
  projectCategory: undefined,
  projectCode: undefined,
  projectName: undefined,
  managerId: undefined,
  managerName: undefined,
  productManagerId: undefined,
  productManagerName: undefined,
  approveUserId: undefined,
  approveUserName: undefined,
  contractAmount: undefined,
  netContractAmount: undefined,
  budgetCost: undefined,
  budgetRate: undefined,
  reduceBudgetCost: undefined,
  reduceBudgetRate: undefined,
  duringOperation: undefined,
  unitId: undefined,
  unitName: undefined,
  exportFlag: undefined,
  budgetStatus: undefined,
  flowStatus: undefined,
  contractId: undefined,
  remark: undefined
};
const data = reactive<PageData<budgetInfoForm, budgetInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    budgetCode: undefined,
    projectId: undefined,
    approvedFlag: undefined,
    budgetVersion: undefined,
    projectCategory: undefined,
    projectCode: undefined,
    projectName: undefined,
    managerId: undefined,
    managerName: undefined,
    productManagerId: undefined,
    productManagerName: undefined,
    approveUserId: undefined,
    approveUserName: undefined,
    contractAmount: undefined,
    netContractAmount: undefined,
    budgetCost: undefined,
    budgetRate: undefined,
    reduceBudgetCost: undefined,
    reduceBudgetRate: undefined,
    duringOperation: undefined,
    unitId: undefined,
    unitName: undefined,
    exportFlag: undefined,
    budgetStatus: undefined,
    flowStatus: undefined,
    contractId: undefined,
    params: {}
  },
  rules: {
    budgetId: [{ required: true, message: '预算ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    budgetVersion: [{ required: true, message: '版本，新版本+1不能为空', trigger: 'blur' }],
    projectCategory: [{ required: true, message: '冗余，项目类别不能为空', trigger: 'blur' }],
    projectCode: [{ required: true, message: '项目号不能为空', trigger: 'blur' }],
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 销售类项目（实施 / 物流 / 备件），与字典 project_category 及 OAEnum 一致 */
const MARKET_BUDGET_CATEGORIES: readonly string[] = [
  ProjectCategoryEnum.SALE_IMPLEMENT,
  ProjectCategoryEnum.SALE_LOGISTICS,
  ProjectCategoryEnum.SALE_SPARE
];

function isMarketBudgetCategory(category: string | number | undefined | null): boolean {
  const c = category === undefined || category === null ? '' : String(category);
  return MARKET_BUDGET_CATEGORIES.includes(c);
}

/** 列表「新增市场项目预算」进入编辑页的默认类别（选项目后仍以项目档案为准） */
const DEFAULT_ADD_MARKET_PROJECT_CATEGORY = ProjectCategoryEnum.SALE_LOGISTICS;

/** 关闭当前列表 Tab 并跳转预算相关路由，统一附带列表页码 */
function navigateToBudget(path: string, query: Record<string, string | number | undefined>) {
  proxy.$tab.closePage(route);
  router.push({
    path,
    query: {
      pageNum: queryParams.value.pageNum,
      ...query
    } as Record<string, any>
  });
}

const BUDGET_STATUS = reactive({
  DRAFT: '1', //暂存，草稿
  AUDITING: '2', //审批中
  AVAILABLE: '3' //可用
});

// 格式化百分比
const formatRate = (value: number) => {
  if (!value) return '';
  return value + '%';
};

/** 查询用户列表 */
const getUsers = async () => {
  const res = await getUserList({});
  userList.value = res.data;
};

/** 查询项目预算列表 */
const getList = async () => {
  loading.value = true;
  const res = await listErpBudgetInfo(queryParams.value);
  budgetInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: budgetInfoVO[]) => {
  ids.value = selection.map((item) => item.budgetId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增市场项目预算按钮操作 */
const handleAdd = () => {
  navigateToBudget('/budget/budgetInfo/edit', {
    type: 'add',
    projectCategory: DEFAULT_ADD_MARKET_PROJECT_CATEGORY
  });
};

/** 新增研发项目按钮操作 */
const handleAddRd = () => {
  navigateToBudget('/budget/budgetInfo/edit', {
    type: 'add',
    projectCategory: ProjectCategoryEnum.RD
  });
};

/** 查询、修改按钮操作 */
const handleUpdate = async (row?: budgetInfoVO, type?: string, changeFlag?: string) => {
  if (!row?.budgetId) return;
  navigateToBudget('/budget/budgetInfo/edit', {
    type: type ?? 'view',
    id: row.budgetId,
    ...(changeFlag !== undefined && changeFlag !== '' ? { changeFlag } : {}),
    projectCategory: row.projectCategory
  });
};

/** 变更按钮操作 */
const handleChange = async (row?: budgetInfoVO) => {
  if (!row?.budgetId) return;
  navigateToBudget('/budget/budgetInfo/change', {
    type: 'update',
    id: row.budgetId,
    changeFlag: '1',
    projectCategory: row.projectCategory
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: budgetInfoVO) => {
  const _budgetIds = row?.budgetId || ids.value;
  const projectName = row.projectName;
  await proxy?.$modal.confirm('是否确认删除项目名称为"' + projectName + '"的数据项？').finally(() => (loading.value = false));
  await delErpBudgetInfo(_budgetIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = (row?: budgetInfoVO) => {
  if (!row?.budgetId) return;
  const budgetId = row.budgetId;
  const projectName = row.projectName;
  const projectCode = row.projectCode;
  const projectCategory = row.projectCategory;
  const fileNamePrefix = isMarketBudgetCategory(projectCategory) ? '市场项目经费预算表-' : '研发项目经费预算表-';
  proxy?.download(
    'oa/erp/budgetInfo/exportBudgetInfo',
    {
      budgetId: budgetId
    },
    `${fileNamePrefix}${projectCode}_${projectName}_预算表.xlsx`
  );
};

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

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