<template>
  <div class="formBox">
		<el-form
      ref="formRef"
      :model="formQuery"
      label-width="128px"
      v-loading="loading"
      :disabled="readOnly"
    >
      <div class="m-title">
        <div class="mb-10px">基础信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="姓名(中)" prop="name_zh">
              <el-input v-model="formQuery.name_zh" placeholder="请输入中文姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名(英)" prop="name_en">
              <el-input v-model="formQuery.name_en" placeholder="请输入英文姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位/头衔(中)" prop="title_zh">
              <el-input v-model="formQuery.title_zh" placeholder="请输入中文职位/头衔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位/头衔(英)" prop="title_en">
              <el-input v-model="formQuery.title_en" placeholder="请输入英文职位/头衔" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                v-model="formQuery.birthday"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="请选择出生日期"
                :disabledDate="disabledDates"
                @change="birthdayChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="native_place">
              <el-input v-model="formQuery.native_place" placeholder="请输入籍贯" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="formQuery.age" placeholder="请输入年龄" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-input v-model="formQuery.gender" placeholder="请输入性别" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="工作地" prop="residence">
              <el-input v-model="formQuery.residence" placeholder="请输入当前工作地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <div class="m-title my-10px">
        <div class="mb-10px">联系方式</div>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="formQuery.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="固定电话" prop="phone">
              <el-input v-model="formQuery.phone" placeholder="请输入固定电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码1" prop="mobile">
              <el-input v-model="formQuery.mobile[0]" placeholder="请输入手机号码" @change="val => mobileChange(val, 0)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码2" prop="mobile">
              <el-input v-model="formQuery.mobile[1]" placeholder="请输入手机号码" @change="val => mobileChange(val, 1)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码3" prop="mobile">
              <el-input v-model="formQuery.mobile[2]" placeholder="请输入手机号码" @change="val => mobileChange(val, 2)" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <div class="m-title">
        <div class="mb-10px">酒店/公司信息</div>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="酒店/公司名称(中)" prop="hotel_zh">
              <el-input v-model="formQuery.hotel_zh" placeholder="请输入中文酒店/公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="酒店/公司名称(英)" prop="hotel_en">
              <el-input v-model="formQuery.hotel_en" placeholder="请输入英文酒店/公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌名称(中)" prop="brand_zh">
              <el-input v-model="formQuery.brand_zh" placeholder="请输入中文品牌名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌名称(英)" prop="brand_en">
              <el-input v-model="formQuery.brand_en" placeholder="请输入英文品牌名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隶属关系(中)" prop="affiliation_zh">
              <el-input v-model="formQuery.affiliation_zh" placeholder="请输入中文隶属关系" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隶属关系(英)" prop="affiliation_en">
              <el-input v-model="formQuery.affiliation_en" placeholder="请输入英文隶属关系" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="品牌组合" prop="brand_group">
              <el-input v-model="formQuery.brand_group" placeholder="请输入品牌组合" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <div class="m-title my-10px">
        <div>职业轨迹</div>
        <div class="text-right mb-5px">
          <el-button @click="addCareer" plain type="primary" class="cursor-pointer">
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
        </div>
        <el-table :data="careerTrajectory" :stripe="true">
          <el-table-column label="酒店名称" align="center" prop="hotel_zh">
            <template #default="scope">
              <el-input v-model="scope.row.hotel_zh" placeholder="请输入酒店名称" />
            </template>
          </el-table-column>
          <el-table-column label="职位名称" align="center" prop="title_zh">
            <template #default="scope">
              <el-input v-model="scope.row.title_zh" placeholder="请输入职位名称" />
            </template>
          </el-table-column>
          <el-table-column label="任职时间" align="center" prop="date">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.date"
                value-format="YYYY-MM-DD"
                type="date"
                :disabledDate="disabledDates"
                placeholder="任职时间"
                class="!w-100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #default="scope">
              <el-button link type="danger" :icon="Delete" @click="removeCareer(scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="m-title">
        <div class="mb-10px">地址信息</div>
        <el-form-item label="中文地址" prop="address_zh">
          <el-input v-model="formQuery.address_zh" placeholder="请输入中文地址" />
        </el-form-item>
        <el-form-item label="英文地址" prop="address_en">
          <el-input v-model="formQuery.address_en" placeholder="请输入英文地址" />
        </el-form-item>
        <el-form-item label="邮政编码" prop="postal_code_zh">
          <el-input v-model="formQuery.postal_code_zh" placeholder="请输入邮政编码" />
        </el-form-item>
      </div>
      
      <div class="m-title my-10px">
        <div class="mb-10px">信息补充</div>
        <el-form-item label="人才信息" prop="talent_profile">
          <el-input v-model="formQuery.talent_profile" show-word-limit maxlength="500" type="textarea" :rows="2" placeholder="个人简介、背景、职业发展、专业技能、资质认证、教育背景、获奖情况及荣誉等信息" />
        </el-form-item>
      </div>
      
      <template v-if="formType === 'edit'">
        <div class="m-title">
          <div class="mb-10px">系统信息</div>
          <el-form-item label="状态" v-if="itemData.status">
            <el-tag :type="itemData.status === 'active' ? 'success' : 'danger'">
              {{ itemData.status === 'active' ? '已启用' : '已禁用' }}
            </el-tag>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-tag v-if="itemData?.created_at" type="primary" effect="light">{{ itemData?.created_at }}</el-tag>
          </el-form-item>
          <el-form-item label="更新时间">
            <el-tag v-if="itemData?.updated_at" type="primary" effect="light">{{ itemData?.updated_at }}</el-tag>
          </el-form-item>
        </div>
      </template>
    </el-form>
	</div>
