<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="980">
    <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="contractValueQuantity">
            <el-input-number
              v-model="formData.contractValueQuantity"
              :min="0"
              :precision="4"
              :step="1"
              class="!w-1/1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同产值单价" prop="contractValueUnitPrice">
            <el-input-number
              v-model="formData.contractValueUnitPrice"
              :min="0"
              :precision="4"
              :step="1000"
              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="planningAmountPreview" class="readonly-result" 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-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="增值税率(%)" prop="vatRate">
            <el-input-number
              v-model="vatRatePercent"
              :min="0"
              :precision="2"
              :step="0.01"
              class="!w-1/1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="增值税(元)">
            <el-input :model-value="vatAmountPreview" class="readonly-result" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <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-col :span="12">
          <el-form-item label="管理费(元)">
            <el-input :model-value="managementFeePreview" class="readonly-result" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="项目预算产值(元)">
            <el-input
              :model-value="projectBudgetOutputValuePreview"
              class="budget-result"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sortNo">
            <el-input
              v-model="formData.sortNo"
              maxlength="50"
              placeholder="请输入排序，如 A-01"
              class="!w-1/1"
            />
          </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 ownershipTypeOptions = OWNERSHIP_TYPE_OPTIONS

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,
  sortNo: '',
  ownershipType: ownershipTypeOptions[0].value,
  calculationMethod: '',
  planningContent: '',
  planningAmount,
  contractValueQuantity: 1,
  contractValueUnitPrice: planningAmount,
  managementFeeRate: undefined,
  implementationTeam: '',
  vatRate: 0.06,
  vatAmount: undefined,
  projectBudgetOutputValue: undefined,
  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 vatRatePercent = computed({
  get: () => {
    if (formData.value.vatRate === undefined || formData.value.vatRate === null) {
      return undefined
    }
    return Number((Number(formData.value.vatRate) * 100).toFixed(2))
  },
  set: (value?: number) => {
    formData.value.vatRate =
      value === undefined || value === null ? undefined : Number((value / 100).toFixed(4))
  }
})

const planningAmountPreviewValue = computed(() => {
  const quantity = Number(formData.value.contractValueQuantity || 0)
  const unitPrice = Number(formData.value.contractValueUnitPrice || 0)
  return Number((quantity * unitPrice).toFixed(2))
})

const planningAmountPreview = computed(() => planningAmountPreviewValue.value.toFixed(2))

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

const vatAmountPreview = computed(() => {
  const vatRate = Number(formData.value.vatRate || 0)
  return (planningAmountPreviewValue.value * vatRate).toFixed(2)
})

const projectBudgetOutputValuePreview = computed(() =>
  (
    planningAmountPreviewValue.value -
    Number(managementFeePreview.value || 0) -
    Number(vatAmountPreview.value || 0)
  ).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' }],
  contractValueQuantity: [{ required: true, message: '合同产值数量不能为空', trigger: 'blur' }],
  contractValueUnitPrice: [{ required: true, message: '合同产值单价不能为空', trigger: 'blur' }],
  managementFeeRate: [{ required: true, message: '管理费率不能为空', trigger: 'blur' }],
  vatRate: [{ required: true, message: '增值税率不能为空', trigger: 'blur' }]
})

const buildSavePayload = (): PlanningApi.ProjectPlanningSaveVO => ({
  id: formData.value.id,
  projectId: formData.value.projectId,
  sortNo: formData.value.sortNo?.trim() || undefined,
  ownershipType: formData.value.ownershipType,
  calculationMethod: formData.value.calculationMethod,
  planningContent: formData.value.planningContent,
  contractValueQuantity: formData.value.contractValueQuantity,
  contractValueUnitPrice: formData.value.contractValueUnitPrice,
  managementFeeRate: formData.value.managementFeeRate,
  vatRate: formData.value.vatRate,
  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),
      contractValueQuantity: planning.contractValueQuantity ?? 1,
      contractValueUnitPrice:
        planning.contractValueUnitPrice ?? planning.planningAmount ?? options.defaultPlanningAmount,
      vatRate: planning.vatRate ?? 0.06
    }
  } 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>

<style scoped>
.readonly-result :deep(.el-input__wrapper.is-disabled) {
  background-color: var(--el-fill-color-light);
}

.budget-result :deep(.el-input__wrapper.is-disabled) {
  background-color: var(--el-color-primary-light-9);
  box-shadow: 0 0 0 1px var(--el-color-primary-light-5) inset;
}

.budget-result :deep(.el-input__inner) {
  color: var(--el-color-primary);
  font-weight: 700;
}
</style>
