<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="profitTableRef"
      v-loading="loading"
      :data="list"
      highlight-current-row
      @current-change="handleCurrentProfitChange"
    >
      <el-table-column align="center" label="工程名称" min-width="220" prop="projectName" />
      <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="开始年度" prop="projectStartYear" width="100" />
      <el-table-column align="center" label="合同金额(元)" width="120">
        <template #default="scope">
          {{ formatAmountText(scope.row.contractAmount) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="最终结算金额(元)" width="140">
        <template #default="scope">
          {{ formatAmountText(scope.row.finalSettlementAmount) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="综合所协作金额(元)" width="150">
        <template #default="scope">
          {{ formatAmountText(scope.row.comprehensivePlanningAmount) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="专业分包金额(元)" width="150">
        <template #default="scope">
          {{ formatAmountText(scope.row.subcontractPlanningAmount) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="专业所产值(元)" width="130">
        <template #default="scope">
          {{ formatAmountText(scope.row.majorOutputValue) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="专业所预计绩效(元)" width="150">
        <template #default="scope">
          {{ formatAmountText(scope.row.majorExpectedPerformance) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="科创产值比例" width="110">
        <template #default="scope">
          {{ formatPercentText(scope.row.innovationOutputRate) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="科创产值(元)" width="130">
        <template #default="scope">
          {{ formatAmountText(scope.row.innovationOutputValue) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="其他成本(元)" width="130">
        <template #default="scope">
          {{ formatAmountText(scope.row.otherCost) }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="盈亏值(元)" width="120">
        <template #default="scope">
          <span :class="profitLossClass(scope.row.profitLossValue)">
            {{ formatAmountText(scope.row.profitLossValue) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="盈亏百分比" width="120">
        <template #default="scope">
          <span :class="profitLossClass(scope.row.profitLossValue)">
            {{ formatPercentText(scope.row.profitLossRate) }}
          </span>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <ContentWrap v-if="currentProfit">
    <div class="mb-16px flex items-center justify-between gap-16px">
      <div class="text-16px font-600">{{ currentProfit.projectName }}</div>
      <el-button plain type="primary" @click="openProfitEditDialog">
        <Icon class="mr-5px" icon="ep:edit" />
        编辑盈亏参数
      </el-button>
    </div>

    <el-descriptions :column="3" border>
      <el-descriptions-item label="合同金额(元)">
        {{ formatAmountText(currentProfit.contractAmount) }}
      </el-descriptions-item>
      <el-descriptions-item label="最终结算金额(元)">
        {{ formatAmountText(currentProfit.finalSettlementAmount) }}
      </el-descriptions-item>
      <el-descriptions-item label="项目开始年度">
        {{ currentProfit.projectStartYear || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="综合所协作金额(元)">
        {{ formatAmountText(currentProfit.comprehensivePlanningAmount) }}
      </el-descriptions-item>
      <el-descriptions-item label="专业分包金额(元)">
        {{ formatAmountText(currentProfit.subcontractPlanningAmount) }}
      </el-descriptions-item>
      <el-descriptions-item label="专业所产值(元)">
        {{ formatAmountText(currentProfit.majorOutputValue) }}
      </el-descriptions-item>
      <el-descriptions-item label="专业所预计绩效(元)">
        {{ formatAmountText(currentProfit.majorExpectedPerformance) }}
      </el-descriptions-item>
      <el-descriptions-item label="科创产值比例">
        {{ formatPercentText(currentProfit.innovationOutputRate) }}
      </el-descriptions-item>
      <el-descriptions-item label="科创产值(元)">
        {{ formatAmountText(currentProfit.innovationOutputValue) }}
      </el-descriptions-item>
      <el-descriptions-item label="其他成本(元)">
        {{ formatAmountText(currentProfit.otherCost) }}
      </el-descriptions-item>
      <el-descriptions-item label="盈亏值(元)">
        <span :class="profitLossClass(currentProfit.profitLossValue)">
          {{ formatAmountText(currentProfit.profitLossValue) }}
        </span>
      </el-descriptions-item>
      <el-descriptions-item label="盈亏百分比">
        <span :class="profitLossClass(currentProfit.profitLossValue)">
          {{ formatPercentText(currentProfit.profitLossRate) }}
        </span>
      </el-descriptions-item>
    </el-descriptions>
  </ContentWrap>

  <ContentWrap v-else>
    <el-empty description="请选择项目后查看盈亏详情" />
  </ContentWrap>

  <Dialog v-model="dialogVisible" title="编辑盈亏参数" width="520">
    <el-form ref="formRef" v-loading="dialogLoading" :model="formData" label-width="140px">
      <el-form-item label="最终结算金额(元)" prop="finalSettlementAmount">
        <el-input-number
          v-model="formData.finalSettlementAmount"
          :min="0"
          :precision="2"
          :step="1000"
          class="!w-1/1"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="科创产值比例(%)" prop="innovationOutputRate">
        <el-input-number
          v-model="innovationOutputRatePercent"
          :min="0"
          :max="100"
          :precision="2"
          :step="0.01"
          class="!w-1/1"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="其他成本(元)" prop="otherCost">
        <el-input-number
          v-model="formData.otherCost"
          :min="0"
          :precision="2"
          :step="1000"
          class="!w-1/1"
          controls-position="right"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="dialogLoading" type="primary" @click="submitProfitForm">保存</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as ProfitApi from '@/api/tjt/profit'
import * as ProjectApi from '@/api/tjt/project'
import {
  CONTRACT_SIGN_OPTIONS,
  DEFAULT_INNOVATION_OUTPUT_RATE,
  formatAmountText,
  formatPercentText,
  fromPercentValue,
  toPercentValue
} from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtProfit' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(false)
const total = ref(0)
const list = ref<ProfitApi.ProjectProfitVO[]>([])
const currentProfit = ref<ProfitApi.ProjectProfitVO>()
const queryFormRef = ref()
const profitTableRef = ref()

const dialogVisible = ref(false)
const dialogLoading = ref(false)
const formRef = ref()
const formData = ref<ProjectApi.ProjectVO>({
  projectName: '',
  contractSignedFlag: true,
  innovationOutputRate: DEFAULT_INNOVATION_OUTPUT_RATE,
  otherCost: 0,
  rolePersons: []
})

const innovationOutputRatePercent = computed({
  get: () => toPercentValue(formData.value.innovationOutputRate),
  set: (value) => {
    formData.value.innovationOutputRate = fromPercentValue(value)
  }
})

const normalizeProjectFormData = (data: ProjectApi.ProjectVO): ProjectApi.ProjectVO => ({
  ...data,
  innovationOutputRate: data.innovationOutputRate ?? DEFAULT_INNOVATION_OUTPUT_RATE,
  otherCost: data.otherCost ?? 0,
  rolePersons: data.rolePersons || []
})

const queryParams = reactive<ProfitApi.ProjectProfitPageReqVO>({
  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 getList = async () => {
  loading.value = true
  try {
    const data = await ProfitApi.getProjectProfitPage(queryParams)
    list.value = data.list
    total.value = data.total
    if (!list.value.length) {
      currentProfit.value = undefined
      return
    }
    const targetProjectId = currentProfit.value?.projectId || list.value[0].projectId
    const targetProfit = list.value.find((item) => item.projectId === targetProjectId) || list.value[0]
    await nextTick()
    profitTableRef.value?.setCurrentRow(targetProfit)
  } finally {
    loading.value = false
  }
}

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

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

const handleCurrentProfitChange = async (row?: ProfitApi.ProjectProfitVO) => {
  if (!row?.projectId) {
    currentProfit.value = undefined
    return
  }
  currentProfit.value = await ProfitApi.getProjectProfit(row.projectId)
}

const refreshCurrentProfit = async () => {
  if (!currentProfit.value?.projectId) {
    return
  }
  currentProfit.value = await ProfitApi.getProjectProfit(currentProfit.value.projectId)
  await getList()
}

const openProfitEditDialog = async () => {
  if (!currentProfit.value?.projectId) {
    return
  }
  dialogVisible.value = true
  dialogLoading.value = true
  try {
    formData.value = normalizeProjectFormData(await ProjectApi.getProject(currentProfit.value.projectId))
  } finally {
    dialogLoading.value = false
  }
}

const buildProjectSavePayload = (): ProjectApi.ProjectSaveVO => ({
  id: formData.value.id,
  projectName: formData.value.projectName,
  contractSignedFlag: formData.value.contractSignedFlag,
  contractAmount: formData.value.contractAmount,
  totalConstructionArea: formData.value.totalConstructionArea,
  constructionUnitName: formData.value.constructionUnitName,
  contactName: formData.value.contactName,
  contactPhone: formData.value.contactPhone,
  contractSigningDate: formData.value.contractSigningDate,
  projectType: formData.value.projectType,
  projectCategory: formData.value.projectCategory,
  projectStartYear: formData.value.projectStartYear,
  projectStatus: formData.value.projectStatus,
  pauseReason: formData.value.pauseReason,
  terminateReason: formData.value.terminateReason,
  finalSettlementAmount: formData.value.finalSettlementAmount,
  innovationOutputRate: formData.value.innovationOutputRate,
  otherCost: formData.value.otherCost,
  rolePersons: formData.value.rolePersons || []
})

const submitProfitForm = async () => {
  dialogLoading.value = true
  try {
    await ProjectApi.updateProject(buildProjectSavePayload())
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    await refreshCurrentProfit()
  } finally {
    dialogLoading.value = false
  }
}

const profitLossClass = (value?: number) => {
  if ((value || 0) > 0) {
    return 'text-[var(--el-color-success)] font-600'
  }
  if ((value || 0) < 0) {
    return 'text-[var(--el-color-danger)] font-600'
  }
  return 'text-[var(--el-text-color-primary)]'
}

onMounted(() => {
  getList()
})

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