<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 align="center" label="项目ID" prop="id" width="88" />
      <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>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getProjectList"
    />
  </ContentWrap>

  <el-row :gutter="16">
    <el-col :span="8">
      <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>
    </el-col>

    <el-col :span="16">
      <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="开始年度" 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>
      </ContentWrap>
    </el-col>
  </el-row>
</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 {
  CONTRACT_SIGN_OPTIONS,
  formatAmountText,
  formatAreaText,
  getOwnershipTypeLabel
} from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtReportBudget' })

const message = useMessage()

const loading = ref(false)
const planningLoading = ref(false)
const exportLoading = ref(false)
const total = ref(0)
const projectList = ref<ProjectApi.ProjectVO[]>([])
const planningList = ref<PlanningApi.ProjectPlanningVO[]>([])
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 queryProjectStartYearValue = computed({
  get: () => (queryParams.projectStartYear ? String(queryParams.projectStartYear) : undefined),
  set: (value?: string) => {
    queryParams.projectStartYear = 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 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 = []
      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 handleQuery = () => {
  queryParams.pageNo = 1
  getProjectList()
}

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

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

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

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

onActivated(() => {
  getProjectList()
})
</script>
