<template>
  <div class="resume-box mb-3">
    <div class="resume-header">
      <div class="resume-title">{{ $t('resume.basicInfo') }}</div>
      <v-btn v-if="!isEdit" variant="text" color="primary" prepend-icon="mdi-square-edit-outline" @click="isEdit = true">{{ $t('common.edit') }}</v-btn>
    </div>
    <div class="d-flex align-center">
      <!-- 头像 -->
      <div class="avatarsBox" @mouseover="showIcon = true" @mouseleave="showIcon = false">
        <v-badge 
          bordered 
          offset-x="-25" 
          offset-y="33" 
          :color="baseInfo?.sex ? (baseInfo?.sex === '1' ? '#1867c0' : 'error') : 'error'" 
          :icon="baseInfo?.sex ? (baseInfo?.sex === '1' ? 'mdi-gender-male' : 'mdi-gender-female') : 'mdi-gender-female'">
          <v-avatar size=80 :image="getUserAvatar(baseInfo?.avatar, baseInfo?.sex)">
          </v-avatar>
          <div v-show="showIcon" @click="openFileInput" v-bind="$attrs" class="mdi mdi-camera-outline">
            <input
              type="file"
              ref="fileInput"
              accept="image/png, image/jpg, image/jpeg"
              style="display: none;"
              @change="handleUploadFile"
            />
          </div>
        </v-badge>
      </div>
      <!-- 基础信息 -->
      <div style="flex: 1;" class="mr-8 mt-5">
        <!-- 编辑 -->
        <div v-if="isEdit">
          <CtForm ref="CtFormRef" :items="items" style="width: 100%;">
            <template v-slot:phone>
              <v-btn variant="text" class="ml-2" color="primary">{{ $t('common.change') }}</v-btn>
            </template>
          </CtForm>
          <div class="text-end">
            <v-btn class="half-button mr-3" variant="tonal" @click="isEdit = false">{{ $t('common.cancel') }}</v-btn>
            <v-btn color="primary" class="half-button" @click="handleSave">{{ $t('common.save') }}</v-btn>
          </div>
        </div>
        <!-- 展示 -->
        <div v-else>
          <span style="font-size: 20px; font-weight: 600;color: var(--color-666);">{{ baseInfo?.name }}</span>
          <div class="mt-3 d-flex">
            <div class="listBox" :style="{ height: isExpand ? 'auto' : '68px' }">
              <div>
                <span class="mdi mdi-map-marker-outline"></span>
                <span>{{ baseInfo?.areaName || $t('common.currentlyUnavailable') }}</span>
              </div>
              <div>
                <span class="mdi mdi-phone-outline"></span>
                <span>{{ baseInfo?.phone || $t('common.currentlyUnavailable') }}</span>
              </div>
              <div>
                <span class="mdi mdi-email-outline"></span>
                <span>{{ baseInfo?.email || $t('common.currentlyUnavailable') }}</span>
              </div>
              <div>
                <span class="mdi mdi-calendar-blank-outline"></span>
                <span>{{ baseInfo?.expTypeText || $t('common.currentlyUnavailable') }}</span>
              </div>
              <div>
                <span class="mdi mdi-school-outline"></span>
                <span>{{ baseInfo?.eduTypeText || $t('common.currentlyUnavailable') }}</span>
              </div>
              <!-- <div>
                <span class="mdi mdi-briefcase-outline"></span>
                <span>{{ baseInfo?.jobTypeText || $t('common.currentlyUnavailable') }}</span>
              </div> -->
              <div>
                <span class="mdi mdi-tag-outline"></span>
                <span>{{ baseInfo?.jobStatusText || $t('common.currentlyUnavailable') }}</span>
              </div>
              <div>
                <span class="mdi mdi-cake-variant-outline"></span>
                <span>{{ baseInfo?.birthdayText || $t('common.currentlyUnavailable') }}</span>
              </div>
              <div>
                <span class="mdi mdi-account-heart"></span>
                <span>{{ baseInfo?.maritalText || $t('common.currentlyUnavailable') }}</span>
              </div>
              <div>
                <span>{{ $t('resume.firstWorkTime') }}：</span>
                <span>{{ baseInfo?.firstWorkTimeText || $t('common.currentlyUnavailable') }}</span>
              </div>
            </div>
            <div class="ml-3">
              <v-btn variant="text" color="primary" v-if="isExpand" @click="isExpand = false">{{ $t('resume.retract') }}</v-btn>
              <v-btn variant="text" color="primary" v-else @click="isExpand = true">{{ $t('resume.expand') }}</v-btn>
            </div>
          </div>
          <div class="mt-4">
            <span style="font-size: 15px;">个人画像：</span>
            <v-chip size="small" label v-for="(k, i) in welfareList.slice(0, 8)" :key="i" class="mr-2" color="primary">{{ k }}</v-chip>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <Loading :visible="overlay"></Loading>
  <!-- 图片裁剪 -->
  <ImgCropper :visible="isShowCopper" :image="selectPic" :cropBoxResizable="true" @submit="handleHideCopper" :aspectRatio="1 / 1" @close="isShowCopper = false, selectPic = ''"></ImgCropper>
