<template>
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="88px"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          class="!w-240px"
          clearable
          placeholder="请输入项目名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始年度" prop="projectStartYear">
        <el-date-picker
          v-model="queryProjectStartYearValue"
          class="!w-180px"
          clearable
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table
      ref="projectTableRef"
      v-loading="loading"
      :data="projectList"
      highlight-current-row
      @current-change="handleCurrentProjectChange"
    >
      <el-table-column
        :index="getProjectRowIndex"
        align="center"
        label="序号"
        type="index"
        width="80"
      />
      <el-table-column align="center" label="项目名称" min-width="220" prop="projectName" />
      <el-table-column align="center" label="项目经理" min-width="120" prop="projectManagerName" />
      <el-table-column
        align="center"
        label="工程负责人"
        min-width="120"
        prop="engineeringPrincipalName"
      />
      <el-table-column align="center" label="开始年度" prop="projectStartYear" width="120" />
      <el-table-column align="center" label="排序" prop="sortNo" width="80" />
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getProjectList"
    />
  </ContentWrap>

  <SplitPane>
    <template #left>
      <ContentWrap>
        <div class="mb-12px text-14px font-600">
          {{ currentProject?.projectName || '合约规划列表' }}
        </div>
        <el-table
          ref="planningTableRef"
          v-loading="planningLoading"
          :data="planningList"
          highlight-current-row
          @current-change="handleCurrentPlanningChange"
        >
          <el-table-column align="center" label="项目任务包" min-width="180" prop="planningContent" />
          <el-table-column align="center" label="归属类型" min-width="110">
            <template #default="scope">
              {{ getOwnershipTypeLabel(scope.row.ownershipType) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="开始年度" prop="planningStartYear" width="100" />
          <el-table-column align="center" label="考核产值(元)" width="120">
            <template #default="scope">
              {{ formatAmountText(scope.row.assessmentOutputValue) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="排序" prop="sortNo" width="80" />
        </el-table>
      </ContentWrap>
    </template>

    <template #right>
      <ContentWrap>
        <div v-loading="previewLoading" class="min-h-320px">
          <template v-if="currentPlanning && currentGroup">
        <div class="mb-16px flex items-center justify-between gap-12px">
          <div>
            <div class="text-16px font-600">{{ currentPlanning.planningContent }}</div>
            <div class="mt-6px text-12px text-[var(--el-text-color-secondary)]">
              按当前合约规划、年度和专业预览专业内人员计取结果
            </div>
          </div>
          <div class="flex items-center gap-10px">
            <el-date-picker
              v-model="selectedYearValue"
              class="!w-150px"
              clearable
              placeholder="计取年度"
              type="year"
              value-format="YYYY"
            />
            <el-button
              v-hasPermi="['tjt:report-specialty-person:export']"
              :disabled="!canExportCurrentGroup || !selectedYear"
              :loading="exportSpecialtyLoading"
              plain
              type="success"
              @click="handleExportSpecialtyPerson"
            >
              <Icon class="mr-5px" icon="ep:download" />
              导出专业内人员计取表
            </el-button>
          </div>
        </div>

        <div class="mb-16px">
          <el-radio-group v-model="selectedGroupCode" size="small">
            <el-radio-button v-for="item in groupTabOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <el-row :gutter="16" class="mb-16px">
          <el-col v-for="item in buildSummaryCards(currentGroup)" :key="item.label" :span="6">
            <div class="rounded-8px bg-[var(--el-fill-color-light)] px-16px py-12px">
              <div class="text-12px text-[var(--el-text-color-secondary)]">{{ item.label }}</div>
              <div class="mt-6px text-18px font-600">{{ item.value }}</div>
            </div>
          </el-col>
        </el-row>

        <div class="mb-10px flex items-center justify-between gap-12px">
          <div class="text-14px font-600">专业内人员工作量与年度 / 季度计取预览</div>
          <div class="text-12px text-[var(--el-text-color-secondary)]">季度金额单位：万元</div>
        </div>
        <el-table
          :data="currentGroupDisplayRows"
          border
          empty-text="当前年度暂无可预览的专业人员考核产值计取数据"
          :span-method="spanRoleColumns"
        >
          <el-table-column align="center" label="角色" min-width="110" prop="roleName" />
          <el-table-column align="center" label="角色比例" min-width="120">
            <template #default="scope">
              {{ formatPercentText(scope.row.roleRatio) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="角色金额(元)" min-width="130">
            <template #default="scope">
              {{ formatAmountText(scope.row.roleAmount) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="人员合计" min-width="120">
            <template #default="scope">
              {{ formatPercentText(scope.row.personTotalRatio) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="人员明细">
            <el-table-column align="center" label="人员基本分配">
              <el-table-column align="center" label="姓名" min-width="110">
                <template #default="scope">
                  <span class="person-display-name">{{ scope.row.employeeName || '暂无人员' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="工作量比例" min-width="110">
                <template #default="scope">
                  {{ scope.row.employeeName ? formatPercentText(scope.row.personRatio) : '' }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="人员金额(元)" min-width="120">
                <template #default="scope">
                  {{ scope.row.employeeName ? formatAmountText(scope.row.personAmount) : '' }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="占专业比例" min-width="110">
                <template #default="scope">
                  {{ scope.row.employeeName ? formatPercentText(scope.row.adjustedPersonRatio) : '' }}
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="季度计取明细（合约规划年度预览：比例 / 金额 万元）">
              <el-table-column align="center" label="一季度" min-width="150">
                <template #default="scope">
                  {{
                    scope.row.employeeName
                      ? formatRatioAmountText(scope.row.quarterOneRatio, scope.row.quarterOneAmountWan)
                      : ''
                  }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="二季度" min-width="150">
                <template #default="scope">
                  {{
                    scope.row.employeeName
                      ? formatRatioAmountText(scope.row.quarterTwoRatio, scope.row.quarterTwoAmountWan)
                      : ''
                  }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="三季度" min-width="150">
                <template #default="scope">
                  {{
                    scope.row.employeeName
                      ? formatRatioAmountText(scope.row.quarterThreeRatio, scope.row.quarterThreeAmountWan)
                      : ''
                  }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="四季度" min-width="150">
                <template #default="scope">
                  {{
                    scope.row.employeeName
                      ? formatRatioAmountText(scope.row.quarterFourRatio, scope.row.quarterFourAmountWan)
                      : ''
                  }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="本年度小计" min-width="170">
                <template #default="scope">
                  {{
                    scope.row.employeeName
                      ? formatRatioAmountText(scope.row.yearTotalRatio, scope.row.yearTotalAmountWan)
                      : ''
                  }}
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>
        </el-table>
          </template>

          <el-empty v-else-if="!previewLoading" description="请选择合约规划后查看导出预览" />
        </div>
      </ContentWrap>
    </template>
  </SplitPane>
</template>

<script lang="ts" setup>
import * as PlanningApi from '@/api/tjt/planning'
import * as ProjectApi from '@/api/tjt/project'
import * as ReportApi from '@/api/tjt/report'
import download from '@/utils/download'
import SplitPane from '@/views/tjt/shared/SplitPane.vue'
import {
  formatAmountText,
  formatPercentText,
  getOwnershipTypeLabel,
  OUTPUT_SPLIT_SPECIALTY
} from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtReportSpecialtyPerson' })

const PROJECT_LEAD_GROUP_CODE = OUTPUT_SPLIT_SPECIALTY.projectLead

const message = useMessage()
const currentYear = new Date().getFullYear()

const loading = ref(false)
const planningLoading = ref(false)
const previewLoading = ref(false)
const exportSpecialtyLoading = ref(false)
const selectedYear = ref<number | undefined>(currentYear)
const total = ref(0)
const projectList = ref<ProjectApi.ProjectVO[]>([])
const planningList = ref<PlanningApi.ProjectPlanningVO[]>([])
const currentProject = ref<ProjectApi.ProjectVO>()
const currentPlanning = ref<PlanningApi.ProjectPlanningVO>()
const previewData = ref<ReportApi.SpecialtyPersonOutputPreviewRespVO>()
const selectedGroupCode = ref('')
const queryFormRef = ref()
const projectTableRef = ref()
const planningTableRef = ref()

const queryParams = reactive<ProjectApi.ProjectPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  projectName: undefined,
  projectStartYear: undefined
})

const getProjectRowIndex = (index: number) =>
  ((queryParams.pageNo || 1) - 1) * (queryParams.pageSize || 10) + index + 1

const queryProjectStartYearValue = computed({
  get: () => (queryParams.projectStartYear ? String(queryParams.projectStartYear) : undefined),
  set: (value?: string) => {
    queryParams.projectStartYear = value ? Number(value) : undefined
  }
})

const selectedYearValue = computed({
  get: () => (selectedYear.value ? String(selectedYear.value) : undefined),
  set: (value?: string) => {
    selectedYear.value = value ? Number(value) : undefined
  }
})

const formatWanAmountText = (value?: number | string | null) => formatAmountText(value)
const formatRatioAmountText = (
  ratio?: number | string | null,
  amount?: number | string | null
) => `${formatPercentText(ratio)} / ${formatWanAmountText(amount)}`

const groups = computed(() =>
  (previewData.value?.groups || []).filter(
    (item) => item.specialtyCode !== PROJECT_LEAD_GROUP_CODE && item.exportable !== false
  )
)
const groupTabOptions = computed(() =>
  groups.value.map((item) => ({
    label: item.specialtyName,
    value: item.specialtyCode
  }))
)
const currentGroup = computed(
  () => groups.value.find((item) => item.specialtyCode === selectedGroupCode.value) || groups.value[0]
)
const canExportCurrentGroup = computed(
  () => !!currentGroup.value?.specialtyCode && currentGroup.value.exportable !== false
)

type SpecialtyPersonDisplayRow = ReportApi.SpecialtyPersonOutputPreviewPersonRow &
  Pick<
    ReportApi.SpecialtyPersonOutputPreviewRoleRow,
    'specialtyCode' | 'specialtyName' | 'roleCode' | 'roleName' | 'roleRatio' | 'roleAmount' | 'personTotalRatio'
  > & {
    roleRowSpan: number
  }

const currentGroupDisplayRows = computed(() => {
  const displayRows: SpecialtyPersonDisplayRow[] = []
  const rows = currentGroup.value?.rows || []
  rows.forEach((roleRow) => {
    if (!roleRow.persons?.length) {
      displayRows.push({
        specialtyCode: roleRow.specialtyCode,
        specialtyName: roleRow.specialtyName,
        roleCode: roleRow.roleCode,
        roleName: roleRow.roleName,
        roleRatio: roleRow.roleRatio,
        roleAmount: roleRow.roleAmount,
        personTotalRatio: roleRow.personTotalRatio,
        personKey: `${roleRow.specialtyCode}-${roleRow.roleCode}-empty`,
        roleRowSpan: 1
      })
      return
    }
    roleRow.persons.forEach((person, index) => {
      displayRows.push({
        ...person,
        specialtyCode: roleRow.specialtyCode,
        specialtyName: roleRow.specialtyName,
        roleCode: roleRow.roleCode,
        roleName: roleRow.roleName,
        roleRatio: roleRow.roleRatio,
        roleAmount: roleRow.roleAmount,
        personTotalRatio: roleRow.personTotalRatio,
        roleRowSpan: index === 0 ? roleRow.persons.length : 0
      })
    })
  })
  return displayRows
})

const spanRoleColumns = ({ row, columnIndex }: { row: SpecialtyPersonDisplayRow; columnIndex: number }) => {
  if (columnIndex > 3) {
    return { rowspan: 1, colspan: 1 }
  }
  return row.roleRowSpan > 0
    ? { rowspan: row.roleRowSpan, colspan: 1 }
    : { rowspan: 0, colspan: 0 }
}

const buildSummaryCards = (group?: ReportApi.SpecialtyPersonOutputPreviewGroupRow) => {
  if (!group) {
    return []
  }
  return [
    { label: '分组金额', value: `${formatAmountText(group.specialtyAmount)} 元` },
    { label: '角色合计', value: formatPercentText(group.roleTotal) },
    { label: '已配置人数', value: `${group.personCount} 人` },
    { label: '超额提醒', value: group.overRatio ? '存在' : '无' }
  ]
}

watch(
  groups,
  (value) => {
    const codes = value.map((item) => item.specialtyCode)
    if (!codes.length) {
      selectedGroupCode.value = ''
      return
    }
    if (!codes.includes(selectedGroupCode.value)) {
      selectedGroupCode.value = codes[0]
    }
  },
  { immediate: true }
)

const getProjectList = async () => {
  loading.value = true
  try {
    const data = await ProjectApi.getProjectPage(queryParams)
    projectList.value = data.list
    total.value = data.total
    if (!projectList.value.length) {
      currentProject.value = undefined
      planningList.value = []
      currentPlanning.value = undefined
      previewData.value = undefined
      return
    }
    const targetProjectId = currentProject.value?.id || projectList.value[0].id
    const targetProject =
      projectList.value.find((item) => item.id === targetProjectId) || projectList.value[0]
    await nextTick()
    projectTableRef.value?.setCurrentRow(targetProject)
  } finally {
    loading.value = false
  }
}

const getPlanningList = async () => {
  if (!currentProject.value?.id) {
    planningList.value = []
    currentPlanning.value = undefined
    previewData.value = undefined
    return
  }
  planningLoading.value = true
  try {
    const list = await PlanningApi.getProjectPlanningListByProjectId(currentProject.value.id)
    planningList.value = list
    if (!planningList.value.length) {
      currentPlanning.value = undefined
      previewData.value = undefined
      return
    }
    const targetPlanningId = currentPlanning.value?.id || planningList.value[0].id
    const targetPlanning =
      planningList.value.find((item) => item.id === targetPlanningId) || planningList.value[0]
    await nextTick()
    planningTableRef.value?.setCurrentRow(targetPlanning)
  } finally {
    planningLoading.value = false
  }
}

const loadSpecialtyPersonPreview = async () => {
  if (!currentPlanning.value?.id || !selectedYear.value) {
    previewData.value = undefined
    return
  }
  previewLoading.value = true
  try {
    previewData.value = await ReportApi.getSpecialtyPersonOutputPreview({
      planningId: currentPlanning.value.id,
      year: selectedYear.value
    })
  } finally {
    previewLoading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getProjectList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleCurrentProjectChange = async (row?: ProjectApi.ProjectVO) => {
  currentProject.value = row || undefined
  await getPlanningList()
}

const handleCurrentPlanningChange = async (row?: PlanningApi.ProjectPlanningVO) => {
  currentPlanning.value = row || undefined
  if (!row?.id) {
    previewData.value = undefined
    return
  }
  selectedYear.value = row.planningStartYear || currentYear
  previewData.value = undefined
}

const handleExportSpecialtyPerson = async () => {
  if (!currentPlanning.value?.id) {
    message.warning('请先选择合约规划')
    return
  }
  if (!canExportCurrentGroup.value || !currentGroup.value?.specialtyCode) {
    message.warning('请选择具体专业后再导出')
    return
  }
  if (!selectedYear.value) {
    message.warning('请选择年度')
    return
  }
  try {
    await message.exportConfirm()
    exportSpecialtyLoading.value = true
    const data = await ReportApi.exportSpecialtyPersonOutput({
      planningId: currentPlanning.value.id,
      specialtyCode: currentGroup.value.specialtyCode,
      year: selectedYear.value
    })
    download.excel(
      data,
      `${currentProject.value?.projectName || '项目'}_${selectedYear.value}_${currentGroup.value.specialtyName || '专业'}内人员年度季度计取表.xlsx`
    )
  } finally {
    exportSpecialtyLoading.value = false
  }
}

watch(
  [() => currentPlanning.value?.id, selectedYear],
  () => {
    loadSpecialtyPersonPreview()
  }
)

let activatedOnce = false

onMounted(() => {
  getProjectList()
})

onActivated(() => {
  // KeepAlive 首次挂载也会触发 onActivated，跳过首轮避免重复请求项目与合约规划列表。
  if (!activatedOnce) {
    activatedOnce = true
    return
  }
  getProjectList()
})
</script>

<style lang="scss" scoped>
.person-display-name {
  font-weight: 600;
}
</style>
