<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="contractSignedFlag">
        <el-select
          v-model="queryParams.contractSignedFlag"
          class="!w-180px"
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in CONTRACT_SIGN_OPTIONS"
            :key="String(item.value)"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </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"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="是否签约" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.contractSignedFlag ? 'success' : 'info'">
            {{ scope.row.contractSignedFlag ? '已签约' : '未签约' }}
          </el-tag>
        </template>
      </el-table-column>
      <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="合同总产值(元)" width="130">
        <template #default="scope">
          {{ formatAmountText(scope.row.contractAmount) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="建筑面积(㎡)" width="140">
        <template #default="scope">
          {{ formatAreaText(scope.row.totalConstructionArea) }}
        </template>
      </el-table-column>
      <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 v-if="currentProject">
        <div class="mb-16px flex items-center justify-between gap-12px">
          <div>
            <div class="text-16px font-600">{{ currentProject.projectName }}</div>
          </div>
          <el-button
            v-hasPermi="['tjt:report-budget:export']"
            :loading="exportLoading"
            plain
            type="success"
            @click="handleExportProjectBudget"
          >
            <Icon class="mr-5px" icon="ep:download" />
            导出考核产值预算表
          </el-button>
        </div>

        <el-descriptions :column="1" border title="项目信息">
          <el-descriptions-item label="项目名称">
            {{ currentProject.projectName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="项目经理">
            {{ currentProject.projectManagerName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="工程负责人">
            {{ currentProject.engineeringPrincipalName || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="合同总产值(元)">
            {{ formatAmountText(currentProject.contractAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="建筑面积(㎡)">
            {{ formatAreaText(currentProject.totalConstructionArea) }}
          </el-descriptions-item>
          <el-descriptions-item label="开始年度">
            {{ currentProject.projectStartYear || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-row :gutter="12" class="mt-16px">
          <el-col :span="8">
            <div class="rounded-8px bg-[var(--el-fill-color-light)] px-12px py-12px">
              <div class="text-12px text-[var(--el-text-color-secondary)]">合约规划数</div>
              <div class="mt-6px text-18px font-600">{{ planningList.length }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="rounded-8px bg-[var(--el-fill-color-light)] px-12px py-12px">
              <div class="text-12px text-[var(--el-text-color-secondary)]">分项合同产值合计</div>
              <div class="mt-6px text-18px font-600">{{
                formatAmountText(totalPlanningAmount)
              }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="rounded-8px bg-[var(--el-fill-color-light)] px-12px py-12px">
              <div class="text-12px text-[var(--el-text-color-secondary)]">考核产值合计</div>
              <div class="mt-6px text-18px font-600">
                {{ formatAmountText(totalAssessmentOutputValue) }}
              </div>
            </div>
          </el-col>
        </el-row>
      </ContentWrap>

      <ContentWrap v-else>
        <el-empty description="请选择项目后查看预算导出范围" />
      </ContentWrap>
    </template>

    <template #right>
      <ContentWrap>
        <div class="mb-12px flex items-center justify-between">
          <div class="text-14px font-600">
            {{ currentProject?.projectName || '合约规划列表' }}
          </div>
          <el-button v-if="currentProject" size="small" @click="getPlanningList">刷新</el-button>
        </div>
        <el-table v-loading="planningLoading" :data="planningList" border>
          <el-table-column
            align="center"
            label="项目任务包"
            min-width="180"
            prop="planningContent"
          />
          <el-table-column align="center" label="归属类型" width="100">
            <template #default="scope">
              {{ getOwnershipTypeLabel(scope.row.ownershipType) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="计算方式" min-width="110">
            <template #default="scope">
              {{ getCalculationMethodLabel(scope.row.calculationMethod) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="开始年度" width="100" prop="planningStartYear" />
          <el-table-column align="center" label="分项合同产值(元)" width="130">
            <template #default="scope">
              {{ formatAmountText(scope.row.planningAmount) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="考核产值(元)" width="130">
            <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>
  </SplitPane>

  <ContentWrap v-if="currentProject" v-loading="budgetPreviewLoading">
    <div class="mb-12px flex flex-wrap items-center justify-between gap-12px">
      <div>
        <div class="text-16px font-600">考核产值预算表预览</div>
        <div class="mt-4px text-12px text-[var(--el-text-color-secondary)]">
          {{ budgetPreview?.projectName || currentProject.projectName }}
        </div>
      </div>
      <div class="flex items-center gap-8px">
        <span class="text-13px text-[var(--el-text-color-secondary)]">年度</span>
        <el-date-picker
          v-model="previewYearValue"
          class="!w-150px"
          clearable
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
          @change="getProjectBudgetPreview"
        />
        <el-button :loading="budgetPreviewLoading" @click="getProjectBudgetPreview">刷新</el-button>
      </div>
    </div>

    <SplitPane>
      <template #left>
        <div class="budget-preview-pane">
          <div class="mb-12px text-14px font-600">建筑（装饰）工程项目考核产值预算表</div>
          <el-table
            :data="budgetPreview?.budgetRows || []"
            :empty-text="budgetPreviewEmptyText"
            :row-class-name="getBudgetPreviewRowClassName"
            border
            class="budget-preview-table"
            max-height="520"
          >
            <el-table-column
              align="center"
              fixed="left"
              label="规划内容"
              min-width="160"
              prop="planningContent"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              fixed="left"
              label="设计部位"
              min-width="120"
              prop="displayDesignPart"
            />
            <el-table-column
              align="center"
              label="设计内容/设计类型"
              min-width="160"
              prop="displayBuildingType"
              show-overflow-tooltip
            />
            <el-table-column align="center" label="内部指导单价(元/㎡)" min-width="140">
              <template #default="scope">{{
                formatNullableAmount(scope.row.internalGuidanceUnitPrice)
              }}</template>
            </el-table-column>
            <el-table-column align="center" label="设计面积(㎡)" min-width="120">
              <template #default="scope">{{ formatNullableAmount(scope.row.designArea) }}</template>
            </el-table-column>
            <el-table-column
              align="center"
              label="栋数/户型数"
              min-width="110"
              prop="buildingOrUnitCount"
            />
            <el-table-column align="center" label="套图系数" min-width="100">
              <template #default="scope">{{ formatFactor(scope.row.drawingSetFactor) }}</template>
            </el-table-column>
            <el-table-column align="center" label="规模系数" min-width="100">
              <template #default="scope">{{ formatFactor(scope.row.scaleFactor) }}</template>
            </el-table-column>
            <el-table-column align="center" label="修改系数" min-width="100">
              <template #default="scope">{{ formatFactor(scope.row.modificationFactor) }}</template>
            </el-table-column>
            <el-table-column align="center" label="复杂系数/复杂等级" min-width="140">
              <template #default="scope">{{ formatFactor(scope.row.complexityFactor) }}</template>
            </el-table-column>
            <el-table-column align="center" label="小计(㎡)" min-width="120">
              <template #default="scope">{{
                formatNullableAmount(scope.row.subtotalArea)
              }}</template>
            </el-table-column>
            <el-table-column align="center" label="设计阶段占比" min-width="120">
              <template #default="scope">{{
                formatNullablePercent(scope.row.currentDesignStageRatio)
              }}</template>
            </el-table-column>
            <el-table-column align="center" label="考核产值小计(万元)" min-width="150">
              <template #default="scope">{{
                formatNullableAmount(scope.row.assessmentOutputValueWan)
              }}</template>
            </el-table-column>
          </el-table>
          <div
            v-if="budgetPreview?.remark"
            class="mt-10px text-12px text-[var(--el-text-color-secondary)]"
          >
            备注：{{ budgetPreview.remark }}
          </div>
        </div>
      </template>

      <template #right>
        <div class="budget-preview-pane">
          <div class="mb-12px text-14px font-600">项目考核产值年度季度预算计取表</div>
          <el-table
            :data="budgetPreview?.quarterBudgetRows || []"
            :empty-text="budgetPreviewEmptyText"
            :row-class-name="getQuarterPreviewRowClassName"
            border
            class="budget-preview-table"
            max-height="520"
          >
            <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="180"
              show-overflow-tooltip
            >
              <template #default="scope">{{
                scope.row.totalRow ? '项目合计' : budgetPreview?.projectName
              }}</template>
            </el-table-column>
            <el-table-column align="center" label="产值类型" min-width="120" prop="outputType" />
            <el-table-column
              align="center"
              label="设计内容"
              min-width="180"
              prop="designContent"
              show-overflow-tooltip
            />
            <el-table-column align="center" label="总建筑设计面积(㎡)" min-width="150">
              <template #default="scope">{{
                formatNullableAmount(scope.row.totalDesignArea)
              }}</template>
            </el-table-column>
            <el-table-column align="center" label="总考核产值面积(㎡)" min-width="150">
              <template #default="scope">{{
                formatNullableAmount(scope.row.totalAssessmentArea)
              }}</template>
            </el-table-column>
            <el-table-column align="center" label="总考核产值(万元)" min-width="150">
              <template #default="scope">{{
                formatNullableAmount(scope.row.totalAssessmentOutputWan)
              }}</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 ? '' : formatNullablePercent(scope.row.designStageRatio)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="考核产值" min-width="120">
                <template #default="scope">{{
                  formatNullableAmount(scope.row.designStageOutputWan)
                }}</template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="发放情况">
              <el-table-column align="center" label="往年已发放比例" min-width="130">
                <template #default="scope">{{
                  scope.row.totalRow ? '' : formatNullablePercent(scope.row.historicalIssuedRatio)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="一季度" min-width="100">
                <template #default="scope">{{
                  scope.row.totalRow ? '' : formatNullablePercent(scope.row.quarterOneRatio)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="二季度" min-width="100">
                <template #default="scope">{{
                  scope.row.totalRow ? '' : formatNullablePercent(scope.row.quarterTwoRatio)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="三季度" min-width="100">
                <template #default="scope">{{
                  scope.row.totalRow ? '' : formatNullablePercent(scope.row.quarterThreeRatio)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="四季度" min-width="100">
                <template #default="scope">{{
                  scope.row.totalRow ? '' : formatNullablePercent(scope.row.quarterFourRatio)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="本年度小计" min-width="120">
                <template #default="scope">{{
                  scope.row.totalRow ? '' : formatNullablePercent(scope.row.currentYearRatio)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="未发放比例" min-width="120">
                <template #default="scope">{{
                  scope.row.totalRow ? '' : formatNullablePercent(scope.row.pendingRatio)
                }}</template>
              </el-table-column>
            </el-table-column>
            <el-table-column align="center" label="本年度项目考核产值(万元)">
              <el-table-column align="center" label="一季度" min-width="110">
                <template #default="scope">{{
                  formatNullableAmount(scope.row.quarterOneAmountWan)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="二季度" min-width="110">
                <template #default="scope">{{
                  formatNullableAmount(scope.row.quarterTwoAmountWan)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="三季度" min-width="110">
                <template #default="scope">{{
                  formatNullableAmount(scope.row.quarterThreeAmountWan)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="四季度" min-width="110">
                <template #default="scope">{{
                  formatNullableAmount(scope.row.quarterFourAmountWan)
                }}</template>
              </el-table-column>
              <el-table-column align="center" label="本年度小计" min-width="120">
                <template #default="scope">{{
                  formatNullableAmount(scope.row.yearTotalAmountWan)
                }}</template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              align="center"
              label="备注"
              min-width="180"
              prop="ratioRemark"
              show-overflow-tooltip
            />
          </el-table>
        </div>
      </template>
    </SplitPane>
  </ContentWrap>

  <Dialog v-model="exportDialogVisible" title="导出项目考核产值预算表" width="420">
    <el-form label-width="88px">
      <el-form-item label="年度">
        <el-date-picker
          v-model="exportYearValue"
          class="!w-220px"
          clearable
          placeholder="请选择年度"
          type="year"
          value-format="YYYY"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="exportDialogVisible = false">取消</el-button>
      <el-button :loading="exportLoading" type="primary" @click="submitProjectBudgetExport">
        确定导出
      </el-button>
    </template>
  </Dialog>
