<template>
  <view class="pd-b-px-55">
    <van-sticky>
      <view class="top-bar justify-center bg-white sh mg-b-20">
        <van-icon class="top-left" name="arrow-left" @tap="goBack" />
        <view class="top-center">{{ state.title }}</view>
      </view>
    </van-sticky>
    <van-cell-group class="pd-h-5 mg-b-15">
      <van-cell class="pd-t-px-10 pd-b-px-0" :border="false">
        <template #title>
          <van-uploader class="round" v-model="state.headList" preview-size="60" :max-size="1024 * 1024 * 10"
            :after-read="upload" max-count="1">
            <template #default v-if="state.data.userHeadImage">
              <van-image fit="cover" width="60px" height="60px" round :src="state.data.userHeadImage" />
            </template>
          </van-uploader>
        </template>
      </van-cell>
      <van-cell is-link @tap="onEdit('真实姓名', 'userName', state.data.userName, 10)">
        <template #title>
          <text class="text-black">真实姓名</text>
        </template>
        <template #right-icon>
          <view class="text-darkGray">
            <view class="cell_value">{{ state.data.userName }}</view>
            <van-icon name="arrow" class="pd-l-10" />
          </view>
        </template>
      </van-cell>
      <van-cell is-link @tap="onSex">
        <template #title>
          <text class="text-black">性别</text>
        </template>
        <template #right-icon>
          <view class="text-darkGray">{{ Enum.get('userSex', state.data.userSex) }}
            <van-icon name="arrow" class="pd-l-10" />
          </view>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group class="pd-h-5">
      <van-cell>
        <template #title>
          <text class="text-black">手机</text>
        </template>
        <template #right-icon>
          <view class="text-darkGray">{{ state.data.userPhone }}</view>
        </template>
      </van-cell>
      <van-cell is-link @tap="onEdit('邮箱', 'userEmail', state.data.userEmail, '25')">
        <template #title>
          <text class="text-black">邮箱</text>
        </template>
        <template #right-icon>
          <view class="text-darkGray">
            <view class="cell_value">{{ state.data.userEmail || '未绑定' }}</view>
            <van-icon name="arrow" class="pd-l-10" />
          </view>
        </template>
      </van-cell>
      <van-cell is-link @tap="onChangePwd">
        <template #title>
          <text class="text-black">修改密码</text>
        </template>
        <template #right-icon>
          <view class="text-darkGray">
            <van-icon name="arrow" class="pd-l-10" />
          </view>
        </template>
      </van-cell>
    </van-cell-group>
    <div class="pd-50">
      <van-button class="text-l" :loading="state.loading.logout" @tap="logout"
        color="linear-gradient(315deg, #FE521F 0%, #FE7902 100%)" round block>
        退出登录
      </van-button>
	    <div style="text-align: center;position: absolute;bottom: 10px;width: 100%;left: 0" @click="gotoU">
		    <img style="width: 20px;height: 20px;vertical-align: sub;margin-right: 10px" src="../../static/favicon.ico" alt=""><span style="color: #666666">提供技术支持</span>
	    </div>
    </div>
    <!-- 通用改单个数据的dialog -->
    <van-form @submit="onEditChange" class="round">
      <van-dialog class="withBg pd-b-px-70" v-model:show="state.dialog.edit.show" theme="round-button" width="264px">
        <template #title>
          <view class="pd-h-px-20">
            <view class="mg-t-px-10-m text-bold">{{ '设置' + state.dialog.edit.title }}</view>
            <view class="text-gray text-s" style="min-height: 20px;"></view>
          </view>
        </template>
        <view class="pd-h-px-20 pd-v-px-10">
          <van-field ref="editField" v-model="state.dialog.edit.value" :class="{ 'field-focus': state.focus == 'edit' }"
            :placeholder="'请输入' + state.dialog.edit.title" @focus="onFocus('edit')" @blur="onFocus('')" clearable
            clear-trigger="always" :maxlength="state.dialog.edit.len" enterkeyhint="done" autocomplete="off" />
        </view>
        <template #footer>
          <van-action-bar class="pd-h-px-15 pd-b-px-15">
            <van-action-bar-button type="warning" text="取消" @tap="state.dialog.edit.show = false" />
            <van-action-bar-button type="danger" text="保存" native-type="submit" />
          </van-action-bar>
        </template>
      </van-dialog>
    </van-form>
    <van-form @submit="alterPassword" class="round">
      <van-dialog class="withBg pd-b-px-70" v-model:show="state.dialog.pwd.show" theme="round-button" width="320px">
        <template #title>
          <view class="pd-h-px-20">
            <view class="mg-t-px-10-m text-bold">修改密码</view>
            <view class="text-gray text-s" style="min-height: 20px;">
              忘记当前密码？
              <text class="text-orange" @tap="onForget">短信找回</text>
            </view>
          </view>
        </template>
        <view class="pd-h-px-20 pd-v-px-10">
          <van-field v-model="state.dialog.pwd.originPwd" class="mg-b-30" autocomplete="off" ref="pwdField"
            :class="{ 'field-focus': state.focus == 'originPwd' }" placeholder="请输入当前密码" @focus="onFocus('originPwd')"
            @blur="onFocus('')" :type="state.dialog.pwd.showOriginPwd ? 'text' : 'password'" clearable
            clear-trigger="always">
            <template #right-icon>
              <view class="flex">
                <van-icon class="mg-l-5" class-prefix="icon"
                  @tap="state.dialog.pwd.showOriginPwd = !state.dialog.pwd.showOriginPwd"
                  :name="state.dialog.pwd.showOriginPwd ? 'xianshimima' : 'yincangmima'" />
              </view>
            </template>
          </van-field>
          <van-field v-model="state.dialog.pwd.pwd" class="mg-b-30" :class="{ 'field-focus': state.focus == 'pwd' }"
            placeholder="请确认新密码" @focus="onFocus('pwd')" @blur="onFocus('')" autocomplete="off"
            :type="state.dialog.pwd.showPwd ? 'text' : 'password'" clearable clear-trigger="always">
            <template #right-icon>
              <view class="flex">
                <van-icon class="mg-l-5" class-prefix="icon" @tap="state.dialog.pwd.showPwd = !state.dialog.pwd.showPwd"
                  :name="state.dialog.pwd.showPwd ? 'xianshimima' : 'yincangmima'" />
              </view>
            </template>
          </van-field>
          <van-field v-model="state.dialog.pwd.rePwd" :class="{ 'field-focus': state.focus == 'rePwd' }"
            placeholder="请再次输入新密码" @focus="onFocus('rePwd')" @blur="onFocus('')" autocomplete="off"
            :type="state.dialog.pwd.showRePwd ? 'text' : 'password'" clearable clear-trigger="always">
            <template #right-icon>
              <view class="flex">
                <template v-if="state.dialog.pwd.rePwd">
                  <van-icon v-if="validReRwd" color="#39b54a" name="checked" />
                  <van-icon v-else color="#e54d42" name="clear" />
                </template>
                <van-icon class="mg-l-20" class-prefix="icon"
                  @tap="state.dialog.pwd.showRePwd = !state.dialog.pwd.showRePwd"
                  :name="state.dialog.pwd.showRePwd ? 'xianshimima' : 'yincangmima'" />
              </view>
            </template>
          </van-field>
        </view>
        <template #footer>
          <van-action-bar class="pd-h-px-15 pd-b-px-15">
            <van-action-bar-button type="warning" text="取消" @tap="state.dialog.pwd.show = false" />
            <van-action-bar-button type="danger" text="修改" native-type="submit" />
          </van-action-bar>
        </template>
      </van-dialog>
    </van-form>
    <van-popup v-model:show="state.popup.sex.show" round position="bottom">
      <van-picker title="性别" :columns="final.sexOptions" :default-index="state.popup.sex.default"
        @confirm="onSexChange" />
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import { computed, onBeforeMount, reactive, ref } from "vue";
import { Dialog, Toast } from 'vant';
import api from "@/api";
import { Enum, PageUtils } from '@/utils/utils';
import md5 from 'md5';

