<template>
  <div class="personSetting">
    <el-button type="text" class="passWard-btn"  @click="openPassword"><svg-icon icon-class="passWard-edit" style="margin-right: 10px;font-size: 22px;"></svg-icon>修改密码</el-button>
    <div class="avatar" @click="openAvatar">
      <el-avatar :src="avatar" :size="116" alt=""></el-avatar>
      <!-- <span>{{userInfo.name}}</span> -->
      <!-- <el-button type="primary" @click="openAvatar">修改头像</el-button> -->
    </div>
    <!-- <el-form :model="form" label-position="right" label-width="80px"> -->
      <div class="informationItem">
        <div class="information-header">
          <h4>基础信息</h4>
        </div>
        <ul class="base-info">
          <li><label class="label" style="width:32px">姓名</label><span class="info-text">{{form.name}}</span></li>
          <li><label class="label" style="width:32px">性别</label><span class="info-text">{{form.gender == 1?'男':'女'}}</span></li>
          <li><label class="label">所属部门</label><span class="info-text">{{form.departName}}</span></li>
        </ul>
        <ul class="base-info">
          <li><label class="label" style="width:32px">生日</label><span class="info-text">{{form.birthday}}</span></li>
          <li><label class="label">手机号</label><span class="info-text">{{form.account.mobile}}</span></li>
          <li><label class="label">邮箱</label><span class="info-text">{{form.account.email}}</span></li>
        </ul>
      </div>
      <div class="informationItem">
        <div class="information-header">
          <h4>个人签名</h4>
        </div>
        <div class="base-info">
          <label class="label" style="min-width:70px;text-align: left;">我的签名</label>
          <p class="info-text" style="width:540px" v-show="!signData.isEdit">{{form.sign}}</p>
          <el-input v-show="signData.isEdit" style="width:40%;height:40px" type="textarea" maxlength="20" v-model="signData.sign" :rows="1"></el-input>
          <el-button v-show="signData.isEdit" style="margin-left:110px" @click="signData.isEdit = false">取消</el-button>
          <el-button v-show="signData.isEdit" type="primary" @click="saveSign()">保存</el-button>
          <el-button v-show="!signData.isEdit" style="margin-left:110px" type="primary" @click="signData.isEdit = true">编辑</el-button>
        </div>
      </div>
      <div class="informationItem">
        <div class="information-header">
          <h4>动态可见范围</h4>
        </div>
        <div class="dynamic-range">
           <el-radio v-model="form.dynamic" :label="1">全部动态</el-radio>
           <el-radio v-model="form.dynamic" :label="2">最近半年动态</el-radio>
           <el-radio v-model="form.dynamic" :label="3">最近三个月动态</el-radio>
           <!-- <el-button v-show="dynamicData.isEdit" style="margin-left:110px" @click="dynamicData.isEdit = false">取消</el-button> -->
           <el-button style="margin-left:110px" type="primary" @click="saveDynamic()">保存</el-button>
           <!-- <el-button v-show="!dynamicData.isEdit" style="margin-left:110px" type="primary" @click="dynamicData.isEdit = true">编辑</el-button> -->
        </div>
      </div>
         <h4>兴趣爱好 <svg-icon v-show="!interestIsEdit" type="primary" @click="interestIsEdit = true" icon-class="passWard-edit" style="margin-left: 10px;font-size: 18px;"></svg-icon></h4>
         <div class="interest" v-show="!interestIsEdit">
            <ul class="interest-ul">
              <li class="interest-li" v-for="int in interestList" :key="int.id">{{int.name}}</li>
            </ul>
         </div>
         <div v-show="interestIsEdit">
          <div class="interest" v-for="(sys,index) in sysTypeListMap" :key="sys.id">
           <span class="interest-title">{{sys.name}}</span>
           <div style="width:100%">
            <el-checkbox-group v-model="checkboxGroup" v-if="sys.children.length > 0">
              <el-checkbox size="medium" border v-for="ch in sys.children" :label="ch.id" :key="ch.id">{{ch.name}}</el-checkbox>
            </el-checkbox-group>
           </div>
          </div>
         </div>

         <div style="text-align: center;margin-top:56px">
          <el-button v-show="interestIsEdit" @click="interestIsEdit = false">取消</el-button>
          <el-button v-show="interestIsEdit" type="primary" @click="saveHobby()">保存</el-button>
          <!-- 
          <el-button v-show="!interestIsEdit" type="primary" @click="interestIsEdit = true">编辑</el-button>
          -->
         </div>
      <!-- </div> -->
    <!-- </el-form> -->
    <el-dialog
      title="上传头像"
      :visible.sync="dialogVisibleAvatar"
      :close-on-click-modal="false"
      center
      width="30%"
      custom-class="g-dialog">
      <div>
        <p>图片尺寸建议在：宽100px,高100px</p>
        <p>图片大小不超过：500KB</p>
        <p>图片类型：.jpg.gif.png.jpeg.bmp</p>
        <imageUpload width="240px" height="240px" :value="avatarUrl" fileSizeLimit="500KB" :compress="0.7" :compressAccurately="20" @success="handleUploadSuccess" @remove="removeHandle"></imageUpload>
        <div class="dialog-btn">
          <el-button type="primary" @click="updateAvatar">确定</el-button>
          <el-button @click="dialogVisibleAvatar=false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="设置密码"
      :visible.sync="dialogVisiblePassword"
      :close-on-click-modal="false"
      center
      width="30%"
      custom-class="g-dialog">
      <el-form ref="form" :model="passwordForm" :rules="rules" status-icon label-position="right" label-width="80px">
        <p>规则：密码由8-16位大写字母，小写字母，数字或符号</p>
        <p>任意三种的组合密码，不能单独使用字母、数字或符号</p>
        <el-form-item style="margin-top: 22px" label="旧密码">
          <el-input show-password type="password" placeholder="请输入旧密码" v-model="passwordForm.oldPass"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass">
          <el-input show-password type="password" placeholder="请输入新密码" v-model="passwordForm.newPass"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPass">
          <el-input show-password type="password" placeholder="请再次确认新密码" v-model="passwordForm.confirmPass"></el-input>
        </el-form-item>

        <div class="dialog-btn">
          <el-button type="primary" @click="updatePassword">提交</el-button>
          <el-button @click="dialogVisiblePassword=false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters, mapActions } from 'vuex';
  import userApi from "@/api/system/user";
  import accountApi from "@/api/account";
  import apiPassword from '@/api/boe/login.js'
  import imageUpload from '@/components/ImageUpload/index.vue';
  import apiUserhobby from "@/api/phase2/userhobby.js"
   const cityOptions = ['上海', '北京', '广州', '深圳'];
  export default{
    components:{imageUpload},
    data(){
      var testPassword =/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/;
      var validatePass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入旧密码'));
        } else if(!testPassword.test(value)){
          callback(new Error('请输入由8-16位大写字母、小写字母、数字或符号任意三种的组合密码'));
        }else{
          if (this.passwordForm.newPass !== '') {
            this.$refs.form.validateField('newPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入新密码'));
        } else if(!testPassword.test(value)){
          callback(new Error('请输入由8-16位大写字母、小写字母、数字或符号任意三种的组合密码'));
        } else {
          if (this.passwordForm.confirmPass !== '') {
            this.$refs.form.validateField('confirmPass');
          }
          callback();
        }
      };
      var validatePass3 = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请再次输入新密码'));
        } else if(!testPassword.test(value)){
          callback(new Error('请输入由8-16位大写字母、小写字母、数字或符号任意三种的组合密码'));
        } else if(value!=this.passwordForm.newPass){
          callback(new Error('新密码和再次确认密码不一致!'));
        }else{
          callback();
        }
      };
      return {
        signData:{
          sign:'',
          isEdit:false
        },
        cities: cityOptions,
        checkboxGroup: [],
        radio: '1',
        form:{
          account:{}
        },
        dialogVisibleAvatar:false,
        dialogVisiblePassword:false,
        avatarUrl:'',
        passwordForm:{},
        rules:{
          newPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
          confirmPass: [
            { validator: validatePass3, trigger: 'blur' }
          ]
        },
        sysTypeListMap:[],
        interestList:[],//已有兴趣爱好列表
        interestIsEdit:false,
      }
    },
    computed: {

      ...mapGetters(['userInfo','sysTypeMap']),
      avatar(){
        if(this.userInfo.avatar){
          if(this.userInfo.avatar.indexOf('http')==-1){
            return this.baseUrl+this.userInfo.avatar
          }else{
            return this.userInfo.avatar
          }
        }else{
          if(this.userInfo.sex==2){
            return this.webBaseUrl + '/images/Avatarwoman.png'
          }else{
            return this.webBaseUrl + '/images/Avatarman.png'
          }
        }

      }
    },
    watch:{
      dialogVisiblePassword(val) {
        if(!val) {
           this.passwordForm={};
        }
      },

      // 监听"编辑按钮"事件变化
      interestIsEdit(){
        this.load();
        this.getInfo();
      }


    },
    mounted(){
      if(this.userInfo.avatar){
        this.avatarUrl = this.avatar;
      }
      this.load();
      this.getInfo();
      this.getSysTypeTree().then(rs => {
        this.sysTypeListMap = rs;
      });
    },
    methods:{
      checkAndSendFinish(){
        //验证并发送完成事件
        if(this.userInfo.avatar && this.form.sign && this.form.sign!='' && this.interestList.length>1){
           let event = {
             key: "FinishSelf",//后台的事件key  发布文章且审核通过
             title: "完善个人信息奖励",//事件的标题
             parameters:"",//用户自定义参数 name:value,name:value
             content: "需完成头像，个性签名，学习偏好设置",//事件的内容
             source:'page',
             objId: this.userInfo.aid,//关联的id
             objType: "98",//关联的类型
             objInfo: "个人信息",
             aid: this.userInfo.aid, //当前登录人的id
             aname: this.userInfo.name,//当前人的姓名
             status: 1 //状态，直接写1
           }
           this.$store.dispatch("userTrigger", event);
        }else{
          // console.log('还未达到奖励');
          // console.log('this.userInfo.avatar',this.userInfo.avatar);
          // console.log('this.form.sign',this.form.sign);
          // console.log('this.interestList',this.interestList);
        }
      },
      saveDynamic() {
        userApi.updateDynamic(this.form.dynamic).then(res=>{
           if(res.status == 200) {
            this.$message.success('修改动态可见范围成功');
           }
        })
      },
      saveSign() {
        userApi.updateSign(this.signData.sign).then(res=>{
           if(res.status == 200){
              this.$message.success('我的签名修改成功');
              this.form.sign = this.signData.sign;
              this.signData.isEdit = false;
              this.checkAndSendFinish();
           } else {
            this.$message.error('保存失败：'+res.message);
           }
        })
      },
      getInfo() { //获取用户兴趣关联的id
        this.checkboxGroup = [];
        apiUserhobby.info(this.userInfo.aid).then(res=>{
          if(res.status == 200) {
            res.result.forEach(item=>{
              this.checkboxGroup.push(item.refId);
              item.name = this.sysTypeName(item.refId)
            })
            this.interestList = res.result;
          }
        })
      },
      sysTypeName(code){
        if(code==''){return '';}
        return this.sysTypeMap.get(code);
      },

      // 更新用户与偏好数据
      saveHobby(){
        let data = []
        if(this.checkboxGroup.length  <3 && this.checkboxGroup.length>=1) {
          this.$message.error('至少选择三个兴趣偏好！')
          return;
        }
        this.checkboxGroup.forEach(item=>{
          data.push({
            type:1,
            refId:item
          })
        })
        apiUserhobby.update(data).then(res=>{
          if(res.status == 200) {
            this.interestIsEdit = false;
            this.getInfo();
            this.checkAndSendFinish();
            this.$message.success('更改成功！')
          } else {
            this.$message.error("更改失败！")
          }
        })
      },
      ...mapActions({
            getResOwnerTree: 'resOwner/getResOwnerTree',
            loadResOwners: 'resOwner/loadResOwners',
            getSysTypeTree: 'sysType/getSysTypeTree',
            loadSysTypes: 'sysType/loadSysTypes'
        }),
      load(){
        userApi.detail(this.userInfo.aid).then(res=>{
          if(res.status==200){
            this.form=res.result;
            this.signData.sign = res.result.sign;
            if(res.result.dynamic == '') {
              this.form.dynamic = 0;
            }
          }
        });
      },
      openAvatar(){
        this.dialogVisibleAvatar=true
      },
      openPassword(){
        this.dialogVisiblePassword=true
      },
      handleUploadSuccess(res){
        this.form.account.avatar = res.result.filePath;
        this.avatarUrl= res.result.httpPath;
      },
      removeHandle(){
         this.avatarUrl='';
         this.form.account.avatar = '';
      },
      updateAvatar(){
        // if(!this.avatarUrl){
        //   return this.$message.error('请上传图片')
        // }
        accountApi.updateAvatar({id:this.form.id,avatar:this.form.account.avatar}).then(res=>{
          if(res.status==200){
            this.$store.dispatch('InitData');
            this.$message.success("保存图片成功")
            this.dialogVisibleAvatar=false;
            this.checkAndSendFinish();
          }else{
            this.$message.error("保存图片失败")
          }
        })
      },
      updatePassword(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            apiPassword.modifyPassword({oldPassword:this.passwordForm.oldPass,newPassword:this.passwordForm.newPass,confirmPassword:this.passwordForm.confirmPass}).then(res=>{
              if(res.status==200){
                this.$message.success('修改密码成功')
                this.dialogVisiblePassword = false;
              }else{
                this.$message.error(res.message);
              }
            })
          } else {
            return false;
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>

::v-deep .el-checkbox-button--medium .el-checkbox-button__inner{
  // padding: 10px 40px !important;
  width: 146px;
  height: 44px;
  line-height: 24px;
}
::v-deep .el-checkbox-button.is-checked .el-checkbox-button__inner {
  background-color: rgba(0,0,0,0) !important;
  color: #387DF8 !important;
}
::v-deep .el-checkbox-button.is-focus .el-checkbox-button__inner{
  // border-color:#fff !important;
  outline: none;
}
// ::v-deep .el-checkbox-button.is-focus{
//   border-color:none !important;
//   outline: none !important;
// }
::v-deep .el-checkbox-button:first-child .el-checkbox-button__inner{
  border-left:none;
}
.el-checkbox-button, .el-checkbox-button__inner {
   margin-right: 40px;
   background: #FFFFFF;
   border-radius: 4px;
   box-shadow: none;
   border-left: 1px solid rgba(151,151,151,0.3);
   box-shadow: 1px 0 0 0 #fff;
}
.interest{
  display: flex;
  padding-left: 20px;
  .interest-ul{
    display: flex;
    flex-wrap: wrap;
    .interest-li{
      width: 146px;
      height: 44px;
      text-align: center;
      line-height: 44px;
      font-size: 14px;
      color: #333333;
      border: 1px solid rgba($color: #979797, $alpha: 0.3);
      border-radius: 4px;
      margin-right: 44px;
      margin-bottom: 22px;
    }
  }

  .interest-title{
    width: 70px;
    margin-right: 17px;
    color: #333333;
    font-size: 14px;
    margin-bottom: 20px;
  }
  ::v-deep .el-checkbox__input{
    display: none;
  }
  ::v-deep .el-checkbox{
     width: 146px;
     height: 44px;
     margin-bottom: 22px;
     text-align: center;
     line-height: 26px;
     margin-left: 0px;
     margin-right: 48px;
  }
  ::v-deep .el-checkbox.is-bordered+.el-checkbox.is-bordered{
    margin-left: 0px;
  }

}
 .dynamic-range{
   span{
     font-size: 14px;
     color: #333333;
     margin-right: 10px;
   }
 }
  .depart{
    font-size: 14px;
    color: #999999;
  }
 ::v-deep .el-radio-button:first-child .el-radio-button__inner {
      border: none !important;
}
  .personSetting{
    background-color: #fff;
    box-sizing: border-box;
    // padding: 30px 0px 0px 247px;
    padding: 30px 0 10% 20%;
    // margin: 0 auto;
    position: relative;
    .avatar{
      position: absolute;
      left: 5%;
      top:56px;
    }
    .passWard-btn{
      position: absolute;
      font-size: 16px;
      top:45px;
      right:45px;
    }

    ::v-deep .el-radio-button__inner{
      background: #F4F4F4 !important;
      border-radius: 4px !important;
    }
    ::v-deep .el-radio-button__orig-radio:checked+.el-radio-button__inner{
      color: #FFF;
      background-color: #387DF7 !important;
      border-color: #387DF7;
      box-shadow: -1px 0 0 0 #387DF7;
    }
    .informationItem{
      min-width: 600px;
      padding-right: 10%;
      margin-bottom: 82px;
      .information-header{
        // display: flex;
        // justify-content: space-between;
        // align-items: center;
        // padding: 10px 0;
        margin-bottom: 35px;
      }
      .base-info{
        margin: 0;
        display: flex;
        margin-bottom: 46px;
        text-align: left;
        // flex-direction: row;
        // flex-wrap: nowrap;
        li{
          width: 260px;
          text-align: left;
          // flex-grow: 2;
        }
        .label{
          display: inline-block;
          font-size: 16px;
          font-weight: 400;
          color: #333333;
          width: 64px;
          margin-right: 20px;
          text-align: left;
        }
        .info-text{
          font-size: 14px;
          color: #999999;
          text-align: left;
        }
      }
    }
    ::v-deep .el-dialog{
      .el-dialog__body{
        display: flex;
        justify-content: center;
        align-items: center;
        p{
          line-height: 24px;
        }
        .component-upload-image{
          margin: 20px 0;
        }
        .dialog-btn{
          display: flex;
          justify-content: space-evenly;
          align-items: center;
          .el-button{
            width: 102px;
            height: 36px;
          }
        }
        .el-form-item{
          margin-bottom: 36px;
        }
      }
    }
  }
</style>
