<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view v-if="!showImageCropper" class="main-container">
      <wk-nav-bar title="个人信息">
        <!-- #ifndef MP-WEIXIN -->
        <button
          class="button white-btn"
          @click="handleSave">
          保存
        </button>
        <!-- #endif -->
      </wk-nav-bar>

      <view class="container">
        <view class="scroll-content">
          <view class="avatar-box">
            <view class="box-title">
              头像
            </view>
            <view class="box-cell">
              <wk-avatar
                :name="userInfo.realname"
                :avatar="userInfo.img"
                :preview="false"
                class="avatar" />
              <text class="wk wk-arrow-right icon" @click="handlToEditAvatar" />
            </view>
          </view>

          <wk-form ref="form" :fields="fieldArr" />
        </view>
      </view>

      <!-- #ifdef MP-WEIXIN -->
      <view class="footer-btn-group">
        <button class="button" @click="handleSave">
          保存
        </button>
      </view>
      <!-- #endif -->

      <uni-popup ref="popupOptions">
        <view class="pop-wrapper">
          <view
            v-for="(item, index) in popOptions"
            :key="index"
            class="pop-item"
            @click.stop="handlePopChoose(item)">
            {{ item.label }}
          </view>
        </view>
      </uni-popup>
    </view>

    <view v-else class="cropper-wrapper">
      <invinbg-image-cropper
        :src="tempFilePath"
        @confirm="handleCropperConfirm"
        @cancel="handleCropperCancel" />
    </view>
  </view>
</template>

<script>
  import { AdminQueryLoginUser, AdminSetUser } from 'API/admin'

  import InvinbgImageCropper from './invinbg-image-cropper/index.vue'

  import { isEmail } from '@/utils/lib.js'
  import { BASE_URL_FN } from '@/config.js'
  import { mapMutations } from 'vuex'
  import Fields from '@/utils/fields.js'

  export default {
    name: 'PersonalUser',
    components: {
      InvinbgImageCropper
    },
    data() {
      return {
        userInfo: {},

        popOptions: [
          { label: '修改头像', value: 'update' }
        ],

        fieldArr: [
          new Fields({
            name: '姓名',
            fieldName: 'realname',
            formType: 'text',
            isNull: 1
          }),
          new Fields({
            name: '性别',
            fieldName: 'sex',
            formType: 'select',
            setting: [
              { label: '男', value: 1 },
              { label: '女', value: 2 }
            ]
          }),
          new Fields({
            name: '邮箱',
            fieldName: 'email',
            formType: 'email'
          }),
          new Fields({
            name: '岗位',
            fieldName: 'post',
            formType: 'text'
          }),
          new Fields({
            name: '手机',
            fieldName: 'mobile',
            formType: 'mobile',
            disabled: true
          }),
          new Fields({
            name: '部门',
            fieldName: 'deptName',
            formType: 'text',
            disabled: true
          })
        ],

        showImageCropper: false,
        tempFilePath: '',
        cropFilePath: ''
      }
    },
    onLoad() {
      this.getUserInfo()
    },
    methods: {
			...mapMutations({
				setUserInfo: 'user/SET_USER_INFO'
			}),
			getUserInfo() {
				AdminQueryLoginUser().then(res => {
					this.userInfo = res
					this.setUserInfo(res)
					this.$nextTick(() => {
						if (this.$refs.form) {
							this.$refs.form.setForm({
								...res,
								sex: res.sex ? [{ label: this.getSex(res.sex), value: res.sex }] : []
							})
						}
					})
				}).catch()
			},

			getSex(sex) {
				if (isNaN(Number(sex))) return sex
				if (Number(sex) === 1) return '男'
				else if (Number(sex) === 2) return '女'
				return ''
			},

			/**
			 * 去修改头像
			 */
			handlToEditAvatar() {
				this.$refs.popupOptions.open()
			},

			handlePopChoose() {
				this.$refs.popupOptions.close()
				const that = this
				uni.chooseImage({
          count: 1, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album'], // 从相册选择
          success: (res) => {
						that.showImageCropper = true
						that.$nextTick(function() {
							that.tempFilePath = res.tempFilePaths.shift()
						})
          }
        })
			},

			handleCropperConfirm(e) {
				console.log('confirm: ', e)
				this.showImageCropper = false
				this.tempFilePath = ''
				this.cropFilePath = e.detail.tempFilePath;
				const that = this
				const appid = uni.getStorageSync('appid') || ''
				const header = {
					'Admin-Token': uni.getStorageSync('token') || ''
				}
				if (appid) {
					header.k = appid
				}
				uni.uploadFile({
					url: BASE_URL_FN() + 'adminUser/updateImg',
					fileType: 'image',
					name: 'file',
					header,
					filePath: that.cropFilePath,
					success: res => {
						that.$refreshAndToPrev(that, false)
						that.getUserInfo()
					},
					fail: (error) => {
						console.log('err', error)
					}
				})
			},

			handleCropperCancel() {
				this.showImageCropper = false
				this.$nextTick(() => {
					if (this.$refs.form) {
						this.$refs.form.setForm({
							...this.userInfo,
							sex: this.userInfo.sex ? [{ label: this.getSex(this.userInfo.sex), value: this.userInfo.sex }] : []
						})
					}
				})
			},

			/**
			 * 保存
			 */
			handleSave() {
				this.$refs.form.getForm().then(form => {
					form = form.entity
					delete form.mobile
					delete form.deptName
					form.userId = this.userInfo.userId
					form.username = this.userInfo.username
					console.log('save: ', form)

					AdminSetUser(form).then(res => {
						this.getUserInfo()
						this.$toast('保存成功')
						this.$refreshAndToPrev(this)
					}).catch()
				}).catch(() => {})
			}
    }
  }
</script>

<style scoped lang="scss">
	.main-container {
		.container {
			flex: 1;
			width: 100%;
			overflow: hidden;

			.scroll-content {
				width: 100%;
				height: 100%;
				overflow: auto;
			}

			.avatar-box {
				background-color: white;
				padding: 20rpx 30rpx;
				.box-title {
					font-size: 30rpx;
				}
				.box-cell {
					margin-top: 20rpx;
					@include left;
					.avatar {
						width: 80rpx;
						height: 80rpx;
					}
					.icon {
						flex: 1;
						font-size: 28rpx;
						color: $light;
						text-align: right;
						margin-left: 10rpx;
					}
				}
			}

		}
	}

	.cropper-wrapper {
		flex: 1;
		width: 100%;
	}

</style>
