<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="920">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="128px"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="归属类型" prop="ownershipType">
            <el-select
              v-model="formData.ownershipType"
              :disabled="formType === 'update'"
              class="!w-1/1"
              placeholder="请选择归属类型"
            >
              <el-option
                v-for="item in ownershipTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规划内容" prop="planningContent">
            <el-input
              v-model="formData.planningContent"
              maxlength="255"
              placeholder="请输入规划内容"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="规划金额(元)" prop="planningAmount">
            <el-input-number
              v-model="formData.planningAmount"
              :min="0"
              :precision="2"
              :step="1000"
              class="!w-1/1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理费率(%)" prop="managementFeeRate">
            <el-input-number
              v-model="managementFeeRatePercent"
              :min="0"
              :precision="2"
              :step="0.01"
              class="!w-1/1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="管理费(元)">
            <el-input :model-value="managementFeePreview" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实施团队" prop="implementationTeam">
            <el-input
              v-model="formData.implementationTeam"
              maxlength="100"
              placeholder="请输入实施团队"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">保存</el-button>
      <el-button @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import type { FormRules } from 'element-plus'
import * as PlanningApi from '@/api/tjt/planning'
import { OWNERSHIP_TYPE_OPTIONS } from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtPlanningForm' })

const OWNERSHIP_TYPE_LABELS = ['专业所', '综合所', '专业分包']
const ownershipTypeOptions = OWNERSHIP_TYPE_OPTIONS.map((item, index) => ({
  label: OWNERSHIP_TYPE_LABELS[index] || item.label,
  value: item.value
}))

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

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')
const formRef = ref()

const createFormData = (
  projectId?: number,
  planningAmount?: number
): PlanningApi.ProjectPlanningVO => ({
  projectId: projectId || 0,
  ownershipType: ownershipTypeOptions[0].value,
  calculationMethod: '',
  planningContent: '',
  planningAmount,
  managementFeeRate: undefined,
  implementationTeam: '',
  planningStartYear: undefined,
  planningArea: undefined,
  designStage: undefined,
  currentDesignStageRatio: undefined,
  reviewOutsourceFlag: false,
  reviewOutsourceRatio: undefined,
  totalDistributionAmount: 1,
  progressRemark: '',
  allocatedAmount: undefined,
  pendingAmount: undefined,
  buildingOrUnitCount: undefined,
  drawingSetFactor: 1,
  scaleFactor: 1,
  modificationFactor: 1,
  complexityFactor: 1,
  internalGuidanceUnitPrice: undefined,
  virtualCalculationMethod: undefined,
  workingDayCount: undefined,
  workingDayUnitPrice: undefined,
  guidanceUnitPrice: undefined,
  guidanceTotalPrice: undefined,
  calculationRatio: undefined,
  contractUnitPrice: undefined,
  totalAdjustmentFactor: undefined,
  assessmentArea: undefined,
  virtualOutputValue: undefined,
  assessmentOutputValue: undefined
})

const formData = ref<PlanningApi.ProjectPlanningVO>(createFormData())

const managementFeeRatePercent = computed({
  get: () => {
    if (formData.value.managementFeeRate === undefined || formData.value.managementFeeRate === null) {
      return undefined
    }
    return Number((Number(formData.value.managementFeeRate) * 100).toFixed(2))
  },
  set: (value?: number) => {
    formData.value.managementFeeRate =
      value === undefined || value === null ? undefined : Number((value / 100).toFixed(4))
  }
})

const managementFeePreview = computed(() => {
  const planningAmount = Number(formData.value.planningAmount || 0)
  const managementFeeRate = Number(formData.value.managementFeeRate || 0)
  return (planningAmount * managementFeeRate).toFixed(2)
})

const normalizeOwnershipType = (value?: string) =>
  ownershipTypeOptions.find((item) => item.value === value)?.value || ownershipTypeOptions[0].value

const formRules = reactive<FormRules>({
  projectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
  ownershipType: [{ required: true, message: '归属类型不能为空', trigger: 'change' }],
  planningContent: [{ required: true, message: '规划内容不能为空', trigger: 'blur' }],
  planningAmount: [{ required: true, message: '规划金额不能为空', trigger: 'blur' }],
  managementFeeRate: [{ required: true, message: '管理费率不能为空', trigger: 'blur' }]
})

const buildSavePayload = (): PlanningApi.ProjectPlanningSaveVO => ({
  id: formData.value.id,
  projectId: formData.value.projectId,
  ownershipType: formData.value.ownershipType,
  calculationMethod: formData.value.calculationMethod,
  planningContent: formData.value.planningContent,
  planningAmount: formData.value.planningAmount,
  managementFeeRate: formData.value.managementFeeRate,
  implementationTeam: formData.value.implementationTeam,
  planningStartYear: formData.value.planningStartYear,
  planningArea: formData.value.planningArea,
  designStage: formData.value.designStage,
  currentDesignStageRatio: formData.value.currentDesignStageRatio,
  reviewOutsourceFlag: formData.value.reviewOutsourceFlag,
  reviewOutsourceRatio: formData.value.reviewOutsourceRatio,
  totalDistributionAmount: formData.value.totalDistributionAmount,
  progressRemark: formData.value.progressRemark,
  buildingOrUnitCount: formData.value.buildingOrUnitCount,
  drawingSetFactor: formData.value.drawingSetFactor,
  scaleFactor: formData.value.scaleFactor,
  modificationFactor: formData.value.modificationFactor,
  complexityFactor: formData.value.complexityFactor,
  internalGuidanceUnitPrice: formData.value.internalGuidanceUnitPrice,
  virtualCalculationMethod: formData.value.virtualCalculationMethod,
  workingDayCount: formData.value.workingDayCount,
  workingDayUnitPrice: formData.value.workingDayUnitPrice,
  guidanceUnitPrice: formData.value.guidanceUnitPrice,
  guidanceTotalPrice: formData.value.guidanceTotalPrice,
  calculationRatio: formData.value.calculationRatio
})

const open = async (
  type: 'create' | 'update',
  options: {
    id?: number
    projectId?: number
    defaultPlanningAmount?: number
  } = {}
) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增合约规划' : '编辑合约规划'
  formType.value = type
  resetForm(options.projectId, options.defaultPlanningAmount)
  if (!options.id) {
    return
  }
  formLoading.value = true
  try {
    const planning = await PlanningApi.getProjectPlanning(options.id)
    formData.value = {
      ...createFormData(options.projectId, options.defaultPlanningAmount),
      ...planning,
      ownershipType: normalizeOwnershipType(planning.ownershipType)
    }
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])

const submitForm = async () => {
  if (!formRef.value) {
    return
  }
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  formLoading.value = true
  try {
    const payload = buildSavePayload()
    if (formType.value === 'create') {
      await PlanningApi.createProjectPlanning(payload)
      message.success(t('common.createSuccess'))
    } else {
      await PlanningApi.updateProjectPlanning(payload)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = (projectId?: number, planningAmount?: number) => {
  formData.value = createFormData(projectId, planningAmount)
  formRef.value?.resetFields()
}
</script>
