<template>
  <div class=" column items-center" :class="{'q-pa-xl':$q.platform.is.desktop,'q-pa-sm':$q.platform.is.mobile}">
    <div class="col full-width" style="max-width: 1000px">
      <div class="rounded-borders bg-white light-shadow q-pa-lg" style="padding-bottom: 0 !important">
        <div :class="{'row':$q.platform.is.desktop,'column items-center':$q.platform.is.mobile}">
          <n-upload @change="uploadHandleChange()" style="width: unset" accept="image/*" :action="importFileUrl" @finish="handleFinish" file-list-style="display:none">
            <q-avatar size="160px" rounded class="bg-blue-2 cursor-pointer q-mr-md">
              <q-img :src="userInfo.photo" v-if="userInfo?.photo" mode="cover" />
              <span class="text-primary text-h2" v-else>{{ userInfo?.name.substring(0, 1) }}</span>
            </q-avatar>
          </n-upload>
          <div class="colunm" :class="{'q-ml-sm':$q.platform.is.desktop,'q-mt-md':$q.platform.is.mobile}">
            <div class="" :class="{'row items-center':$q.platform.is.desktop,'text-center':$q.platform.is.mobile}">
              <span style="font-size: 20px" class="text-weight-bold q-mr-md personal-hover">{{ userInfo.name }}</span>
              <span class="bg-green-11 text-green-14 rounded-borders q-px-sm">{{$t('verified')}}</span>
            </div>
            <div class="row q-mt-sm text-blue-grey-4" :class="{'justify-center':$q.platform.is.mobile}">
              <div class="personal-hover row">
                <svg-icon icon="Communication/Contact1.svg" color="nav" :size="18"></svg-icon>
                <span class="f12 q-ml-sm">{{ $t('personal.post') }}</span>
              </div>
              <div class="personal-hover row q-mx-lg">
                <svg-icon icon="Communication/Mail.svg" color="nav" :size="18"></svg-icon>
                <span class="f12 q-ml-sm">{{ userInfo.email }}</span>
              </div>
              <div class="personal-hover row q-mx-lg">
                <svg-icon icon="Map/Marker1.svg" color="nav" :size="18"></svg-icon>
                <span class="f12 q-ml-sm">{{ customerInfo.address }}</span>
              </div>
            </div>
            <div class="row justify-between col q-mt-lg din">
              <div class="column rounded-borders personal-data" :class="{ 'q-px-lg': $q.platform.is.desktop, 'q-py-sm': $q.platform.is.desktop, 'q-px-xs': $q.platform.is.mobile, 'q-py-xs': $q.platform.is.mobile }" style="flex: 1; flex-shrink: 0">
                <div class="row no-wrap items-center">
                  <q-icon class="q-pr-sm text-positive" name="arrow_upward"></q-icon>
                  <div class="q-ml-xs">
                    <span class="text-weight-bold" :class="{ fz16: $q.platform.is.desktop, fz14: $q.platform.is.mobile }">{{ $t('unit.jpc') }}</span>
                    <span class="text-weight-bold" :class="{ fz20: $q.platform.is.desktop, fz18: $q.platform.is.mobile }">0.00</span>
                  </div>
                </div>
                <div class="text-grey-13">{{ $t('personal.trading') }}</div>
              </div>
              <div class="column rounded-borders personal-data" :class="{ 'q-px-lg': $q.platform.is.desktop, 'q-py-sm': $q.platform.is.desktop, 'q-px-xs': $q.platform.is.mobile, 'q-py-xs': $q.platform.is.mobile, 'q-mx-lg': $q.platform.is.desktop, 'q-mx-sm': $q.platform.is.mobile }" style="flex: 1; flex-shrink: 0">
                <div class="row no-wrap items-center">
                  <q-icon class="q-pr-sm text-red-14" name="arrow_downward"></q-icon>
                  <div class="q-ml-xs">
                    <span class="text-weight-bold" :class="{ fz16: $q.platform.is.desktop, fz14: $q.platform.is.mobile }"></span>
                    <span class="text-weight-bold" :class="{ fz20: $q.platform.is.desktop, fz18: $q.platform.is.mobile }">0.00</span>
                  </div>
                </div>
                <div class="text-grey-13">{{ $t('personal.order') }}</div>
              </div>
              <div class="column rounded-borders personal-data" :class="{ 'q-px-lg': $q.platform.is.desktop, 'q-py-sm': $q.platform.is.desktop, 'q-px-xs': $q.platform.is.mobile, 'q-py-xs': $q.platform.is.mobile }" style="flex: 1; flex-shrink: 0">
                <div class="row no-wrap items-center">
                  <q-icon class="q-pr-sm text-positive" name="arrow_upward"></q-icon>
                  <div class="q-ml-xs">
                    <span class="text-weight-bold" :class="{ fz16: $q.platform.is.desktop, fz14: $q.platform.is.mobile }">%</span>
                    <span class="text-weight-bold" :class="{ fz20: $q.platform.is.desktop, fz18: $q.platform.is.mobile }">0.00</span>
                  </div>
                </div>
                <div class="text-grey-13">{{ $t('personal.cancel') }}</div>
              </div>
            </div>
          </div>
        </div>
        <q-tabs v-model="showActive" active-class="text-primary" class="text-blue-grey-4 q-mt-lg">
          <q-tab name="profile" :label="$t('personal.profile')" />
          <q-tab name="security" :label="$t('personal.security')" />
        </q-tabs>
      </div>
      <div class="rounded-borders bg-white light-shadow q-mt-lg q-pb-lg" v-if="showActive == 'profile'">
        <div class="q-pa-lg text-h6" style="border-bottom:1px solid #f1f1f1;">{{ $t('personal.ProfileDetails') }}</div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500">{{ $t('personal.TravelAgency') }}</div>
            <div class="col text-subtitle2">{{ customerInfo.customerName }}</div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500">{{ $t('personal.post') }}</div>
            <div class="col text-subtitle2">{{ customerInfo.contact }}</div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500">{{ $t('personal.Email') }}</div>
            <div class="col text-subtitle2">
              {{ userInfo.email }}
              <br v-if="$q.platform.is.mobile"/>
              <span v-if="userInfo.email" class="bg-green-11 text-green-14 rounded-borders q-px-sm"  :class="{'q-ml-md':$q.platform.is.desktop}">{{$t('verified')}}</span>
            </div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500">{{ $t('personal.numbering') }}</div>
            <div class="col text-subtitle2 text-weight-bolder">{{ customerInfo.uniqueCode }}</div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500">{{ $t('personal.LINEID') }}</div>
            <div class="col text-subtitle2 text-weight-bolder">{{ customerInfo.lineid}}</div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500">{{ $t('personal.Phone') }}</div>
            <div class="col text-subtitle2 text-weight-bolder">{{ customerInfo.contactNumber }}</div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500">{{ $t('personal.addreess') }}</div>
            <div class="col text-subtitle2">{{ customerInfo.address ?? $t('新北市三重區三和路四段101-1號17樓') }}</div>
          </div>
        </div>


        <div class="q-mt-lg q-mx-lg rounded-borders bg-orange-1 row"  :class="{'q-pa-lg':$q.platform.is.desktop,'q-pa-sm items-baseline':$q.platform.is.mobile}" style="border: 1px dashed; border-color: var(--q-warning)">
          <svg-icon :size="$q.platform.is.desktop?36:20" icon="Code/Warning-1-circle.svg" color="warning"></svg-icon>
          <div class="q-ml-md col">
            <div class="text-grey-900 text-subtitle1 text-weight-bold">{{ $t('personal.accountUpdate') }}</div>
            <div class="text-grey-700 f12">{{ $t('personal.accountUpdateTips') }}</div>
          </div>
        </div>
      </div>
      <div v-else class="rounded-borders bg-white light-shadow q-mt-lg q-pb-lg">
        <div class="q-pa-lg text-h6" style="border-bottom:1px solid #f1f1f1;">{{ $t('personal.resetPw') }}</div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500 desktop-only">{{ $t('personal.cpw') }}：</div>
            <div class="col-5 text-subtitle2" :class="{'col-5':$q.platform.is.desktop,'col-12':$q.platform.is.mobile}">
              <q-input v-model="password.current" standout dense type="password" ref="oldPassWordRef" :rules="[(val: any) => !!val || $t('personal.cpwTips')]" />
            </div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500 desktop-only">{{ $t('personal.npw') }}：</div>
            <div class="col-5 text-subtitle2" :class="{'col-5':$q.platform.is.desktop,'col-12':$q.platform.is.mobile}">
              <q-input v-model="password.new" ref="passwordRef" :rules="password.passRules" standout dense :hint="$t('newpwd.passTips')" type="password" />
              <div class="row q-mt-sm">
                <div class="col rounded-borders" style="height: 8px" :class="{ 'bg-positive': level.indexOf('low') != -1, 'bg-grey-3': level.indexOf('low') == -1 }"></div>
                <div class="col q-mx-md rounded-borders" style="height: 8px" :class="{ 'bg-positive': level.indexOf('middle') != -1, 'bg-grey-3': level.indexOf('middle') == -1 }"></div>
                <div class="col rounded-borders" style="height: 8px" :class="{ 'bg-positive': level.indexOf('high') != -1, 'bg-grey-3': level.indexOf('high') == -1 }"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500 desktop-only">{{ $t('personal.rpw') }}：</div>
            <div class="col-5 text-subtitle2" :class="{'col-5':$q.platform.is.desktop,'col-12':$q.platform.is.mobile}">
              <q-input v-model="password.repeat" standout dense type="password" ref="repeatPassWordRef" :rules="[(val: any) => val == password.new || $t('newpwd.repeatPassvalidate')]" />
            </div>
          </div>
        </div>
        <div class="q-px-lg">
          <div class="q-mt-lg row items-center">
            <div class="col-5 f12 text-grey-500 desktop-only"></div>
            <div class="col-5 text-subtitle2" :class="{'col-5':$q.platform.is.desktop,'col-12 text-center':$q.platform.is.mobile}">
              <q-btn :loading="subLoading" color="primary" :label="$t('personal.subBtn')" class="q-px-xl" unelevated  @click="submitSetPasswordHandler" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <q-inner-loading :showing="loading" :label="$t('loading')" label-class="text-grey-6 f12" />
  </div>
