<template>
  <ContentWrap>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="员工个人考核产值汇总表" name="employeeSummary">
        <el-form :inline="true" :model="employeeSummaryForm" label-width="88px">
          <el-form-item label="年度">
            <el-date-picker
              v-model="employeeSummaryYearValue"
              class="!w-180px"
              clearable
              placeholder="请选择年度"
              type="year"
              value-format="YYYY"
            />
          </el-form-item>
          <el-form-item>
            <el-button :loading="employeeSummaryPreviewLoading" @click="getEmployeeSummaryPreview">
              <Icon class="mr-5px" icon="ep:refresh" />
              刷新预览
            </el-button>
            <el-button
              v-hasPermi="['tjt:report-summary:export']"
              :loading="employeeSummaryExportLoading"
              plain
              type="primary"
              @click="openEmployeeSummaryExportDialog"
            >
              <Icon class="mr-5px" icon="ep:download" />
              导出员工汇总
            </el-button>
          </el-form-item>
        </el-form>

        <el-table
          v-loading="employeeSummaryPreviewLoading"
          :data="employeeSummaryRows"
          :empty-text="employeeSummaryForm.year ? '暂无员工个人考核产值汇总数据' : '请先选择年度'"
          :row-class-name="getRowClassName"
          border
          class="summary-table"
          max-height="640"
        >
          <el-table-column align="center" fixed="left" label="序号" width="70">
            <template #default="scope">
              {{ scope.row.totalRow ? '' : scope.row.serialNo }}
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="left" label="专业所" min-width="140" prop="officeName" />
          <el-table-column align="center" fixed="left" label="姓名" min-width="120" prop="employeeName" />
          <el-table-column align="center" label="第一季度" min-width="110">
            <template #default="scope">{{ formatAmount(scope.row.quarterOneAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="第二季度" min-width="110">
            <template #default="scope">{{ formatAmount(scope.row.quarterTwoAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="第三季度" min-width="110">
            <template #default="scope">{{ formatAmount(scope.row.quarterThreeAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="第四季度" min-width="110">
            <template #default="scope">{{ formatAmount(scope.row.quarterFourAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="年度合计" min-width="110">
            <template #default="scope">{{ formatAmount(scope.row.annualTotalAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="所长 / BIM 考核产值" min-width="150">
            <template #default="scope">{{ formatAmount(scope.row.officeLeaderOrBimAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="年度考核产值合计" min-width="150">
            <template #default="scope">{{ formatAmount(scope.row.totalAssessmentOutputAmount) }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            label="1~12 月份预计发生成本（含预计精神文明奖）"
            min-width="220"
          >
            <template #default="scope">{{ formatAmount(scope.row.expectedCostAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="基本考核产值" min-width="130">
            <template #default="scope">{{ formatAmount(scope.row.basicAssessmentOutputAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="剩余产值" min-width="120">
            <template #default="scope">{{ formatAmount(scope.row.remainingOutputAmount) }}</template>
          </el-table-column>
          <el-table-column align="center" label="预估年底绩效" min-width="130">
            <template #default="scope">{{ formatAmount(scope.row.estimatedYearEndPerformanceAmount) }}</template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="项目总览表" name="projectOverview">
        <el-form :inline="true" :model="projectOverviewForm" label-width="88px">
          <el-form-item label="专业所">
            <el-select
              v-model="projectOverviewForm.officeId"
              class="!w-220px"
              clearable
              placeholder="请选择专业所"
            >
              <el-option
                v-for="item in officeOptions"
                :key="item.id"
                :label="item.officeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="年度">
            <el-date-picker
              v-model="projectOverviewYearValue"
              class="!w-180px"
              clearable
              placeholder="请选择年度"
              type="year"
              value-format="YYYY"
            />
          </el-form-item>
          <el-form-item>
            <el-button :loading="projectOverviewPreviewLoading" @click="getProjectOverviewPreview">
              <Icon class="mr-5px" icon="ep:refresh" />
              刷新预览
            </el-button>
            <el-button
              v-hasPermi="['tjt:report-summary:export']"
              :loading="projectOverviewExportLoading"
              plain
              type="primary"
              @click="openProjectOverviewExportDialog"
            >
              <Icon class="mr-5px" icon="ep:download" />
              导出项目总览
            </el-button>
          </el-form-item>
        </el-form>

        <el-table
          v-loading="projectOverviewPreviewLoading"
          :data="projectOverviewRows"
          :empty-text="projectOverviewEmptyText"
          :row-class-name="getRowClassName"
          border
          class="summary-table"
          max-height="640"
        >
          <el-table-column align="center" fixed="left" label="序号" width="70">
            <template #default="scope">
              {{ scope.row.totalRow ? '' : scope.row.serialNo }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            fixed="left"
            label="项目名称"
            min-width="220"
            prop="projectName"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="工程进度情况及其它说明"
            min-width="240"
            prop="progressText"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="工作阶段"
            min-width="180"
            prop="workStage"
            show-overflow-tooltip
          />
          <el-table-column align="center" label="本专业 + 项目总核算总产值" min-width="170">
            <template #default="scope">{{ formatAmountBlank(scope.row.totalOutputAmountWan) }}</template>
          </el-table-column>
          <el-table-column align="center" label="往期已发放百分比" min-width="140">
            <template #default="scope">
              {{ scope.row.totalRow ? '' : formatPercent(scope.row.historicalIssuedRatio) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="本期结算">
            <el-table-column align="center" label="占比" min-width="110">
              <template #default="scope">
                {{ scope.row.totalRow ? '' : formatPercent(scope.row.currentSettlementRatio) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="考核产值" min-width="120">
              <template #default="scope">
                {{ formatAmountBlank(scope.row.currentSettlementAmountWan) }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label="未结算比例" min-width="120">
            <template #default="scope">
              {{ scope.row.totalRow ? '' : formatPercent(scope.row.pendingRatio) }}
            </template>
          </el-table-column>
          <el-table-column
            v-for="employee in projectOverviewEmployeeColumns"
            :key="employee.employeeId"
            align="center"
            :label="employee.employeeName || '-'"
          >
            <el-table-column align="center" label="一季度" min-width="100">
              <template #default="scope">
                {{ formatAmountBlank(getEmployeeAmount(scope.row, employee.employeeId).quarterOneAmountWan) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="二季度" min-width="100">
              <template #default="scope">
                {{ formatAmountBlank(getEmployeeAmount(scope.row, employee.employeeId).quarterTwoAmountWan) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="三季度" min-width="100">
              <template #default="scope">
                {{ formatAmountBlank(getEmployeeAmount(scope.row, employee.employeeId).quarterThreeAmountWan) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="四季度" min-width="100">
              <template #default="scope">
                {{ formatAmountBlank(getEmployeeAmount(scope.row, employee.employeeId).quarterFourAmountWan) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="本年度小计" min-width="120">
              <template #default="scope">
                {{ formatAmountBlank(getEmployeeAmount(scope.row, employee.employeeId).annualTotalAmountWan) }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>

  <Dialog v-model="exportDialogVisible" :title="exportDialogTitle" width="480">
    <el-form label-width="88px">
      <template v-if="exportDialogType === 'employeeSummary'">
        <el-form-item label="年度">
          <span>{{ employeeSummaryForm.year || '-' }}</span>
        </el-form-item>
        <el-form-item label="导出排序">
          <el-select
            v-model="employeeSummaryForm.sortType"
            class="!w-220px"
            placeholder="请选择导出排序"
          >
            <el-option
              v-for="item in EMPLOYEE_SUMMARY_SORT_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </template>

      <template v-else>
        <el-form-item label="专业所">
          <span>{{ currentOfficeName || '-' }}</span>
        </el-form-item>
        <el-form-item label="年度">
          <span>{{ projectOverviewForm.year || '-' }}</span>
        </el-form-item>
        <el-form-item label="导出排序">
          <el-select
            v-model="projectOverviewForm.sortType"
            class="!w-220px"
            placeholder="请选择导出排序"
          >
            <el-option
              v-for="item in PROJECT_OVERVIEW_SORT_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </template>
    </el-form>

    <template #footer>
      <el-button @click="exportDialogVisible = false">取消</el-button>
      <el-button :loading="currentExportLoading" type="primary" @click="submitExport">
        确定导出
      </el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as OfficeApi from '@/api/tjt/office'
import * as ReportApi from '@/api/tjt/report'
import download from '@/utils/download'

defineOptions({ name: 'TjtReportSummary' })

type SelectOption = {
  label: string
  value: string
}

type ExportDialogType = 'employeeSummary' | 'projectOverview'

type SummaryTableRow = {
  totalRow?: boolean
}

const PROJECT_OVERVIEW_SORT_OPTIONS: SelectOption[] = [
  { label: '产值从高到低', value: 'output_desc' },
  { label: '产值从低到高', value: 'output_asc' },
  { label: '项目名称升序', value: 'name_asc' }
]

const EMPLOYEE_SUMMARY_SORT_OPTIONS: SelectOption[] = [
  { label: '专业所 + 所内年度合计从高到低', value: 'annual_total_desc' },
  { label: '专业所 + 所内年度合计从低到高', value: 'annual_total_asc' },
  { label: '专业所 + 所内姓名升序', value: 'name_asc' }
]

const message = useMessage()

const activeTab = ref('employeeSummary')
const exportDialogVisible = ref(false)
const exportDialogType = ref<ExportDialogType>('employeeSummary')
const projectOverviewExportLoading = ref(false)
const employeeSummaryExportLoading = ref(false)
const employeeSummaryPreviewLoading = ref(false)
const projectOverviewPreviewLoading = ref(false)
const officeOptions = ref<OfficeApi.OfficeSimpleVO[]>([])
const employeeSummaryPreview = ref<ReportApi.EmployeeOutputSummaryPreviewRespVO>()
const projectOverviewPreview = ref<ReportApi.ProjectOverviewPreviewRespVO>()
const currentYear = new Date().getFullYear()

const projectOverviewForm = reactive<ReportApi.ProjectOverviewExportReqVO>({
  year: currentYear,
  officeId: undefined,
  sortType: 'output_desc'
})

const employeeSummaryForm = reactive<ReportApi.EmployeeOutputSummaryExportReqVO>({
  year: currentYear,
  officeId: undefined,
  employeeId: undefined,
  employeeStatus: undefined,
  sortType: 'annual_total_desc'
})

const employeeSummaryRows = computed<ReportApi.EmployeeOutputSummaryRow[]>(() => {
  const rows = employeeSummaryPreview.value?.rows || []
  const totalRow = employeeSummaryPreview.value?.totalRow
  if (!totalRow) {
    return rows
  }
  return [...rows, { ...totalRow, totalRow: true }]
})

const projectOverviewEmployeeColumns = computed(
  () => projectOverviewPreview.value?.employeeColumns || []
)

const projectOverviewRows = computed<ReportApi.ProjectOverviewProjectRow[]>(() => {
  const rows = projectOverviewPreview.value?.rows || []
  const totalRow = projectOverviewPreview.value?.totalRow
  if (!totalRow) {
    return rows
  }
  return [...rows, { ...totalRow, totalRow: true }]
})

const exportDialogTitle = computed(() =>
  exportDialogType.value === 'employeeSummary' ? '导出员工个人考核产值汇总表' : '导出项目总览表'
)

const currentExportLoading = computed(() =>
  exportDialogType.value === 'employeeSummary'
    ? employeeSummaryExportLoading.value
    : projectOverviewExportLoading.value
)

const currentOfficeName = computed(() => {
  return officeOptions.value.find((item) => item.id === projectOverviewForm.officeId)?.officeName || ''
})

const projectOverviewEmptyText = computed(() => {
  if (!projectOverviewForm.officeId) {
    return '请先选择专业所'
  }
  if (!projectOverviewForm.year) {
    return '请先选择年度'
  }
  return '暂无项目总览数据'
})

const projectOverviewYearValue = computed({
  get: () => (projectOverviewForm.year ? String(projectOverviewForm.year) : undefined),
  set: (value?: string) => {
    projectOverviewForm.year = value ? Number(value) : undefined
  }
})

const employeeSummaryYearValue = computed({
  get: () => (employeeSummaryForm.year ? String(employeeSummaryForm.year) : undefined),
  set: (value?: string) => {
    employeeSummaryForm.year = value ? Number(value) : undefined
  }
})

const formatAmount = (value?: number) => {
  if (value === undefined || value === null) {
    return ''
  }
  return Number(value).toFixed(2)
}

const formatAmountBlank = (value?: number) => {
  if (value === undefined || value === null || Number(value) === 0) {
    return ''
  }
  return Number(value).toFixed(2)
}

const formatPercent = (value?: number) => {
  if (value === undefined || value === null || Number(value) === 0) {
    return ''
  }
  return `${(Number(value) * 100).toFixed(2)}%`
}

const getEmployeeAmount = (
  row: ReportApi.ProjectOverviewProjectRow,
  employeeId?: number
): ReportApi.ProjectOverviewEmployeeAmountValue => {
  if (!employeeId || !row.employeeAmountMap) {
    return {}
  }
  return row.employeeAmountMap[String(employeeId)] || {}
}

const getRowClassName = ({ row }: { row: SummaryTableRow }) => {
  return row?.totalRow ? 'summary-total-row' : ''
}

const getOfficeList = async () => {
  officeOptions.value = await OfficeApi.getOfficeSimpleList()
}

const getEmployeeSummaryPreview = async () => {
  if (!employeeSummaryForm.year) {
    employeeSummaryPreview.value = undefined
    return
  }
  employeeSummaryPreviewLoading.value = true
  try {
    employeeSummaryPreview.value = await ReportApi.getEmployeeOutputSummaryPreview(employeeSummaryForm)
  } finally {
    employeeSummaryPreviewLoading.value = false
  }
}

const getProjectOverviewPreview = async () => {
  if (!projectOverviewForm.officeId || !projectOverviewForm.year) {
    projectOverviewPreview.value = undefined
    return
  }
  projectOverviewPreviewLoading.value = true
  try {
    projectOverviewPreview.value = await ReportApi.getProjectOverviewPreview(projectOverviewForm)
  } finally {
    projectOverviewPreviewLoading.value = false
  }
}

const openEmployeeSummaryExportDialog = () => {
  if (!employeeSummaryForm.year) {
    message.warning('请选择年度')
    return
  }
  exportDialogType.value = 'employeeSummary'
  exportDialogVisible.value = true
}

const openProjectOverviewExportDialog = () => {
  if (!projectOverviewForm.officeId) {
    message.warning('请选择专业所')
    return
  }
  if (!projectOverviewForm.year) {
    message.warning('请选择年度')
    return
  }
  exportDialogType.value = 'projectOverview'
  exportDialogVisible.value = true
}

const submitExport = async () => {
  if (exportDialogType.value === 'employeeSummary') {
    await handleExportEmployeeSummary()
    return
  }
  await handleExportProjectOverview()
}

const handleExportProjectOverview = async () => {
  if (!projectOverviewForm.officeId) {
    message.warning('请选择专业所')
    return
  }
  if (!projectOverviewForm.year) {
    message.warning('请选择年度')
    return
  }
  try {
    projectOverviewExportLoading.value = true
    const data = await ReportApi.exportProjectOverview(projectOverviewForm)
    download.excel(
      data,
      `${currentOfficeName.value || '专业所'}_${projectOverviewForm.year}_项目总览表.xlsx`
    )
    exportDialogVisible.value = false
  } finally {
    projectOverviewExportLoading.value = false
  }
}

const handleExportEmployeeSummary = async () => {
  if (!employeeSummaryForm.year) {
    message.warning('请选择年度')
    return
  }
  try {
    employeeSummaryExportLoading.value = true
    const data = await ReportApi.exportEmployeeOutputSummary(employeeSummaryForm)
    download.excel(data, `${employeeSummaryForm.year}_员工个人考核产值汇总表.xlsx`)
    exportDialogVisible.value = false
  } finally {
    employeeSummaryExportLoading.value = false
  }
}

const refreshCurrentPreview = () => {
  if (activeTab.value === 'projectOverview') {
    getProjectOverviewPreview()
    return
  }
  getEmployeeSummaryPreview()
}

watch(
  () => [employeeSummaryForm.year, employeeSummaryForm.sortType],
  () => {
    getEmployeeSummaryPreview()
  },
  { immediate: true }
)

watch(
  () => [projectOverviewForm.officeId, projectOverviewForm.year, projectOverviewForm.sortType],
  () => {
    getProjectOverviewPreview()
  },
  { immediate: true }
)

watch(
  () => activeTab.value,
  () => {
    refreshCurrentPreview()
  }
)

let activatedOnce = false

onActivated(() => {
  // immediate watch 已经负责首次预览加载，跳过 KeepAlive 首轮激活避免重复请求。
  if (!activatedOnce) {
    activatedOnce = true
    return
  }
  refreshCurrentPreview()
})

onMounted(async () => {
  await getOfficeList()
})
</script>

<style scoped>
.summary-table :deep(.summary-total-row) {
  background: var(--el-fill-color-light);
  font-weight: 700;
}
</style>