</template>

<script setup>
import CtForm from '@/components/CtForm'
import Snackbar from '@/plugins/snackbar'
import { getDict } from '@/hooks/web/useDictionaries'
import { cityToProvince } from '@/utils/areaDeal'
import { getTimeStamp, timesTampChange } from '@/utils/date'
import { updatePersonAvatar, saveResumeBasicInfo } from '@/api/recruit/personal/resume'
import { useUserStore } from '@/store/user'
import { uploadFile } from '@/api/common'
import { getUserAvatar } from '@/utils/avatar'
import { useI18n } from '@/hooks/web/useI18n'
import { ref } from 'vue';
defineOptions({name: 'resume-components-basicInfo'})

const { t } = useI18n()
const userStore = useUserStore()
const CtFormRef = ref()
const isEdit = ref(false)
const showIcon = ref(false)
const isExpand = ref(false)
const overlay = ref(false) // 加载中
const welfareList = ref(['响应', '改变', '诚信', '进取精神', '信任', '卓越'])
let baseInfo = ref({})
const getBasicInfo = () => { // 获取基础信息
  const key = localStorage.getItem('baseInfo')
  if (!key || !Object.keys(key).length) return
  baseInfo.value = JSON.parse(key) // 人才信息
}
getBasicInfo()

// 选择文件
const fileInput = ref()
const clicked = ref(false)
const openFileInput = () => {
  if (clicked.value) return
  clicked.value = true
  fileInput.value.click()
  clicked.value = false
}

// 上传头像
const selectPic = ref('')
const isShowCopper = ref(false)
const handleUploadFile = async (e) => {
  const file = e.target.files[0]
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    selectPic.value = String(reader.result)
    isShowCopper.value = true
  }
}

// 图片裁剪
const handleHideCopper = (data) => {
  isShowCopper.value = false
  if (data) {
    const { file } = data
    if (!file) return
    const formData = new FormData()
    formData.append('file', file)
    overlay.value = true
    uploadFile(formData).then(async ({data}) => {
      if (!data) return
      await updatePersonAvatar(data)
      setTimeout(async () => {
        await userStore.getUserBaseInfos(baseInfo.value.userId)
        getBasicInfo()
        overlay.value = false
        Snackbar.success(t('common.uploadSucMsg'))
      }, 1000)
    })
  }
}

