<template>
  <div class="user-avatar-dropdown">
    <Dropdown @on-click="handleClick">
      <!-- <Badge :dot="!!messageUnreadCount">
        <h2>{{ $store.state.admin.account }}</h2>
      </Badge> -->
      <img :src="$store.state.admin.headImg" style="width:50px;height:50px;margin-top:6px;border-radius:50%;object-fit:cover;">
      <Icon :size="20" type="md-arrow-dropdown" style="margin-top: -38px"></Icon>
      <!-- <Icon :size="18" type="md-arrow-dropdown" style="margin-top: -5px"></Icon> -->
      <DropdownMenu slot="list">
        <DropdownItem name="userInfo">个人中心</DropdownItem>
        <DropdownItem name="updatePwd">修改密码</DropdownItem>
        <DropdownItem name="logout">退出登录</DropdownItem>
      </DropdownMenu>
    </Dropdown>
      <Modal
      title="个人信息"
      v-model="userInfoModal"
      :width="500"
      @on-cancel="cancelUserInfo"
      footer-hide
    >
    <div v-if="userInfo">
      <p class="userInfo">
        <span class="user-label">登录账号：</span>
        <span class="user-info">{{userInfo.account}}</span>
      </p>
      <p class="userInfo">
        <span class="user-label" >角色：</span>
        <span class="user-info">{{userInfo.role}}</span>
      </p>
      <p class="userInfo">
        <span class="user-label">我的头像：</span>
        <file-upload
          :width="60"
          :iconSize="26"
          :maxNum="1"
          v-model="userThumbList"
          :defaultList="detailUserThumbList"
          showWatch
        />
        <span @click="handelheadImg" class="setHeadImg">提交头像设置</span>
      </p>
      <p class="userInfo" v-if="!platform">
        <span class="user-label">姓名：</span>
        <span class="user-info">{{userInfo.applyName}}</span>
      </p>
      <p class="userInfo" v-if="!platform">
        <span class="user-label">身份证号：</span>
        <span class="user-info" v-if="detailIdCard">{{detailIdCard}}<Icon  :size="20" type="ios-eye-off" @click.native="idCardInfo"/></span>
        <span class="user-info" v-else>{{userInfo.idCard}}<Icon  :size="20" type="ios-eye-off" @click.native="idCardInfo"/></span>

        <!-- <command icon="ios-eye-off"></command> -->
      </p>
      <p class="userInfo" v-if="!platform">
        <span class="user-label">联系方式：</span>
        <span class="user-info">{{userInfo.applyPhone}}</span>
      </p>
      <p class="userInfo" v-if="!platform">
        <span class="user-label">企业名称：</span>
        <span class="user-info">{{userInfo.enterpriseName}}</span>
      </p>
      <p class="userInfo" v-if="!platform">
        <span class="user-label">统一社会信用码：</span>
        <span class="user-info">{{userInfo.creditCode}}</span>
      </p>
      <p class="userInfo" v-if="!platform">
        <span class="user-label">营业执照：</span>
        <!-- <span class="user-info">{{userInfo.account}}</span> -->
        <img :src="userInfo.businessLicense" class="user-info">
      </p>
    </div>
    </Modal>
    <Modal
      title="修改密码"
      v-model="updatePwdModal"
      :width="400"
      @on-cancel="cancelUpdatePwd"
    >
      <Form
        :model="updatePwdForm"
        ref="updatePwdForm"
        :rules="updatePwdRules"
        :label-width="100"
        style="width: 95%"
        v-show="status==1"
      >
        <FormItem label="原密码：" prop="pwd">
          <Input
            type="password"
            v-model="updatePwdForm.pwd"
            placeholder="请输入原密码"

          />
        </FormItem>
        <FormItem label="新密码：" prop="newPwd">
          <Input
            type="password"
            v-model="updatePwdForm.newPwd"
            :maxlength="16"
            placeholder="长度为6至16个字符"
          />
        </FormItem>
        <FormItem label="确认新密码：" prop="newPwd2">
          <Input
            type="password"
            v-model="updatePwdForm.newPwd2"
            :maxlength="16"
            placeholder="长度为6至16个字符"
          />
        </FormItem>
        <div class="phonePas" @click="changeStatus('phoneUpdatePwdForm')">使用手机验证码修改</div>
      </Form>
      <Form
        :model="phoneUpdatePwdForm"
        ref="phoneUpdatePwdForm"
        :rules="phoneUpdatePwdRules"
        :label-width="100"
        style="width: 95%"
        v-show="status==2"
      >
        <FormItem label="手机号：" prop="phone" class="phone">
          <Input
            type="text"
            v-model="phoneUpdatePwdForm.phone"
            placeholder="请输入手机号"
          >
            <Button slot="append" v-show="loading" @click="verificationCode">发送</Button>
            <Button slot="append" type="primary" v-show="!loading">{{count}}</Button>
          </Input>

        </FormItem>
        <FormItem label="验证码：" prop="code"  v-show="status==2">
          <Input
            type="text"
            v-model="phoneUpdatePwdForm.code"
            placeholder="请输入验证码"
          />
        </FormItem>
        <FormItem label="新密码：" prop="newPwd">
          <Input
            type="password"
            v-model="phoneUpdatePwdForm.newPwd"
            :maxlength="16"
            placeholder="长度为6至16个字符"
          />
        </FormItem>
        <FormItem label="确认新密码：" prop="newPwd2">
          <Input
            type="password"
            v-model="phoneUpdatePwdForm.newPwd2"
            :maxlength="16"
            placeholder="长度为6至16个字符"
          />
        </FormItem>
        <div class="phonePas" @click="changeStatus('updatePwdForm')">使用原密码修改</div>
      </Form>
      <div slot="footer" v-show="status==1">
        <Button
          @click="updatePwd"
          :loading="updatePwdLoading"
          type="primary"
          long
          >确 定</Button
        >
      </div>
      <div slot="footer" v-show="status==2">
        <Button
          @click="updatePwd2"
          :loading="updatePwdLoading"
          type="primary"
          long
          >确 定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import './user.less'
