<template>
  <v-card class="pa-5 card-box d-flex flex-column align-center">
    <CtForm ref="CtFormRef" :items="formItems" style="width: 700px;">
      <template #avatar="{ item }">
        <div style="color: #7a7a7a;">头像</div>
        <div class="avatarsBox" @mouseover="showIcon = true" @mouseleave="showIcon = false">
          <v-avatar class="elevation-5" size=80 :image="getUserAvatar(item.value, 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>
        </div>
        <div style="font-size: 14px; color: var(--color-999);">只支持JPG、JPEG、PNG类型的图片，大小不超过10M</div>
      </template>
    </CtForm>
    <v-btn class="buttons mt-5" color="primary" @click.stop="handleSubmit">{{ $t('common.save') }}</v-btn>
    <v-btn class="mt-3" color="primary" variant="text" to="/recruit/enterprise/staffChangePassword">修改登录密码</v-btn>
  </v-card>

  <Loading :visible="overlay"></Loading>
  <ImgCropper :visible="isShowCopper" :image="selectPic" :cropBoxResizable="true" @submit="handleHideCopper" :aspectRatio="1 / 1" @close="isShowCopper = false"></ImgCropper>
</template>

<script setup>
defineOptions({ name: 'information-setting'})
import { ref } from 'vue'
import { saveUserInfo } from '@/api/enterprise'
import { uploadFile } from '@/api/common'
import { useI18n } from '@/hooks/web/useI18n'
// import { getDict } from '@/hooks/web/useDictionaries'
import { useUserStore } from '@/store/user'
import Snackbar from '@/plugins/snackbar'
import { getUserAvatar } from '@/utils/avatar'
// import { checkEmail } from '@/utils/validate'

const { t } = useI18n()
const userStore = useUserStore()
const showIcon = ref(false)

// 图片裁剪
const overlay = ref(false)
const selectPic = ref('')
const isShowCopper = ref(false)

const CtFormRef = ref()
const formItems = ref({
  options: [
    {
      slotName: 'avatar',
      key: 'avatar',
      value: '',
      flexStyle: 'align-center'
    },
    // {
    //   type: 'ifRadio',
    //   key: 'sex',
    //   value: '2',
    //   label: '性别',
    //   width: 90,
    //   dictTypeName: 'menduner_sex',
    //   items: []
    // },
    {
      type: 'text',
      key: 'name',
      value: '',
      label: '用户名 *',
      rules: [v => !!v || '请输入用户名']
    },
    {
      type: 'phoneNumber',
      key: 'phone',
      value: '',
      label: '手机号码 *',
      rules: [v => !!v || '请输入手机号码']
    },
    {
      type: 'text',
      key: 'email',
      value: '',
      label: '电子邮箱',
      disabled: true,
      // rules: [
      //   value => {
      //     if (value) return true
      //     return '请输入联系邮箱'
      //   },
      //   value => {
      //     if (checkEmail(value)) return true
      //     return '请输入正确的电子邮箱'
      //   }
      // ]
    },
    {
      type: 'text',
      key: 'postName',
      value: '',
      label: '所属岗位'
    }
  ]
})

// 用户基本信息
// let emailChange = false
const baseInfo = ref(JSON.parse(localStorage.getItem('entBaseInfo')) || {})
const query = ref({})
// 获取字典数据以及字段回显
formItems.value.options.forEach(item => {
  // if (item.dictTypeName) {
  //   getDict(item.dictTypeName).then(({ data }) => {
  //     data = data?.length && data || []
  //     item.items = data
  //   })
  // }
  if (Object.keys(baseInfo).length) {
    item.value = baseInfo.value[item.key]
    query.value.id = baseInfo.value.id
  }
  // if (item.key === 'email') {
  //   item.disabled = checkEmail(item.value)
  //   emailChange = !item.disabled
  // }
})
// 监听store变化
userStore.$subscribe((mutation, state) => {
  baseInfo.value = state.baseInfo
})

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

// 上传头像
const handleUploadFile = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  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)
    uploadFile(formData).then(async ({ data }) => {
      if (!data) return
      formItems.value.options.find(e => e.key === 'avatar').value = data
    })
  }
}

// 提交
const handleSubmit = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return
  overlay.value = true
  formItems.value.options.forEach(item => {
    query.value[item.key] = item.value
  })
  await saveUserInfo(query.value)
  // if (query.value?.email && emailChange) await entUpdateEmail({ email: query.value.email })
  setTimeout(async () => {
    await userStore.getEnterpriseInfo()
    Snackbar.success(t('common.submittedSuccessfully'))
    overlay.value = false
  }, 1000)
}

</script>

<style scoped lang="scss">
.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%;
  }
}
</style>