</template>

<script lang="ts">
import useMetaModule from '../../module/meta/metaModule'
import { useI18n } from 'vue-i18n'
import svgIcon from '../../components/global/svg-icon.vue'
import { defineComponent, inject, provide, reactive, ref, toRefs } from 'vue'
import { DirtionmaryHelper } from '../../config/dictionary'
import { dispatchAction, getStoreGetter } from 'src/store/utils'
import { UserGetter } from 'src/store/modules/user/getters'
import UserService from 'src/api/user'
import { ApiResult } from 'src/@types/enumHelper'
import message from 'src/utils/message'
import { UserActionsType } from 'src/store/modules/user/actions'
import { UploadFileInfo, NUpload } from 'naive-ui'
export default defineComponent({
  components: { svgIcon, NUpload },
  setup() {
    const data = reactive({
      loading: false,
      importFileUrl: 'https://mallApi.oytour.com/api/File/UploadTencent?MallBaseId=1',
      userInfo: getStoreGetter<UserGetter>('user', 'getUser'),
      showActive: 'profile',
      level: [] as string[],
      passwordRef: null as any,
      oldPassWordRef: null as any,
      repeatPassWordRef: null as any,
      subLoading: false,
      customerInfo: {} as any,
      password: {
        current: '',
        new: '',
        repeat: '',
        passRules: [(val: string | undefined) => (val && val.length >= 8) || t('newpwd.notEmptyPass'), (val: string | undefined) => (val && val.length <= 16) || t('newpwd.maxLengthPass'), (val: string) => methods.checkPassword(val) || '']
      }
    })
    let { setTitle } = useMetaModule()
    const { t } = useI18n()
    const pageTitle = inject(DirtionmaryHelper.PAGE_TITLE_KEY) as any
    pageTitle.value = t('personal.pageTitle')
    setTitle(pageTitle.value)

    const methods = {
      uploadHandleChange() {
        data.loading = true
      },
      handleFinish(options: { file: UploadFileInfo; event?: ProgressEvent }) {
        data.loading = false
        let r = (options.event?.target as XMLHttpRequest).response
        if (r) {
          let res = JSON.parse(r)
          if (res.resultCode == ApiResult.SUCCESS && res.data) {
            methods.modifyPhotoHandler(res.data)
          } else {
            message.errorMsg(t('upload.failed'))
            data.loading = false
          }
        } else {
          message.errorMsg(t('upload.failed'))
          data.loading = false
        }
      },
      modifyPhotoHandler(url: string) {
        UserService.setUserPhoto(url)
          .then(r => {
            if (r.data.resultCode == ApiResult.SUCCESS) {
              message.successMsg(t('photoSuccess'))
              data.userInfo.photo=url
              try {
                dispatchAction<UserActionsType>('user', 'setUserDetail', data.userInfo)
              } catch (error) {}
              setTimeout(() => {
                document.location.reload()
              }, 1000)
            } else {
              message.errorMsg(r.data.message)
            }
            data.loading = false
          })
          .catch(e => {
            data.loading = false
            message.errorMsg(e.message)
          })
      },
      checkPassword(value: string): boolean {
        data.level = []
        if (value && value.length >= 8 && value.length <= 16) {
          // 校验是数字
          const regex1 = /^\d+$/
          // 校验字母
          const regex2 = /^[A-Za-z]+$/
          // 校验符号
          const regex3 = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$/
          if (regex1.test(value)) {
            data.level.push('low')
          } else if (regex2.test(value)) {
            data.level.push('low')
          } else if (regex3.test(value)) {
            data.level.push('low')
          } else if (/^[A-Za-z\d]+$/.test(value)) {
            data.level.push('low')
            data.level.push('middle')
          } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\d]+$/.test(value)) {
            data.level.push('low')
            data.level.push('middle')
          } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z]+$/.test(value)) {
            data.level.push('low')
            data.level.push('middle')
          } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z\d]+$/.test(value)) {
            data.level.push('low')
            data.level.push('middle')
            data.level.push('high')
          }
          return true
        }
        return false
      },
      submitSetPasswordHandler() {
        if (data.subLoading) return
        data.passwordRef.validate()
        data.oldPassWordRef.validate()
        data.repeatPassWordRef.validate()
        if (!data.passwordRef.hasError && !data.oldPassWordRef.hasError && !data.oldPassWordRef.hasError) {
          data.subLoading = true
          UserService.setNewPassword(data.password.current, data.password.new)
            .then(r => {
              data.subLoading = false
              if (r.data.resultCode == ApiResult.SUCCESS) {
                message.successMsg(t('personal.updateSuccess'))
                setTimeout(() => {
                  dispatchAction<UserActionsType>('user', 'setUserSignout', null)
                  window.location.reload()
                }, 2000)
              } else {
                message.errorMsg(r.data.message)
              }
              data.subLoading = false
            })
            .catch(e => {
              data.subLoading = false
              message.errorMsg(e.message)
            })
        }
      },
      getCustomerInfo() {
        UserService.getCustomerInfo()
          .then(r => {
            data.loading = false
            if (r.data.resultCode == ApiResult.SUCCESS) {
              data.customerInfo=r.data.data
            } else {
              message.errorMsg(r.data.message)
            }
            data.loading = false
          })
          .catch(e => {
            data.loading = false
            message.errorMsg(e.message)
          })
      },
    }

    methods.getCustomerInfo()
    return {
      ...toRefs(data),
      ...methods
    }
  }
})
</script>

<style>
.personal-HeadImg:hover .personal-HeadImg-edit {
  display: block;
  color: #019df5;
}
.personal-HeadImg-edit {
  box-shadow: 0 0.5rem 1.5rem 0.5rem rgb(0 0 0 / 8%);
  border-radius: 50%;
  top: -10px;
  right: -10px;
  display: none;
  color: #a7a5b7;
}
.personal-data {
  border: 1px dashed #eeeeee;
}
.personal-hover {
  cursor: pointer;
}
.personal-hover:hover {
  color: var(--q-primary);
}
.personal-hover:hover .svg-icon-nav g [fill] {
  fill: var(--q-primary) !important;
}
</style>