const state = reactive({
  title: PageUtils.getTitle(),
  phone: '',
  data: {} as any,
  headList: [] as any,
  dialog: {
    edit: {
      show: false,
      title: '',
      name: '',
      value: '',
      len: ''
    },
    pwd: {
      show: false,
      originPwd: '',
      pwd: '',
      rePwd: '',
      showOriginPwd: false,
      showPwd: false,
      showRePwd: false
    },
  },
  popup: {
    sex: {
      show: false,
      default: 0
    }
  },
  focus: '',
  loading: {
    edit: false,
    sex: false,
    pwd: false,
    logout: false
  }
});
const final = {
  sexOptions: [
    { text: '男', values: '1', children: null },
    { text: '女', values: '0', children: null }
  ]
}
const editField: any = ref()
const pwdField: any = ref()

const validReRwd = computed(() => {
  return state.dialog.pwd.pwd == state.dialog.pwd.rePwd
})

onBeforeMount(() => {
  const user: any = uni.getStorageSync('user') || { account: undefined }
  if (user.token) {
    state.phone = user.account
    if (!state.phone) {
      Dialog.alert({
        title: '数据异常',
        message: '当前用户缺少手机信息，请联系开发人员#021',
        confirmButtonText: '返回首页'
      }).then(() => {
        uni.reLaunch({
          url: '/'
        })
      })
      return
    }
    accountInfo()
  } else {
    Dialog.confirm({
      message: '您尚未登录，请前往登录',
      title: "提示",
      cancelButtonText: '返回首页'
    }).then(() => {
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }).catch(() => {
      uni.reLaunch({
        url: '/'
      })
    });
  }
})

