import {
  fetchPerson
} from '~/services/usercenter/fetchPerson';
import {
  updatePerson
} from '~/services/usercenter/updatePerson';
import {
  phoneEncryption
} from '~/utils/util';
import Toast from 'tdesign-miniprogram/toast/index';
import { ServerBasePath } from '~/services/_utils/request'

Page({
  data: {
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: 0,
      phoneNumber: '',
    },
    showUnbindConfirm: false,
    pickerOptions: [{
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    typeVisible: false,
    genderMap: ['', '男', '女'],
  },
  onLoad() {
    this.init();
  },
  init() {
    this.fetchData();
  },

  fetchData() {
    fetchPerson().then(({
      personInfo
    }) => {
      this.setData({
        personInfo,
        'personInfo.phoneNumber': phoneEncryption(personInfo.phoneNumber),
      });
    });
  },

  /** 提交 */
  submit() {
    let personInfo = this.data.personInfo
    let data = {
      customerAvatar: personInfo.avatarUrl,
      customerNickname: personInfo.nickName,
      customerGender: personInfo.gender,
    }
    updatePerson(data).then((res) => {
      if (res.code == 200) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: `保存成功`,
          theme: 'success',
        })
        wx.reLaunch({
          url: `/pages/usercenter/index`,
        });
      }
    })
  },

  /** 点击单元格 */
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;
    const {
      nickName
    } = this.data.personInfo;

    switch (dataset.type) {
      case 'gender':
        this.setData({
          typeVisible: true,
        });
        break;
      case 'name':
        wx.navigateTo({
          url: `/pages/usercenter/name-edit/index?name=${nickName}`,
        });
        break;
      case 'avatarUrl':
        this.toModifyAvatar();
        break;
      default: {
        break;
      }
    }
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success',
        });
      },
    );
  },

  /** 修改昵称 */
  changeNickName(e) {
    this.setData({
      'personInfo.nickName': e.detail.value
    })
  },

  /** 修改头像 */
  async toModifyAvatar() {
    let that = this
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              path,
              size
            } = res.tempFiles[0];
            const tempFilePaths = res.tempFilePaths;
            let tempFilePath = tempFilePaths[0];
            // 上传图片到服务器
            wx.uploadFile({
              url: ServerBasePath + 'Common/UploadFile', // 上传接口地址
              filePath: tempFilePath, // 要上传的文件的临时路径
              name: 'file', // 上传文件对应的字段名
              success: function (uploadRes) {
                // 上传成功，服务器返回的数据
                let url = JSON.parse(uploadRes.data).data.url
                that.setData({
                  'personInfo.avatarUrl': url
                })

              },
              fail: function (uploadError) {
                // 上传失败，处理错误
                console.error(uploadError);
              }
            });
            if (size <= 10485760) {
              resolve(path);
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      Toast({
        context: this,
        selector: '#t-toast',
        message: `头像上传成功`,
        theme: 'success',
      })
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'error',
      });
    }
  },
});