import { mapActions, mapMutations } from 'vuex'
import FileUpload from '_c/file-upload'
import { updatePassword } from '@/api/data'
import { clearAdminInfo, clearTagNavListFromLocalstorage } from '@/libs/util'
export default {
  name: 'User',
  components: {
    FileUpload
  },
  props: {
    userAvatar: {
      type: String,
      default: ''
    },
    messageUnreadCount: {
      type: Number,
      default: 0
    }
  },
  data () {
    const validatePass = (rule, value, callback) => {
      if (value != this.updatePwdForm.newPwd) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    const phoneValidatePass = (rule, value, callback) => {
      if (value != this.phoneUpdatePwdForm.newPwd) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      count: '',
      userInfoModal: false,
      userThumbList: [],
      detailUserThumbList: [],
      detailIdCard: '',
      userInfo: {},
      updatePwdModal: false,
      updatePwdForm: {
        pwd: '',
        newPwd: '',
        newPwd2: '',
        code: '',
        phone: '',
        type: ''
      },
      phoneUpdatePwdForm: {
        pwd: '',
        newPwd: '',
        newPwd2: '',
        code: '',
        phone: '',
        type: ''
      },
      updatePwdRules: {
        pwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPwd: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        newPwd2: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      },
      phoneUpdatePwdRules: {
        newPwd: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        newPwd2: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: phoneValidatePass, trigger: 'blur' }
        ],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      },
      updatePwdLoading: false,
      statu: 1
    }
  },
  computed: {
    status () {
      return this.statu
    },
    platform () {
      return this.$store.state.admin.type == 1 || this.$store.state.admin.type == 4
    }
  },
  methods: {
    ...mapActions(['handleLogOut']),
    ...mapMutations(['setHeadImg']),
    logout () {
      this.api({
        apiName: 'logout',
        success: (res) => {}
      })
      clearAdminInfo()
      clearTagNavListFromLocalstorage()
      this.$router.push({
        name: 'login'
      })
    },
    handleUpdatePwd () {
      this.updatePwdModal = true
    },
    cancelUserInfo () {
      this.userInfo = {}
      this.userThumbList = []
      this.detailIdCard = ''
    },
    handleUserInfo () {
      this.userInfoModal = true
      console.log('plant', 11111)
      this.getUserInfo()
    },
    getUserInfo () {
      this.userThumbList = []
      this.api({
        apiName: 'getMerchantInfo',
        success: (res) => {
          // console.log(res)
          this.userInfo = res.data
          this.userThumbList.push(this.userInfo.headImg)
        }
      })
    },
    handelheadImg () {
      let headImg = this.userThumbList[0]
      this.api({
        apiName: 'repairHeadImg',
        postdata: headImg,
        success: (res) => {
          console.log(res)
          this.setHeadImg(headImg)

          this.getUserInfo()
        }
      })
    },
    idCardInfo () {
      if (!this.detailIdCard) {
        this.api({
          apiName: 'queryIdCard',
          success: (res) => {
            console.log(res)
            this.detailIdCard = res.data
          }
        })
      } else {
        this.detailIdCard = ''
      }
    },
    updatePwd () {
      this.updatePwdForm.type = 1

      this.$refs.updatePwdForm.validate((valid) => {
        console.log('valid', valid)
        if (valid) {
          if (this.updatePwdForm.newPwd.length < 6 || this.updatePwdForm.newPwd.length > 16) {
            return this.$Message.warning('新密码长度输入有误！')
          }
          if (this.updatePwdForm.newPwd2.length < 6 || this.updatePwdForm.newPwd2.length > 16) {
            return this.$Message.warning('新密码长度输入有误！')
          }
          this.updatePwdLoading = true
          this.api({
            apiName: 'repairPwd',
            postdata: this.updatePwdForm,
            success: () => {
              clearAdminInfo()
              this.$Notice.success({ title: '密码修改成功，请重新登录！' })
              this.$router.push({ name: 'login' })
            },
            complete: () => {
              this.updatePwdLoading = false
            }
          })
        } else {
          this.$Message.error('请填写完整信息')
        }
      })
    },
    updatePwd2 () {
      this.phoneUpdatePwdForm.type = 2
      this.$refs.phoneUpdatePwdForm.validate((valid) => {
        if (valid) {
          if (this.phoneUpdatePwdForm.newPwd.length < 6 || this.phoneUpdatePwdForm.newPwd.length > 16) {
            return this.$Message.warning('新密码长度输入有误！')
          }
          if (this.phoneUpdatePwdForm.newPwd2.length < 6 || this.phoneUpdatePwdForm.newPwd2.length > 16) {
            return this.$Message.warning('新密码长度输入有误！')
          }
          this.updatePwdLoading = true
          this.api({
            apiName: 'repairPwd',
            postdata: this.phoneUpdatePwdForm,
            success: () => {
              clearAdminInfo()
              this.$Notice.success({ title: '密码修改成功，请重新登录！' })
              this.$router.push({ name: 'login' })
            },
            complete: () => {
              this.updatePwdLoading = false
            }
          })
        } else {
          this.$Message.error('请填写完整信息')
        }
      })
    },
    cancelUpdatePwd () {
      this.$refs.updatePwdForm.resetFields()
    },
    handleClick (name) {
      switch (name) {
        case 'logout':
          this.logout()
          break
        case 'updatePwd':
          this.handleUpdatePwd()
          break
        case 'userInfo':
          this.handleUserInfo()
          break
      }
    },
    changeStatus (name) {
      if (this.statu == 1) {
        this.$refs[name].resetFields()
        this.statu = 2
      } else if (this.statu == 2) {
        this.$refs[name].resetFields()
        this.statu = 1
      }
    },
    // 发送验证码
    verificationCode () {
      let phone = this.phoneUpdatePwdForm.phone
      let type = 3 // 修改密码
      if (phone == '') {
        return this.$Notice.error({ title: '手机号码不能为空' })
      }
      // console.log('验证码', phone)
      this.api({
        apiName: 'sendAuthSms',
        postdata: {
          phone,
          type
        },
        success: (res) => {
          const TIME_COUNT = 60
          if (!this.timer) {
            this.count = TIME_COUNT
            this.loading = false
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
              } else {
                this.loading = true
                clearInterval(this.timer)
                this.timer = null
              }
            }, 1000)
          }
        }
      })
    },
    requestIsInitPwd () {
      this.api({
        apiName: 'getIsInitPwd',
        success: (res) => {
          if (res.data) {
            this.updatePwdModal = true
            setTimeout(() => {
              this.$Message.warning({ content: '您的密码为初始密码，存在安全隐患，建议尽快修改密码！', duration: 2 })
            }, 500)
          }
        }
      })
    }
  },
  mounted () {
    this.requestIsInitPwd()
  }
}
</script>

<style lang="less" scoped>
.phonePas{
      // width: 30%;
      color: #333333;
      font-size: 11px;
      // text-align: right;
      margin-left: 69%;
      cursor:pointer;

  }
  .phonePas:hover{
        color: #2d8cf0;
      }
  .phone{
    /deep/.ivu-input-group-append{
        // width: 90px;
        // height: 48px;
        background-color: #2d8cf0;
        border-color:#2d8cf0;
        color:#fff
    }
  }
   .userInfo{
    width: 100%;
    display: flex;
    flex: 1;
    .user-label{
      display: block;
      width: 120px;
      margin-bottom: 15px;
      text-align: right;
      font-size: 14px;
      font-weight: 500;
    }
    .user-info{
      display: block;
      width: 200px;
      font-size: 13px;
    }
    .setHeadImg{
      margin-top:45px;
      color:#00FF00;
      cursor:pointer;
    }

  }
</style>
