<template>
  <div class="app-container">
    <van-form ref="formRef" @submit="onSubmit" class="mt10" required="auto">
      <van-cell-group>
        <van-field
          v-model="state.form.oldPassword"
          :type="state.showOldPassword ? 'text' : 'password'"
          label="旧密码"
          placeholder="旧密码"
          :right-icon="state.showOldPassword ? 'eye-o' : 'closed-eye'"
          @click-right-icon="state.showOldPassword = !state.showOldPassword"
          :rules="[{ required: true, message: '请输入旧密码' }]"
        />
        <van-field
          v-model="state.form.newPassword"
          :type="state.showNewPassword ? 'text' : 'password'"
          label="新密码"
          placeholder="新密码"
          :right-icon="state.showNewPassword ? 'eye-o' : 'closed-eye'"
          @click-right-icon="state.showNewPassword = !state.showNewPassword"
          :rules="[{ required: true, message: '请输入新密码' }, {validator: checkPassword, message: '密码不合法'}]"
        />
        <van-field
          v-model="state.form.newPassword2"
          :type="state.showNewPassword2 ? 'text' : 'password'"
          label="确认密码"
          placeholder="确认密码"
          :right-icon="state.showNewPassword2 ? 'eye-o' : 'closed-eye'"
          @click-right-icon="state.showNewPassword2 = !state.showNewPassword2"
          :rules="[{ required: true, message: '请输入确认密码', validator: checkConfirmPassword }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">保存</van-button>
      </div>
    </van-form>
  </div>
</template>

<script lang="ts" setup>
  import { storeToRefs } from 'pinia'
  import { useUserInfo } from '/@/stores/userInfo'
  import { Local, Session } from '/@/utils/storage'
  import { showConfirmDialog, showDialog, showNotify } from 'vant'
  import { useRouter } from 'vue-router'
  import { nextTick, onMounted, reactive, ref } from 'vue'
  import { useUserApi } from '/@/api/system/user'
  import to from 'await-to-js'
  import { useDictApi } from '/@/api/system/dict'
  import Cropper from 'cropperjs'
  import 'cropperjs/dist/cropper.css'
  import axios from 'axios' 
  import crypto from 'sm-crypto';
  import { useLoginApi } from '/@/api/login'
  import { enhancedEncrypt, decryptLoginData, encryptWithBackendConfig } from '/@/utils/aesCrypto';
  const sm3 = crypto.sm3;
  const router = useRouter()
  const storesUseUserInfo = useUserInfo()
  const { userInfos } = storeToRefs(storesUseUserInfo)
  const userApi = useUserApi()
  const formRef = ref()
  const dictApi = useDictApi()
  const userSexList = ref(<RowDicDataType[]>[])
  const loginApi = useLoginApi()
  const state = reactive({
    showOldPassword: false,
    showNewPassword: false,
    showNewPassword2: false,
    form: {
      oldPassword: '',
      newPassword: '',
      newPassword2: '',
      saltValue: '',
      token: ''
    },
    dialog: {
      isShowDialog: false,
      type: '',
      title: '',
      submitTxt: ''
    }
  })
  const checkPassword = (value: string) => {
    // if (/^[\w\S]{6,18}$/.test(value) && /[a-z]+/.test(value) && /[A-Z]+/.test(value) && /\d+/.test(value) && /[^a-zA-Z0-9]+/.test(value)) {
    //   return true
    // } else {
    //   return '密码必须包含大小写字母、数字和特殊字符，长度在6~18之间'
    // }
    if (!value) {
      return "请输入新密码"
    }

    return loginApi.validatePassword({ password: value })
      .then(res => {
        return true
      })
      .catch((err) => {
        return err.message || "密码不合法"
      })
  }
  const checkConfirmPassword = (value: string) => {
    if (value !== state.form.newPassword) {
      return '两次输入的密码不一致'
    } else {
      return true
    }
  }
  const onSubmit = async () => {
    const [errValid] = await to(formRef.value.validate())
    if (errValid) return
    const params = JSON.parse(JSON.stringify(state.form))
    params.oldPassword = sm3(params.oldPassword)
    params.saltValue = encryptWithBackendConfig(params.newPassword)
    params.newPassword = sm3(params.newPassword)
    params.token = localStorage.getItem('animalToken')
    const [err]: ToResponse = await to(userApi.changePassword(params))
    if (err) return
    showNotify({
      type: 'success',
      message: '修改成功,请重新登录'
    })
    Session.clear();
    Local.remove('token')
    router.push('/login')
  }
  onMounted(() => {})
</script>

<style lang="scss" scoped>
  .app-container {
    header {
      background-color: #1c9bfd;
      color: #fff;
      padding: 10px;
      border-radius: 8px;
      margin-top: 10px;
      display: flex;
      img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        margin-right: 10px;
      }
      .content {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        overflow: hidden;
        .bold {
          display: flex;
          align-items: center;
          font-weight: bold;
          // flex-wrap: nowrap;
          white-space: nowrap;
          .van-text-ellipsis {
            flex: 1;
          }
        }
      }
    }
    .avatar {
      vertical-align: middle;
    }
  }
  .cropper-warp {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #eee;
    .cropper-warp-left {
      height: 350px;
      width: 350px;
    }
  }
</style>