</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 {
  CONTRACT_SIGN_OPTIONS,
  formatAmountText,
  formatAreaText,
  getCalculationMethodLabel,
  getOwnershipTypeLabel
} from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtReportBudget' })

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

const loading = ref(false)
const planningLoading = ref(false)
const budgetPreviewLoading = ref(false)
const exportLoading = ref(false)
const exportDialogVisible = ref(false)
const previewYear = ref<number>()
const exportYear = ref<number>()
const total = ref(0)
const projectList = ref<ProjectApi.ProjectVO[]>([])
const planningList = ref<PlanningApi.ProjectPlanningVO[]>([])
const budgetPreview = ref<ReportApi.ProjectBudgetPreviewRespVO>()
const currentProject = ref<ProjectApi.ProjectVO>()
const queryFormRef = ref()
const projectTableRef = ref()

const queryParams = reactive<ProjectApi.ProjectPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  projectName: undefined,
  contractSignedFlag: 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 exportYearValue = computed({
  get: () => (exportYear.value ? String(exportYear.value) : undefined),
  set: (value?: string) => {
    exportYear.value = value ? Number(value) : undefined
  }
})

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

const totalPlanningAmount = computed(() =>
  planningList.value.reduce((sum, item) => sum + Number(item.planningAmount || 0), 0)
)
const totalAssessmentOutputValue = computed(() =>
  planningList.value.reduce((sum, item) => sum + Number(item.assessmentOutputValue || 0), 0)
)

