<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="项目编号" prop="projectCode">
        <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="业务方向" prop="businessDirection">
        <el-select v-model="queryParams.businessDirection" placeholder="请选择业务方向" clearable style="width: 200px">
          <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="projectStatus">
        <el-select v-model="queryParams.projectStatus" placeholder="请选择项目状态" clearable style="width: 200px">
          <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="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择部门" clearable filterable style="width: 200px">
          <el-option v-for="dept in deptOptions" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型" prop="projectTypeId">
        <el-select v-model="queryParams.projectTypeId" placeholder="请选择项目类型" clearable style="width: 200px">
          <el-option v-for="item in projectTypeOptions" :key="item.projectTypeId" :label="item.typeName" :value="item.projectTypeId" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目阶段" prop="projectPhases">
        <el-select v-model="queryParams.projectPhases" placeholder="请选择项目阶段" clearable style="width: 200px">
          <el-option v-for="dict in project_phases" :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-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="reportList" border @selection-change="handleSelectionChange">
      <!-- ========== 基本信息 ========== -->
      <el-table-column label="基本信息" align="center">
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
        <el-table-column label="项目编号" prop="projectCode" width="140" align="center" fixed="left" show-overflow-tooltip />
        <el-table-column label="客户名称" prop="customerName" width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.customerName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="项目名称" prop="projectName" width="200" align="center" show-overflow-tooltip />
        <el-table-column label="项目经理" prop="managerName" width="90" align="center" />
        <el-table-column label="部门" prop="deptName" width="120" align="center" show-overflow-tooltip />
        <el-table-column label="项目类型" prop="typeName" width="120" align="center" show-overflow-tooltip />
        <el-table-column label="产品数量" width="100" align="center">
          <template #default>-</template>
        </el-table-column>
        <el-table-column label="项目阶段" width="100" align="center">
          <template #default="scope">
            <dict-tag v-if="scope.row.projectPhases" :options="project_phases" :value="scope.row.projectPhases" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="情况说明" width="120" align="center">
          <template #default>-</template>
        </el-table-column>
        <el-table-column label="状态" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.projectProgressStatus || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="预计验收时间" width="120" align="center">
          <template #default="scope">
            {{ scope.row.expectedAcceptanceTime ? scope.row.expectedAcceptanceTime.substring(0, 10) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="实际验收时间" width="120" align="center">
          <template #default="scope">
            {{ scope.row.acceptanceDate ? scope.row.acceptanceDate.substring(0, 10) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="是否异常启动" width="120" align="center">
          <template #default="scope">{{ scope.row.abnormalStartup || '-' }}</template>
        </el-table-column>
        <el-table-column label="异常启动原因" width="120" align="center">
          <template #default="scope">{{ scope.row.abnormalStartupReason || '-' }}</template>
        </el-table-column>
      </el-table-column>

      <!-- ========== 合同信息 ========== -->
      <el-table-column label="合同信息" align="center">
        <el-table-column label="签订时间" min-width="110" align="center">
          <template #default="scope">
            <span style="white-space: pre-line">{{ scope.row.contractDate || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同额" min-width="120" align="center">
          <template #default="scope">
            <span style="white-space: pre-line">{{ scope.row.contractAmount != null ? scope.row.contractAmount : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户经理" min-width="90" align="center">
          <template #default="scope">
            <span style="white-space: pre-line">{{ scope.row.contractManagerName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="付款方式" min-width="220" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span style="white-space: pre-line">{{ scope.row.paymentMethod || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="质保期描述" min-width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span style="white-space: pre-line">{{ scope.row.warrantyPeriodDescription || '-' }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- ========== 预算及成本 ========== -->
      <el-table-column label="预算及成本" align="center">
        <el-table-column label="预算" width="120" align="center">
          <template #default="scope">
            {{ scope.row.budgetCost != null ? formatNumber(scope.row.budgetCost) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="预算毛利率" width="100" align="center">
          <template #default="scope">
            {{ scope.row.budgetRate != null ? scope.row.budgetRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="降成本后预算" width="130" align="center">
          <template #default="scope">
            {{ scope.row.reduceBudgetCost != null ? formatNumber(scope.row.reduceBudgetCost) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="降成本后预算毛利率" width="150" align="center">
          <template #default="scope">
            {{ scope.row.reduceBudgetRate != null ? scope.row.reduceBudgetRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="累计工时" width="100" align="center">
          <template #default="scope">
            {{ scope.row.totalHours != null ? scope.row.totalHours : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="已发生成本" width="110" align="center">
          <template #default>-</template>
        </el-table-column>
        <el-table-column label="合同净额" width="120" align="center">
          <template #default="scope">
            {{ scope.row.revenue != null ? formatNumber(scope.row.revenue) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="已发生成本占收入比例" width="160" align="center">
          <template #default="scope">
            {{
              scope.row.actualCost != null && scope.row.revenue != null && scope.row.revenue != 0
                ? (Math.round((scope.row.actualCost / scope.row.revenue) * 10000) / 100).toFixed(2) + '%'
                : '-'
            }}
          </template>
        </el-table-column>
      </el-table-column>

      <!-- ========== 进度信息 ========== -->
      <el-table-column label="进度信息" align="center">
        <!-- 启动 -->
        <el-table-column label="启动" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.startupPlanStartTime ? scope.row.startupPlanStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.startupPlanEndTime ? scope.row.startupPlanEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.startupRealStartTime ? scope.row.startupRealStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.startupRealEndTime ? scope.row.startupRealEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 设计 -->
        <el-table-column label="设计" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.designPlanStartTime ? scope.row.designPlanStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.designPlanEndTime ? scope.row.designPlanEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.designRealStartTime ? scope.row.designRealStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.designRealEndTime ? scope.row.designRealEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 采购与发货 -->
        <el-table-column label="采购与发货" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.purchaseShipmentPlanStartTime ? scope.row.purchaseShipmentPlanStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.purchaseShipmentPlanEndTime ? scope.row.purchaseShipmentPlanEndTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.purchaseShipmentRealStartTime ? scope.row.purchaseShipmentRealStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #header>
              <span style="color: red">实际结束时间</span>
            </template>
            <template #default="scope">{{
              scope.row.purchaseShipmentRealEndTime ? scope.row.purchaseShipmentRealEndTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 开发 -->
        <el-table-column label="开发" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.developPlanStartTime ? scope.row.developPlanStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.developPlanEndTime ? scope.row.developPlanEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.developRealStartTime ? scope.row.developRealStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.developRealEndTime ? scope.row.developRealEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 组装调试（设备类） -->
        <el-table-column label="组装调试（设备类）" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.assemblyDebugPlanStartTime ? scope.row.assemblyDebugPlanStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.assemblyDebugPlanEndTime ? scope.row.assemblyDebugPlanEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.assemblyDebugRealStartTime ? scope.row.assemblyDebugRealStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.assemblyDebugRealEndTime ? scope.row.assemblyDebugRealEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 实施与安装调试 -->
        <el-table-column label="实施与安装调试" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.implementDebugPlanStartTime ? scope.row.implementDebugPlanStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.implementDebugPlanEndTime ? scope.row.implementDebugPlanEndTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.implementDebugRealStartTime ? scope.row.implementDebugRealStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.implementDebugRealEndTime ? scope.row.implementDebugRealEndTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 测试与试运行 -->
        <el-table-column label="测试与试运行" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.testPilotRunPlanStartTime ? scope.row.testPilotRunPlanStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.testPilotRunPlanEndTime ? scope.row.testPilotRunPlanEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{
              scope.row.testPilotRunRealStartTime ? scope.row.testPilotRunRealStartTime.substring(0, 10) : '-'
            }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.testPilotRunRealEndTime ? scope.row.testPilotRunRealEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 验收 -->
        <el-table-column label="验收" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.acceptancePlanStartTime ? scope.row.acceptancePlanStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.acceptancePlanEndTime ? scope.row.acceptancePlanEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.acceptanceRealStartTime ? scope.row.acceptanceRealStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column width="110" align="center">
            <template #header>
              <span style="color: red">实际结束时间</span>
            </template>
            <template #default="scope">{{ scope.row.acceptanceRealEndTime ? scope.row.acceptanceRealEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
        </el-table-column>
        <!-- 质保 -->
        <el-table-column label="质保" align="center">
          <el-table-column label="计划开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.warrantyPlanStartTime ? scope.row.warrantyPlanStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="计划结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.warrantyPlanEndTime ? scope.row.warrantyPlanEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际开始时间" width="110" align="center">
            <template #default="scope">{{ scope.row.warrantyRealStartTime ? scope.row.warrantyRealStartTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
          <el-table-column label="实际结束时间" width="110" align="center">
            <template #default="scope">{{ scope.row.warrantyRealEndTime ? scope.row.warrantyRealEndTime.substring(0, 10) : '-' }}</template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
  </div>
</template>

<script setup lang="ts" name="ProjectLedgerReport">
import { listProjectLedgerReport, ProjectLedgerReportQuery, ProjectLedgerReportVO } from '@/api/oa/erp/projectLedgerReport';
import { allListDept, listDept } from '@/api/system/dept';
import { getErpProjectTypeList } from '@/api/oa/erp/projectType/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { business_direction, project_status, project_phases } = toRefs<any>(proxy?.useDict('business_direction', 'project_status', 'project_phases'));

const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const reportList = ref<ProjectLedgerReportVO[]>([]);
const selectedRows = ref<ProjectLedgerReportVO[]>([]);
const queryFormRef = ref<ElFormInstance>();
const deptOptions = ref<any[]>([]);
const projectTypeOptions = ref<any[]>([]);

const queryParams = reactive<ProjectLedgerReportQuery>({
  pageNum: 1,
  pageSize: 30,
  projectCode: undefined,
  projectName: undefined,
  businessDirection: undefined,
  projectStatus: undefined,
  deptId: undefined,
  projectTypeId: undefined,
  projectPhases: undefined
});

/** 格式化数字 */
const formatNumber = (num: number) => {
  return num?.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

/** 查询报表列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listProjectLedgerReport(queryParams);
    reportList.value = res.rows || [];
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProjectLedgerReportVO[]) => {
  selectedRows.value = selection;
};

/** 导出按钮操作 */
const handleExport = () => {
  const exportParams: any = { ...queryParams };

  // 只导出选中的数据，传递到后端的 params.projectIds 中
  if (selectedRows.value.length > 0) {
    exportParams['params[projectIds]'] = selectedRows.value.map((row) => row.projectId).join(',');
  }

  proxy?.download('/oa/erp/projectLedgerReport/export', exportParams, `项目台账报表_${new Date().getTime()}.xlsx`);
};

const getDeptList = async () => {
  // 查询所有部门用于前端筛选
  const res = await allListDept({ deptCategory: '03' } as any);
  deptOptions.value = res.data || res.rows || [];
};

/** 查询项目类型 */
const getProjectTypeList = async () => {
  const res = await getErpProjectTypeList({});
  projectTypeOptions.value = res.data;
};

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

<style scoped>
:deep(.el-table .el-table__header th) {
  font-weight: 600;
}
</style>