const items = ref({
  options: [
    {
      type: 'text',
      key: 'name',
      value: null,
      default: null,
      label: '中文名 *',
      col: 6,
      outlined: true,
      rules: [v => !!v || '请输入您的中文名']
    },
    {
      type: 'ifRadio',
      key: 'sex',
      value: '0', // '1' ? '男' : '女'
      default: 0,
      label: '性别',
      col: 6,
      width: 70,
      dictTypeName: 'system_user_sex',
      items: [],
    },
    {
      type: 'datePicker',
      key: 'birthday',
      // dateType: 'date', // 时间类型 year month date time
      value: null,
      label: '出生日期 *',
      col: 6,
      outlined: true,
      rules: [v => !!v || '请选择出生日期']
      // options: {},
    },
    {
      type: 'phoneNumber',
      key: 'phone',
      value: null,
      default: null,
      label: '电话号码',
      col: 6,
      outlined: true,
      rules: [v => !!v || '请填写手机号码']
      // disabled: true,
      // slotName: 'phone',
    },
    // {
    //   slotName: 'areaType',
    //   key: 'areaId',
    //   value: null,
    //   label: '所在城市 *',
    //   nameKey: 'areaName', // 展示出来id对应的内容
    //   col: 6,
    //   flexStyle: 'mr-3',
    //   rules: [v => !!v || '请选择所在城市']
    // },
    {
      type: 'text',
      key: 'email',
      value: null,
      default: null,
      label: '常用邮箱 *',
      col: 6,
      outlined: true,
      rules: [v => !!v || '请输入常用邮箱']
    },
    {
      type: 'autocomplete',
      key: 'expType',
      value: null,
      default: null,
      label: '工作经验 *',
      col: 6,
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_exp_type',
      rules: [v => !!v || '请选择工作经验'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'eduType',
      value: null,
      default: null,
      label: '最高学历 *',
      col: 6,
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_education_type',
      rules: [v => !!v || '请选择最高学历'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'jobType',
      value: null,
      default: null,
      label: '求职类型 *',
      col: 6,
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_job_type',
      rules: [v => !!v || '请选择求职类型'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'jobStatus',
      value: null,
      default: null,
      label: '求职状态 *',
      col: 6,
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_job_status',
      rules: [v => !!v || '请选择求职状态'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'maritalStatus',
      value: null,
      default: null,
      label: '婚姻状况 *',
      col: 6,
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_marital_status',
      rules: [v => !!v || '请选择婚姻状况'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'workAreaProvinceId',
      value: null,
      label: '所在城市：省 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'id',
      returnSelect: true,
      noParam: true,
      col: 6,
      flexStyle: 'mr-3',
      rules: [v => !!v || '请选择所在城市：省'],
      items: [],
      change: null
    },
    {
      type: 'autocomplete',
      key: 'areaId',
      value: null,
      label: '所在城市：市 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'id',
      col: 6,
      rules: [v => !!v || '请选择所在城市：市'],
      items: [],
      change: null
    },
    {
      type: 'datePicker',
      dateType: 'month',
      key: 'firstWorkTime',
      value: null,
      label: '首次工作时间 *',
      col: 6,
      outlined: true,
      // clearable: true,
      rules: [v => !!v || '请选择首次工作时间']
      // options: {},
    },
  ]
})

// 保存-基础信息
const handleSave = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return
  const obj = {}
  items.value.options.forEach(e => {
    if (e.type === 'datepicker') obj[e.key] = getTimeStamp(e.value)
    else obj[e.key] = e.value
  })
  await saveResumeBasicInfo(obj)
  Snackbar.success(t('common.saveMsg'))
  isEdit.value = false
  // 获取当前登录账户信息
  // if (baseInfo.value.userId) await userStore.getUserBaseInfos(baseInfo.value.userId)
  await userStore.getUserBaseInfos(baseInfo.value.userId || null)
  getBasicInfo()
}

// 获取字典内容
const getDictData = async (dictTypeName) => {
  const item = items.value.options.find(e => e.dictTypeName === dictTypeName)
  if (item) {
    const { data } = await getDict(dictTypeName)
    item.items = data
  }
}
let timeCount = 0
let workAreaId = ''
const deal = async () => {
  if (workAreaId) { // 省份回显
    const province = items.value.options.find(pv => pv.key === 'workAreaProvinceId')
    if (!province?.items.length) { // 字典数据未获取
      setTimeout(() => {
        timeCount++
        if (timeCount < 6) deal()
      }, 2000)
      return
    }
    if (province) {
      const dealReturnObj = await cityToProvince(workAreaId, {}, province.items || [])
      const city = items.value.options.find(pv => pv.key === 'areaId')
      if (city) city.items = dealReturnObj.cityList || []
      province.value = dealReturnObj.pid || ''
    }
  }
}
items.value.options.forEach((e, index) => {
  if ((index + 2) % 2 === 0) e.flexStyle = 'mr-3'
  if (e.dictTypeName) getDictData(e.dictTypeName) // 查字典set options
  // formItems回显
  const infoExist = baseInfo.value && Object.keys(baseInfo.value).length
  if (infoExist && baseInfo.value[e.key]) e.value = baseInfo.value[e.key]
  // 日期相关
  if (e.type === 'datepicker') e.value = timesTampChange(e.value, 'Y-M-D')
  // 所在城市回显
  // if (infoExist && e.nameKey) e[e.nameKey] = baseInfo.value[e.nameKey]
  if (infoExist && e.key === 'areaId' && baseInfo.value[e.key]) {
    workAreaId = baseInfo.value[e.key]
    deal()
  }
})

const provinceChange = (value, val, obj) => {
  const item = items.value.options.find(e => e.key === 'areaId')
  if (!item) return
  item.items = obj.children || []
  item.value = null
}
getDict('areaTreeData', null, 'areaTreeData').then(({ data }) => {
  data = data?.length && data || []
  if (!data?.length) return console.error('areaTreeData获取失败！')
  //
  const china = data.find(e => e.id === '1')
  const chinaTreeData = china?.children?.length ? china.children : []
  //
  if (!chinaTreeData?.length) return console.error('chinaTreeData获取失败！')
  const item = items.value.options.find(e => e.key === 'workAreaProvinceId')
  if (item?.items) {
    item.items = chinaTreeData
    item.change = provinceChange
  }
})
</script>

<style lang="scss" scoped>
.jobTypeCardBox {
  position: absolute;
  top: -22px;
  left: 0;
}
.avatarsBox {
  height: 80px;
  width: 80px;
  position: relative;
  cursor: pointer;
  margin: 32px;
  margin-right: 40px;
  .img {
    width: 100%;
    height: 100%;
  }
  .mdi {
    font-size: 42px;
    color: #fff;
  }
  div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
  }
}

.listBox {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  width: 100%; /* 设置容器宽度 */
  // height: 68px;
  overflow: hidden;
  color: var(--color-666);
  div {
    margin-right: 50px;
    span {
      height: 32px;
      line-height: 32px;
    }
    .mdi {
      font-size: 22px;
      margin-right: 8px;
      // margin-top: 2px;
    }
  }
  // border: 1px solid red; /* 可视化边界 */
  // .jobItems {
  //   font-size: 14px;
  //   margin-left: 12px;
  //   cursor: pointer;
  //   color: var(--color-666);
  //   font-family: 微软雅黑; 
  // }
}
</style>
