<template>
  <Dialog
    title="个人资料"
    :is-dialog-exist="isAdminEditDlgExist"
    :dialog-style="{
      '--dialog-width': '807px',
      '--dialog-height': '543px',
      '--title-height': '51px',
      '--footer-height': '62px'
    }"
    @close-dialog="handleClose"
  >
    <div v-loading="uploadLoading"
         class="slot-box flex-column"
         element-loading-text="图片上传中..."
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">
      <div class="cover-wrap">
        <div class="avatar-big-box">
          <img v-if="adminInfo.headerImg" :src="adminInfo.headerImg" alt="" />
          <img v-else :src="defaultAvatar" alt="" />
        </div>
        <el-upload
          action=""
          :on-change="handleImageSelected"
          :auto-upload="false"
          :show-file-list="false"
        >
          <div class="cover-layer">
            <span>点击编辑</span>
          </div>
        </el-upload>
      </div>
      <div v-if="adminInfo.phone" class="nickname flex-box">
        {{ adminInfo.phone | maskPhone }}
      </div>
      <div class="form-box flex-column">
        <el-form ref="passForm" class="flex-column" label-width="82px" :model="passForm" :rules="rules">
          <el-form-item label="Team ID:">
            <el-input :value="adminInfo.teamId"
                      size="mini"
                      class="form-input-2"
                      disabled />
            <FNButton
              v-clipboard:copy="adminInfo.teamId"
              v-clipboard:success="clipboardSuccess"
              v-clipboard:error="clipboardError"
              size="mini"
              class="copy-btn"
            >
              <template slot="icon">
                <svg-icon icon-class="copy" />
                <span>复制</span>
              </template>
            </FNButton>
          </el-form-item>
          <el-form-item label="新密码:" prop="pass">
            <el-input v-model="passForm.pass"
                      type="password"
                      size="mini"
                      class="form-input-1" />
          </el-form-item>
          <el-form-item label="确认密码:" prop="checkPass">
            <el-input v-model="passForm.checkPass"
                      type="password"
                      size="mini"
                      class="form-input-1" />
          </el-form-item>
          <el-form-item v-if="needCaptcha" label="验证码">
            <el-input v-model="passForm.captcha" size="mini" class="form-input-3" placeholder="请输入验证码" />
            <CountDownBtn class="captcha-btn" @on-click="sendSms" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div slot="footer">
      <button class="bottom-btn blue-btn" @click="savePassword">确定</button>
      <button class="bottom-btn gray-btn ml-20" @click="resetForm">重置</button>
    </div>
  </Dialog>
</template>

<script>
import Dialog from '@/components/Dialog/index'
import { createNamespacedHelpers } from 'vuex'
import CountDownBtn from '@/components/Common/CountDownBtn'
import FNButton from '@/components/FNButton/index'
import clipboard from '@/directive/clipboard'
import { updateAdminPwd } from '@/api/admin'
import { sendSms } from '@/api/admin'
import { maskPhone } from '@/filters'
import CommonSet from '@/api/setting-center/CommonSet'

const { mapGetters, mapActions } = createNamespacedHelpers('admin-info')
export default {
  name: 'AdminInfoDialog',
  components: {
    Dialog,
    CountDownBtn,
    FNButton
  },
  filters: {
    maskPhone
  },
  directives: {
    clipboard
  },
  props: {},
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passForm.checkPass !== '') {
          this.$refs.passForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      uploadLoading: false,
      defaultAvatar: './pic/default/default_avatar.png',
      needCaptcha: false,
      passForm: {
        pass: '',
        checkPass: '',
        captcha: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '短信验证码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['isAdminEditDlgExist', 'adminInfo'])
  },
  created() {
    this.initDialogForm()
  },
  methods: {
    ...mapActions({ initAdminInfo: 'initAdminInfo', changeAvatar: 'updateAvatar' }),
    initDialogForm() {
      this.initAdminInfo()
    },
    handleClose() {
      this.$store.commit('admin-info/TOGGLE_EDIT_DLG', false)
    },
    sendSms() {
      sendSms().then(() => {
        this.$message.success('发送成功')
      }).catch((res) => {
        this.$message.error(res.data.msg)
        this.$refs['count-down-btn'].textContent = '重新发送'
        // this.$refs['count-down-btn'].classList.remove('gray-btn').add('blue-btn')
      })
    },
    savePassword() {
      this.$refs['passForm'].validate((valid) => {
        if (valid) {
          const data = { pwd: this.passForm.pass }
          if (this.passForm.captcha) {
            data.code = this.passForm.captcha
          }
          updateAdminPwd(data).then((res) => {
            if (res.code === 401) {
              this.needCaptcha = true
              this.$message.error('本次操作需要短信验证码')
              return false
            } else {
              this.needCaptcha = false
              this.passForm.captcha = ''
              this.$store.commit('admin-info/TOGGLE_EDIT_DLG', false)
              this.$message.success('操作成功')

              // 退出登录
              this.$store.dispatch('user/logout').then((res) => {
                this.$router.push(`/login?redirect=${this.$route.fullPath}`)
              })
            }
          }).catch(() => {
            this.$message.error('操作失败')
          })
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.passForm.resetFields()
    },
    clipboardSuccess() {
      this.$message.success('复制成功')
    },
    clipboardError() {
      this.$message.error('复制失败')
    },
    handleImageSelected(file, fileList) {
      const api = new CommonSet()
      this.uploadLoading = true
      api.uploadFile(file, '', '管理员头像').then(response => {
        const { data } = response
        const { fileName, saveName } = data
        const payload = { saveName: saveName, fileName: fileName }
        this.changeAvatar(payload).then(_ => {
          this.uploadLoading = false
          this.$message.success('编辑成功')
        }).catch(_ => {
          this.uploadLoading = false
          this.$message.error('编辑失败')
        })
      }).catch(error => {
        this.uploadLoading = false
        this.$message({
          message: error,
          type: 'error'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">

.form-box {
  &::v-deep .el-input__inner {
    height: 38px;
  }

  .form-input-1 {
    width: 457px;
  }

  .form-input-2 {
    width: 389px;
  }

  .form-input-3 {
    width: 359px;
  }
}

.flex-column {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.nickname {
  margin-bottom: 20px;
}

.copy-btn {
  color: #FF4949;
  width: 61px;
  height: 38px;
  background: #FFE7E7;
  border-radius: 5px;
  border: 0;
  margin-left: 5px;
  padding: 7px;
}

.captcha-btn {
  margin-left: 5px;
  height: 38px;
  font-size: 14px;
  font-weight: 400;
  color: #FFFFFF;
  line-height: 22px;
  padding: 8px 9px;
}

.bottom-btn {
  height: 32px;
  font-size: 14px;
  font-weight: 400;
}

.cover-wrap {
  position: relative;

  .avatar-big-box {
    overflow: hidden;
    margin: 21px auto;
    width: 100px;
    height: 100px;
    border-radius: 50%;

    img {
      width: 100px;
      height: 100px;
      border-radius: 50%;
    }
  }

  .cover-layer {
    @extend .avatar-big-box;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(0, 0, 0, 0.3);
    opacity: 0;
    z-index: 20;
    transition: all ease-in-out 0.2s;

    span {
      color: #FFF;
      font-size: 14px;
    }

    &:hover {
      cursor: pointer;
      opacity: 1;
    }
  }

}
</style>
