<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1080">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="工程名称" prop="projectName">
            <el-input v-model="formData.projectName" maxlength="200" placeholder="请输入工程名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否签订合同" prop="contractSignedFlag">
            <el-switch
              v-model="formData.contractSignedFlag"
              active-text="已签订"
              inactive-text="未签订"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="合同金额(元)" prop="contractAmount">
            <el-input-number
              v-model="formData.contractAmount"
              :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="totalConstructionArea">
            <el-input-number
              v-model="formData.totalConstructionArea"
              :min="0"
              :precision="2"
              :step="100"
              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="建设单位" prop="constructionUnitName">
            <el-input
              v-model="formData.constructionUnitName"
              maxlength="200"
              placeholder="请输入建设单位"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工程类型" prop="projectType">
            <el-select
              v-model="formData.projectType"
              class="!w-1/1"
              clearable
              placeholder="请选择工程类型"
            >
              <el-option
                v-for="item in PROJECT_TYPE_OPTIONS"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="formData.contactName" maxlength="64" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contactPhone">
            <el-input v-model="formData.contactPhone" maxlength="32" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="合同签订日期" prop="contractSigningDate">
            <el-date-picker
              v-model="formData.contractSigningDate"
              class="!w-1/1"
              placeholder="请选择合同签订日期"
              type="date"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目开始年度" prop="projectStartYear">
            <el-date-picker
              v-model="projectStartYearValue"
              class="!w-1/1"
              placeholder="请选择项目开始年度"
              type="year"
              value-format="YYYY"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="项目经理" prop="projectManagerName">
            <el-input
              v-model="formData.projectManagerName"
              maxlength="64"
              placeholder="请输入项目经理"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工程负责人" prop="engineeringPrincipalName">
            <el-input
              v-model="formData.engineeringPrincipalName"
              maxlength="64"
              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 ProjectApi from '@/api/tjt/project'
import { PROJECT_TYPE_OPTIONS } from '@/views/tjt/shared/planning'

defineOptions({ name: 'TjtProjectForm' })

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

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()

const createFormData = (): ProjectApi.ProjectVO => ({
  projectName: '',
  contractSignedFlag: true,
  contractAmount: undefined,
  totalConstructionArea: undefined,
  constructionUnitName: '',
  contactName: '',
  contactPhone: '',
  contractSigningDate: undefined,
  projectManagerName: '',
  engineeringPrincipalName: '',
  projectType: '',
  projectStartYear: new Date().getFullYear()
})

const formData = ref<ProjectApi.ProjectVO>(createFormData())

const projectStartYearValue = computed({
  get: () => (formData.value.projectStartYear ? String(formData.value.projectStartYear) : undefined),
  set: (value?: string) => {
    formData.value.projectStartYear = value ? Number(value) : undefined
  }
})

const formRules = reactive<FormRules>({
  projectName: [{ required: true, message: '工程名称不能为空', trigger: 'blur' }],
  contractAmount: [{ required: true, message: '合同金额不能为空', trigger: 'blur' }],
  totalConstructionArea: [{ required: true, message: '工程总面积不能为空', trigger: 'blur' }],
  projectStartYear: [{ required: true, message: '项目开始年度不能为空', trigger: 'change' }]
})

const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (!id) {
    return
  }
  formLoading.value = true
  try {
    formData.value = await ProjectApi.getProject(id)
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])

const buildSavePayload = (): 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,
  projectManagerName: formData.value.projectManagerName,
  engineeringPrincipalName: formData.value.engineeringPrincipalName,
  projectType: formData.value.projectType,
  projectStartYear: formData.value.projectStartYear,
  finalSettlementAmount: formData.value.finalSettlementAmount,
  expectedKValue: formData.value.expectedKValue
})

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 ProjectApi.createProject(payload)
      message.success(t('common.createSuccess'))
    } else {
      await ProjectApi.updateProject(payload)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = createFormData()
  formRef.value?.resetFields()
}
</script>