function gotoU() {
    uni.redirectTo({
        url: "/pages/my/technicalSupport?name=detail",
    });
}
function goBack() {
  PageUtils.goBack()
}
function accountInfo() {
  api.accountInfo({ phone: state.phone }).then((data: any) => {
    state.data = data
  })
}
function onEdit(title: string, name: string, value: any, len?: any) {
  state.dialog.edit.title = title
  state.dialog.edit.name = name
  state.dialog.edit.len = len || ''
  state.dialog.edit.show = true
  setTimeout(() => {
    editField.value && editField.value.focus()
    state.dialog.edit.value = value
  })
}
function onFocus(focus: string) {
  state.focus = focus
}
function onSex() {
  const index = final.sexOptions.findIndex((item: any) => item.values == state.data.userSex)
  state.popup.sex.default = index || 0
  state.popup.sex.show = true
}
function onSexChange(list: Array<any>) {
  if (state.loading.sex) return
  state.loading.sex = true
  api.setSex({
    mobilePhone: state.phone,
    sex: list[0].values
  }).then(() => {
    state.popup.sex.show = false
    state.data.userSex = list[0].values
    Toast.success('保存成功')
  }).finally(() => {
    state.loading.sex = false
  })
}
function onEditChange() {
  if (state.loading.edit) return
  state.loading.edit = true
  if (state.dialog.edit.name == 'userName') {
    if (state.dialog.edit.value == '') {
      Toast('请输入真实姓名')
      state.loading.edit = false
      return
    }
    api.bindName({
      mobilePhone: state.phone,
      name: state.dialog.edit.value
    }).then(() => {
      state.dialog.edit.show = false
      state.data.userName = state.dialog.edit.value
      Toast.success('保存成功')
    }).finally(() => {
      state.loading.edit = false
    })
  } else if (state.dialog.edit.name == 'userEmail') {
    if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(state.dialog.edit.value)) {
      Toast('请正确输入邮箱')
      state.loading.edit = false
      return
    }
    api.bindEmail({
      mobilePhone: state.phone,
      email: state.dialog.edit.value
    }).then(() => {
      state.dialog.edit.show = false
      state.data.userEmail = state.dialog.edit.value
      Toast.success('保存成功')
    }).finally(() => {
      state.loading.edit = false
    })
  } else {
    console.error('请开发人员补充onEditChange中的逻辑')
    state.loading.edit = false
  }
}
function goto(url: any) {
  url && uni.navigateTo({ url })
}
function upload(e: any) {
  e.status = 'uploading'
  e.message = '上传中...'
  api.upload(e.file).then((data: any) => {
    api.setHeadImage({
      mobilePhone: state.phone,
      headImage: data
    }).then(() => {
      // #1: 与下面注释#2一同使用
      state.data.userHeadImage = data
      e.status = 'done'
    }).catch(() => {
      Toast('修改头像失败')
    })
  }).catch(() => {
    Toast('上传头像失败')
  }).finally(() => {
    // #2你删掉下面这句话就能知道，为什么我要加
    state.headList = []
  })
}
function onChangePwd() {
  state.dialog.pwd = {
    show: true,
    originPwd: '',
    pwd: '',
    rePwd: '',
    showOriginPwd: false,
    showPwd: false,
    showRePwd: false
  }
  setTimeout(() => {
    pwdField.value && pwdField.value.focus()
  })
}
function alterPassword() {
  if (!/^[0-9a-zA-Z_]{6,16}$/.test(state.dialog.pwd.pwd)) {
    Dialog.alert({
      title: '提示',
      message: '请输入正确格式（只可包含数字，英文和下划线），且长度为6-16位之间',
    })
    return
  }
  if (state.loading.pwd) return
  state.loading.edit = true
  api.alterPassword({
    mobilePhone: state.phone,
    password: state.dialog.pwd.originPwd,
    newPwd: state.dialog.pwd.pwd,
    confirmPwd: state.dialog.pwd.rePwd,
  }).then(() => {
    state.dialog.pwd.show = false
    Toast.success('修改密码成功')
  }).finally(() => {
    state.loading.pwd = false
  })
}
function onForget() {
  state.dialog.pwd.show = false
  goto(`/pages/login/forget?phone=${state.phone}&reset=1`)
}
function logout() {
  api.logout().finally(() => {
    uni.reLaunch({
      url: '/pages/login/login'
    })
  })
}
</script>

<style lang="scss" scoped>
.top_tab {
  width: 100vw;
}
.cell_value {
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  overflow: hidden;
  max-width: 70vw;
  height: 20px;
}
</style>
