<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue/es';
import { FileType } from 'ant-design-vue/es/upload/interface';
import { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';
import { onMounted, reactive, ref, toRaw } from 'vue';
import { updateUserProfile, uploadAvatar } from '@/api/profile';
import { regExpEmail, regExpMobile, regExpNick } from '@/utils/regular-utils';
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useI18n from '@/hooks/useI18n';
const { t } = useI18n();
const uerStore = useUserStore();
const { getDict } = useDictStore();

/**用户性别字典 */
let sysUserSex = ref<DictType[]>([
  { label: '未知', value: '0', tagType: '', tagClass: '' },
  { label: '男', value: '1', tagType: '', tagClass: '' },
  { label: '女', value: '2', tagType: '', tagClass: '' },
]);

/**表单数据状态 */
let stateForm = reactive({
  /**表单属性 */
  form: {
    nickName: '',
    email: '',
    phonenumber: '',
    sex: '0',
  },
  /**表单提交点击状态 */
  formClick: false,
});

/**表单数据状态初始化 */
function fnInitstateForm() {
  stateForm.form = Object.assign(stateForm.form, uerStore.getBaseInfo);
  stateForm.formClick = false;
}

/**表单验证通过 */
function fnFinish() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.account.settings.profileTip'),
    onOk() {
      stateForm.formClick = true;
      // 发送请求
      const hide = message.loading(t('common.loading'), 0);
      const form = toRaw(stateForm.form);
      updateUserProfile(form).then(res => {
        hide();
        stateForm.formClick = false;
        if (res.code === RESULT_CODE_SUCCESS) {
          Modal.success({
            title: t('common.tipTitle'),
            content: t('views.account.settings.profileOk'),
            okText: t('views.account.settings.know'),
            onOk() {
              uerStore.setBaseInfo(form);
            },
          });
        } else {
          message.error(`${res.msg}`, 3);
        }
      });
    },
  });
}

/**上传状态 */
let upState = ref<boolean>(false);

/**上传前检查或转换压缩 */
function fnBeforeUpload(file: FileType) {
  if (upState.value) return false;
  const isJpgOrPng = ['image/jpeg', 'image/png'].includes(file.type);
  if (!isJpgOrPng) {
    message.error(
      t('views.account.settings.uploadFormat', { format: 'jpg、png' }),
      3
    );
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error(t('views.account.settings.uploadSize', { size: '2' }), 3);
  }
  return isJpgOrPng && isLt2M;
}

/**上传变更 */
function fnUpload(up: UploadRequestOption) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.account.settings.uploadTip'),
    onOk() {
      // 发送请求
      const hide = message.loading(t('common.loading'), 0);
      upState.value = true;
      let formData = new FormData();
      formData.append('file', up.file);
      uploadAvatar(formData).then(res => {
        upState.value = false;
        hide();
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success(t('views.account.settings.uploadOk'), 3);
          uerStore.setAvatar(res.data);
        } else {
          message.error(res.msg, 3);
        }
      });
    },
  });
}

onMounted(() => {
  // 初始字典数据
  getDict('sys_user_sex').then(res => {
    if (res.length > 0) {
      sysUserSex.value = res;
    }
  });
  // 初始表单值
  fnInitstateForm();
});
</script>

<template>
  <a-form
    :model="stateForm.form"
    name="stateForm"
    layout="vertical"
    :wrapper-col="{ span: 18 }"
    @finish="fnFinish"
  >
    <a-row :gutter="16">
      <a-col :lg="12" :md="12" :xs="24" style="margin-bottom: 30px">
        <a-form-item
          :label="t('views.account.settings.nick')"
          name="nickName"
          :rules="[
            {
              required: true,
              pattern: regExpNick,
              message: t('views.account.settings.nickTip'),
            },
          ]"
        >
          <a-input
            v-model:value="stateForm.form.nickName"
            allow-clear
            :maxlength="26"
            :placeholder="t('views.account.settings.nickPleace')"
          ></a-input>
        </a-form-item>

        <a-form-item
          :label="t('views.account.settings.phonenumber')"
          name="phonenumber"
          :rules="[
            {
              required: false,
              pattern: regExpMobile,
              message: t('views.account.settings.phonenumberPleace'),
            },
          ]"
        >
          <IntlTelInput
            v-model:value="stateForm.form.phonenumber"
            allow-clear
            :maxlength="20"
            :placeholder="t('views.account.settings.phonenumberPleace')"
          ></IntlTelInput>
        </a-form-item>

        <a-form-item
          :label="t('views.account.settings.email')"
          name="email"
          :rules="[
            {
              required: false,
              pattern: regExpEmail,
              message: t('views.account.settings.emailPleace'),
            },
          ]"
        >
          <a-input
            v-model:value="stateForm.form.email"
            allow-clear
            :maxlength="40"
            :placeholder="t('views.account.settings.emailPleace')"
          ></a-input>
        </a-form-item>

        <a-form-item
          :label="t('views.account.settings.sex')"
          name="sex"
          :rules="[
            {
              required: true,
              message: t('views.account.settings.sexPleace'),
            },
          ]"
        >
          <a-select v-model:value="stateForm.form.sex" :options="sysUserSex">
          </a-select>
        </a-form-item>

        <a-space :size="8">
          <a-button
            block
            type="primary"
            html-type="submit"
            :loading="stateForm.formClick"
          >
            {{ t('views.account.settings.submit') }}
          </a-button>
          <a-button
            type="default"
            @click="fnInitstateForm"
            :disabled="stateForm.formClick"
          >
            {{ t('views.account.settings.reset') }}
          </a-button>
        </a-space>
      </a-col>
      <a-col :lg="12" :md="12" :xs="24">
        <a-space direction="vertical" :size="16">
          <a-image :width="128" :height="128" :src="uerStore.getAvatar" />
          <span>
            {{
              t('views.account.settings.uploadPleace', {
                txt: '200x200、400x400',
              })
            }}
          </span>
          <a-upload
            name="file"
            list-type="picture"
            :max-count="1"
            :show-upload-list="false"
            :before-upload="fnBeforeUpload"
            :custom-request="fnUpload"
          >
            <a-button type="default" :loading="upState">
              {{ t('views.account.settings.upload') }}
            </a-button>
          </a-upload>
        </a-space>
      </a-col>
    </a-row>
  </a-form>
</template>

<style lang="less" scoped></style>
