<template>
  <div class="talent-unit-form-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isView ? '查看' : (formData.id ? '编辑' : '新增') }}工作单位</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
        :disabled="isView"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构名称" prop="orgName">
              <el-input v-model="formData.orgName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织类型" prop="orgType">
              <el-select v-model="formData.orgType" placeholder="请选择组织类型" style="width: 100%">
                <el-option label="高校" value="SCHOOL" />
                <el-option label="企业" value="ENTERPRISE" />
                <el-option label="科研院所" value="RESEARCH_INSTITUTE" />
                <el-option label="政府机关" value="GOVERNMENT" />
                <el-option label="其他" value="OTHER" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构代码" prop="orgCode">
              <el-input v-model="formData.orgCode" placeholder="请输入统一社会信用代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法定代表人" prop="legalRepresentative">
              <el-input v-model="formData.legalRepresentative" placeholder="请输入法定代表人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="成立日期" prop="establishmentDate">
              <el-date-picker
                v-model="formData.establishmentDate"
                type="date"
                placeholder="请选择成立日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工人数" prop="employeeCount">
              <el-input-number v-model="formData.employeeCount" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 联系信息 -->
        <el-divider content-position="left">联系信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="官方网址" prop="website">
              <el-input v-model="formData.website" placeholder="请输入官方网址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="所属省份" prop="province">
              <el-input v-model="formData.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属城市" prop="city">
              <el-input v-model="formData.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属区域" prop="district">
              <el-input v-model="formData.district" placeholder="请输入区域" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入详细地址" />
        </el-form-item>

        <!-- 企业信息 -->
        <template v-if="formData.orgType === 'ENTERPRISE'">
          <el-divider content-position="left">企业信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="注册资本" prop="registeredCapital">
                <el-input v-model="formData.registeredCapital" placeholder="请输入注册资本" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属行业" prop="industry">
                <el-input v-model="formData.industry" placeholder="请输入所属行业" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="是否高新技术企业" prop="isHighTech">
            <el-radio-group v-model="formData.isHighTech">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="经营范围" prop="businessScope">
            <el-input
              v-model="formData.businessScope"
              type="textarea"
              :rows="3"
              placeholder="请输入经营范围"
            />
          </el-form-item>
        </template>

        <!-- 高校信息 -->
        <template v-if="formData.orgType === 'SCHOOL'">
          <el-divider content-position="left">高校信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="高校类型" prop="schoolType">
                <el-select v-model="formData.schoolType" placeholder="请选择高校类型" style="width: 100%">
                  <el-option label="985" value="985" />
                  <el-option label="211" value="211" />
                  <el-option label="双一流" value="双一流" />
                  <el-option label="普通本科" value="普通本科" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="办学层次" prop="schoolLevel">
                <el-select v-model="formData.schoolLevel" placeholder="请选择办学层次" style="width: 100%">
                  <el-option label="本科" value="本科" />
                  <el-option label="专科" value="专科" />
                  <el-option label="本专科" value="本专科" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <!-- 其他信息 -->
        <el-divider content-position="left">其他信息</el-divider>

        <el-form-item label="机构简介" prop="introduction">
          <el-input
            v-model="formData.introduction"
            type="textarea"
            :rows="4"
            placeholder="请输入机构简介"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item v-if="!isView">
          <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
          <el-button @click="handleBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

defineOptions({
  name: 'TalentUnitForm'
})
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getOrganizationDetail,
  addOrganization,
  updateOrganization,
  type OrganizationFormData
} from '@/api/organization'

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()
const submitting = ref(false)
const isView = ref(false)

// 表单数据
const formData = reactive<OrganizationFormData>({
  orgName: '',
  orgType: 'ENTERPRISE',
  orgCode: '',
  legalRepresentative: '',
  establishmentDate: '',
  province: '',
  city: '',
  district: '',
  address: '',
  contactPhone: '',
  contactEmail: '',
  website: '',
  employeeCount: undefined,
  introduction: '',
  registeredCapital: '',
  businessScope: '',
  industry: '',
  isHighTech: 0,
  schoolType: '',
  schoolLevel: ''
})

// 表单验证规则
const rules: FormRules = {
  orgName: [
    { required: true, message: '请输入机构名称', trigger: 'blur' }
  ],
  orgType: [
    { required: true, message: '请选择组织类型', trigger: 'change' }
  ],
  contactEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  website: [
    { type: 'url', message: '请输入正确的网址', trigger: 'blur' }
  ]
}

// 加载详情
const loadDetail = async (id: string) => {
  try {
    const { data } = await getOrganizationDetail(id)
    if (data.code === 200) {
      Object.assign(formData, data.data)
    } else {
      ElMessage.error(data.message || '加载数据失败')
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
    console.error(error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const apiFunc = formData.id ? updateOrganization : addOrganization
        const { data } = await apiFunc(formData)
        if (data.code === 200) {
          ElMessage.success(formData.id ? '修改成功' : '新增成功')
          handleBack()
        } else {
          ElMessage.error(data.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败')
        console.error(error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 返回
const handleBack = () => {
  router.push('/admin/talent-unit')
}

onMounted(() => {
  const id = route.params.id as string
  isView.value = route.path.includes('/view/')
  
  if (id) {
    loadDetail(id)
  }
})
</script>

<style scoped>
.talent-unit-form-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: #409eff;
}
</style>