</template>

<script setup>
import { talentLabelingApi } from '@/api/menduner/system/talentMap/labeling'
import { talentTagApi } from '@/api/menduner/system/talentMap/tag'
import { getDict } from '@/hooks/web/useDictionaries'
import { cloneDeep } from 'lodash-es'
import { TalentMap } from '@/api/menduner/system/talentMap'
import { Delete, Plus } from '@element-plus/icons-vue'
import { validatePhoneNumber } from '@/utils/formatter'
import { setIndex } from '@/components/Table/src/helper'

const message = useMessage() // 消息弹窗
const props = defineProps({
  itemData: Object,
  formType: String,
  readOnly: { type: Boolean, default: false }
})

const loading = ref(false)
const dialogVisible = ref(false) // 弹窗的是否展示
const defaultQuery = {
  name_zh: undefined,
  name_en: undefined,
  title_zh: undefined,
  title_en: undefined,
  mobile: ['', '', ''],
  phone: undefined,
  email: undefined,
  hotel_zh: undefined,
  hotel_en: undefined,
  brand_zh: undefined,
  brand_en: undefined,
  affiliation_zh: undefined,
  affiliation_en: undefined,
  brand_group: undefined,
  address_zh: undefined,
  address_en: undefined,
  postal_code_zh: undefined,
  postal_code_en: undefined,
  birthday: undefined,
  residence: undefined,
  age: undefined,
  gender: undefined,
  native_place: undefined,
  talent_profile: undefined,
  career_path: []
}
const formQuery = ref(cloneDeep(defaultQuery))
const careerPathItem = { hotel_zh: null, hotel_en: null, title_zh: null, title_en: null, date: null, source: null, image_path: null }
const careerTrajectory = ref([careerPathItem])

// 渲染完成后赋值
onMounted(() => {
  if (props.itemData) {
    setFormData(props.itemData)
  }
})

watch(() => props.itemData, val => {
  if (val) {
    setFormData(val)
  }
}, { deep: true })

const mobileChange = (val, index) => {
  const { cleanedNumber, valid } = validatePhoneNumber(val, true)
  formQuery.value.mobile[index] = cleanedNumber
  val = cleanedNumber
  // if (!valid) message.warning('输入的手机号码格式不正确，请重新输入！')
}

const addCareer = () => {
  careerTrajectory.value = careerTrajectory.value || []
  careerTrajectory.value.push(careerPathItem)
  formQuery.value.career_path = careerTrajectory.value
}
const removeCareer = (index) => {
  if (careerTrajectory.value.length <= 1) return
  careerTrajectory.value.splice(index, 1)
  formQuery.value.career_path = careerTrajectory.value
}

// 未来的日期不可选
const disabledDates = (date) => {
  return date.getTime() > Date.now()
}

// 自动填充年龄
const birthdayChange = (val) => {
  if (!val) return
  const birthDate = new Date(val);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  // 如果当前月份小于出生月份，或者月份相同但日期小于出生日期，则年龄减1
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) age--;
  formQuery.value.age = age;
}

// 保持手机号码数量为三个
function splitStringToArray(str) {
  const MAX_PHONE_NUMBERS = 3;
  const result = Array(MAX_PHONE_NUMBERS).fill('');
  if (!str) return result;
  const parts = String(str).split(',').map(item => item.trim()).slice(0, MAX_PHONE_NUMBERS);
  parts.forEach((part, index) => {
    result[index] = part || '';
  });
  return result;
}

const setFormData = (data) => {
  if (!formQuery.value || !data || 
      !Object.keys(formQuery.value).length || 
      !Object.keys(data).length) {
    return;
  }
  resetFormData()
  Object.entries(formQuery.value).forEach(([key]) => {
    const value = data[key];
    switch (key) {
      case 'mobile':
        formQuery.value[key] = Array.isArray(value) 
          ? splitStringToArray(value.join(',')) 
          : value 
            ? splitStringToArray(value)
            : ['', '', ''];
        break;
      case 'career_path':
        formQuery.value[key] = careerTrajectory.value = value?.length ? cloneDeep(value) : [careerPathItem];
        break;
      default:
        formQuery.value[key] = value ?? null;
    }
  });
}

const resetFormData = (data) => {
  formQuery.value = cloneDeep(defaultQuery)
}
const changeLoading = (bool) => {
  loading.value = bool
}

defineExpose({
	setFormData,
	resetFormData,
	changeLoading,
	formQuery,
  careerTrajectory
})
</script>

<style scoped lang="scss">
.formBox {
  flex: 1;
  max-height: 70vh;
  // padding: 12px;
  overflow: auto;
  // background-color: #f5f7f9;
  .m-title {
    padding: 12px 8px;
    font-size: 13px;
    color: #999;
    background-color: #f5f7f9;
  }
  .trajectoryBox {
    margin: 10px 20px;
    padding-top: 20px;
    padding-bottom: 5px;
    border-radius: 5px;
    background-color: #fff;
  }
}
:deep {
  .el-form-item--default {
    margin-bottom: 5px !important;
  }
}
</style>