<template>
  <section class="AppUserInfo">
    <ai-detail>
      <ai-title slot="title" title="个人中心" isShowBottomBorder/>
      <template #content>
        <ai-card title="个人资料">
          <template #right>
            <span style="color:#999" v-text="'（如需修改基本信息，请联系管理员）'"/>
          </template>
          <template #content>
            <el-row type="flex" justify="space-between">
              <ai-wrapper>
                <ai-info-item label="姓名" :value="user.info.name"/>
                <ai-info-item label="手机号码" :value="user.info.phone"/>
                <ai-info-item label="角色" :value="user.info.roleName"/>
                <ai-info-item label="部门" :value="user.info.departName"/>
                <ai-info-item label="职位" :value="user.info.position"/>
              </ai-wrapper>
              <ai-avatar :value="user.info.avatar" :editable="false"/>
            </el-row>
          </template>
        </ai-card>
        <ai-card title="数据权限">
          <template #right>
            <span style="color:#999" v-text="'（如需修改基本信息，请联系管理员）'"/>
          </template>
          <template #content>
            <ai-wrapper>
              <ai-info-item label="所属地区" :value="user.info.areaList.join('')" isLine/>
              <ai-info-item label="所属党组织" :value="user.info.organizationName" isLine/>
            </ai-wrapper>
          </template>
        </ai-card>
        <ai-card title="密码设置">
          <template #right>
            <el-button type="text" @click="submitForm">保存</el-button>
          </template>
          <template #content>
            <el-form :model="form" ref="ruleForm" :rules="rules" label-width="100px" size="small">
              <el-form-item label="绑定手机：" prop="phone">
                <el-row type="flex" align="middle">
                  <span>{{ user.info.phone }}</span>
                  <el-button type="primary" style="margin-left: 8px" @click="getCode(user.info.phone,true)"
                             :disabled="codeBtn">获取验证码
                    <span v-if="num>0&&codeBtn" style="color:red;">({{ num }}s)</span>
                  </el-button>
                </el-row>
              </el-form-item>
              <el-form-item label="验证码：" prop="code">
                <el-input v-model.trim="form.code" clearable placeholder="请输入短信验证码"/>
                <el-input style="position: fixed; bottom: -9999px"></el-input>
              </el-form-item>
              <el-form-item label="新密码：" prop="pass">
                <el-input type="password" auto-complete="new-password" v-model.trim="form.pass" clearable
                          placeholder="8-16位，需要包含字母和数字及特殊字符(~!@#$%^&*,.?_-)"
                          show-password/>
              </el-form-item>
              <el-form-item label="确认密码：" prop="checkPass">
                <el-input type="password" auto-complete="new-password" placeholder="再次输入密码"
                          v-model.trim="form.checkPass" clearable
                          show-password/>
              </el-form-item>
            </el-form>
          </template>
        </ai-card>
      </template>
    </ai-detail>
  </section>
</template>

<script>
import {mapMutations, mapState} from "vuex";

export default {
  name: "AppUserInfo",
  label: "个人中心",
  props: {
    instance: Function,
  },
  computed: {
    ...mapState(['user']),
    rules() {
      const validatePass = (rule, value, callback) => {
        const reg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*,.?_-])[\da-zA-Z~!@#$%^&*,.?_-]{8,16}$/;
        if (!reg.test(value)) {
          callback(new Error('数字和字母及特殊字符(~!@#$%^&*,.?_-)组合,长度8到16位'));
        } else {
          if (this.form.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      }
      return {
        currentPass: [
          {required: true, message: '请填写当前密码', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请填写验证码', trigger: 'blur'}
        ],
        pass: [
          {validator: validatePass, trigger: 'blur', required: true}
        ],
        checkPass: [
          {
            validator: (r, v, cb) => v ? v != this.form.pass ? cb('两次输入密码不一致') : cb() : cb('请再次输入密码'),
            trigger: 'blur',
            required: true
          }
        ],
      }
    }
  },
  data() {
    return {
      form: {},
      timer: null,
      codeBtn: false,
      num: 60,
    }
  },
  methods: {
    ...mapMutations(['SignOut']),
    getCode(phone, flag) {
      const TEL_REGEXP = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
      if (TEL_REGEXP.test(phone)) {
        this.instance.post(`/admin/user/checkPhone`, null, {
          params: {phone, flag}
        }).then(res => {
          if (res.code == 0) {
            this.$message.success("请查看手机短信!");
            this.timer = setInterval(() => {
              if (this.num > 0) {
                this.codeBtn = true;
                this.num--;
              } else if (this.num == 0) {
                this.codeBtn = false;
                this.num = 60;
                clearInterval(this.timer);

              }
            }, 1000)

          } else {
            this.$message.error("验证码发送失败!");
          }

        })


      } else {
        this.$message.error("手机号格式错误!");
      }

    },
    submitForm() {
      this.$refs.ruleForm.validate(v => {
        if (v) {
          let {pass: newPwd, code} = this.form
          this.instance.post(`/admin/user/update-pwd`, null, {
            params: {
              phone: this.user.info.phone,
              newPwd, code
            }
          }).then(res => {
            if (res?.code == 0) {
              this.$confirm("村微提醒您，更换密码成功！", {
                showCancelButton: false
              }).then(() => this.SignOut()).catch(() => 0)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.AppUserInfo {
  height: 100%;

  :deep( .ai-list__content--wrapper ){
    flex-direction: column;
  }

  :deep( .el-input__inner ){

    -webkit-text-security: disc !important;

  }
}
</style>