const budgetPreviewEmptyText = computed(() =>
  previewYear.value ? '暂无预算表数据' : '请先选择年度'
)

const formatNullableAmount = (value?: number | string | null) => {
  if (value === undefined || value === null || value === '') {
    return ''
  }
  return formatAmountText(value)
}

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

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

const getBudgetPreviewRowClassName = ({ row }: { row: ReportApi.ProjectBudgetPreviewBudgetRow }) =>
  row?.rowType === 'PART_SUBTOTAL' || row?.rowType === 'PLANNING_TOTAL' ? 'budget-total-row' : ''

const getQuarterPreviewRowClassName = ({
  row
}: {
  row: ReportApi.ProjectBudgetPreviewQuarterRow
}) => (row?.totalRow ? 'budget-total-row' : '')

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 = []
      budgetPreview.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 = []
    return
  }
  planningLoading.value = true
  try {
    planningList.value = await PlanningApi.getProjectPlanningListByProjectId(
      currentProject.value.id
    )
  } finally {
    planningLoading.value = false
  }
}

const getProjectBudgetPreview = async () => {
  if (!currentProject.value?.id || !previewYear.value) {
    budgetPreview.value = undefined
    return
  }
  budgetPreviewLoading.value = true
  try {
    budgetPreview.value = await ReportApi.getProjectBudgetPreview({
      projectId: currentProject.value.id,
      year: previewYear.value
    })
  } finally {
    budgetPreviewLoading.value = false
  }
}

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

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

const handleCurrentProjectChange = async (row?: ProjectApi.ProjectVO) => {
  currentProject.value = row || undefined
  previewYear.value = row?.projectStartYear || currentYear
  await Promise.all([getPlanningList(), getProjectBudgetPreview()])
}

const handleExportProjectBudget = async () => {
  if (!currentProject.value?.id) {
    message.warning('请先选择项目')
    return
  }
  exportYear.value = currentProject.value.projectStartYear || currentYear
  exportDialogVisible.value = true
}

const submitProjectBudgetExport = async () => {
  if (!currentProject.value?.id) {
    message.warning('请先选择项目')
    return
  }
  if (!exportYear.value) {
    message.warning('请选择年度')
    return
  }
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await ReportApi.exportProjectBudget({
      projectId: currentProject.value.id,
      year: exportYear.value
    })
    download.excel(
      data,
      `${currentProject.value.projectName}_${exportYear.value}_项目考核产值预算表.xlsx`
    )
    exportDialogVisible.value = false
  } finally {
    exportLoading.value = false
  }
}

let activatedOnce = false

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

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

<style scoped>
.budget-preview-pane {
  min-width: 0;
}

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