<style lang="less">
@import "./own-space.less";
</style>
<template>
    <div>
        <Card style="border:none;box-shadow:none;">
            <div class="userInfor-hd" slot="title">
                {{$t('module.ownSpace.personalInfo')}}
            </div>
            <div class="userinfor-mod">
                <div class="person-photo" @click="showPersonPhotoEdit" :style="{'background-image':'url('+avatorPath+')'}" :class="{'clear-border':!!avatorPath}">
                  <div class="person-photo-edit-warp">
                    <Icon type="md-create"></Icon>
                    </div>  
                </div>
                <Form class="userInfor-box" ref="userForm" :model="userForm" :label-width="130" label-position="right" :rules="inforValidate">
                    <FormItem :label="$t('module.ownSpace.account')" prop="name">
                        <div>
                            {{user.userCode}}
                        </div>
                    </FormItem>
                    <FormItem :label="$t('module.ownSpace.userName')" prop="name">
                        <div>
                            {{user.userName}}
                        </div>
                    </FormItem>
                    <FormItem :label="$t('module.ownSpace.password')">
                        <!-- <Button type="text" size="small" @click="showEditPassword">修改密码</Button> -->
                        <Button class="ivu-btn-hr edit-password-btn" size="small" type="primary" icon="md-create" @click="showEditPassword">{{$t('module.ownSpace.editPass')}}</Button>
                    </FormItem>
                </Form>
            </div>
        </Card>
        <Card style="border:none;box-shadow:none;">
            <div class="userInfor-hd" slot="title">
                {{$t('module.ownSpace.preference')}}             
            </div>
            <div class="userinfor-mod" style="margin-top:30px;">
                <Form class="userInfor-box" ref="userForm" :model="userForm" :label-width="130" label-position="right">
                    <FormItem :label="$t('module.ownSpace.language')" prop="name">
                        <div>
                          <Select size="small" v-model="lang"  style="width: 120px;">
                            <Option v-for="item in languageList" :title="item.langDesc" :value="item.langCode" :key="item.langCode">{{item.langDesc}}</Option>
                          </Select>
                        </div>
                    </FormItem>
                    <FormItem :label="$t('module.ownSpace.role')" prop="name">
                        <div>
                          <Select size="small" v-model="roleModel"  style="width: 120px;">
                            <Option v-for="item in roleList" :title="item.roleName" :value="item.roleId" :key="item.roleId">{{item.roleName}}</Option>
                          </Select>
                        </div>
                    </FormItem>
                    <FormItem>
                      <Button class="ivu-btn-hr" :loading="isOrNotAvailable1" style="" @click.native="setLangAndRole()">{{$t('module.ownSpace.setting')}}</Button>
                    </FormItem>
                </Form>
            </div>
            <!--<div class="userinfor-mod" style="text-align: center">
                <div class="ivu-form-item ivu-form-item-required">
                    <label>{{$t('module.ownSpace.language')}}</label>
                    <Select size="small" v-model="lang"  style="width: 200px;">
                        <Option v-for="item in languageList" :title="item.langDesc" :value="item.langCode" :key="item.langCode">{{item.langDesc}}</Option>
                    </Select>
                </div>
                <div class="ivu-form-item ivu-form-item-required">
                    <label>{{$t('module.ownSpace.role')}}</label>
                    <Select size="small" v-model="roleModel"  style="width: 200px;">
                        <Option v-for="item in roleList" :title="item.roleName" :value="item.roleId" :key="item.roleId">{{item.roleName}}</Option>
                    </Select>
                </div>    
                <Button class="ivu-btn-hr" :loading="isOrNotAvailable1" style="" @click.native="setLangAndRole()">{{$t('module.ownSpace.setting')}}</Button>
            </div>-->
            
        </Card>
        <Modal v-model="editPasswordModal" :mask-closable=false :width="500">
            <h3 slot="header">{{$t('module.ownSpace.editPass')}}</h3>
            <Form class="run-modal-style" ref="editPasswordForm" :model="editPasswordForm" :label-width="100" label-position="right" :rules="passwordValidate">
                <FormItem :label="$t('module.ownSpace.originalPass')" prop="oldPWD" :error="oldPassError">
                    <Input v-model="editPasswordForm.oldPWD" type="password" :placeholder="$t('module.ownSpace.enterOriginalPass')"/>
                </FormItem>
                <FormItem :label="$t('module.ownSpace.newPass')" prop="newPWD">
                    <Input v-model="editPasswordForm.newPWD" type="password" :placeholder="$t('module.ownSpace.enterPassHint')"/>
                </FormItem>
                <FormItem :label="$t('module.ownSpace.confirmNewPass')" prop="rePass">
                    <Input v-model="editPasswordForm.rePass" type="password" :placeholder="$t('module.ownSpace.enterAgain')"/>
                </FormItem>
            </Form>
            <div slot="footer" class="run-modal-ftbButton">
                <Button type="primary" :loading="savePassLoading" @click="saveEditPass">{{$t('common.save')}}</Button>
            </div>
        </Modal>
        <Modal v-model="uploadPhotoModal" :mask-closable=false :width="500">
            <h3 slot="header">{{$t('module.ownSpace.editPicture')}}</h3>
            <div id="person-photo-upload" class="person-photo-upload" :style="{'background-image':'url('+photoFrom.pic+')'}" :class="{'clear-border':!!photoFrom.pic}">
              <Icon type="upload" v-if="!photoFrom.pic"></Icon>
            </div>
            <div slot="footer" class="run-modal-ftbButton">
                <Button type="primary" :loading="savePassLoading" @click="uploadPhotoHandle">{{$t('common.save')}}</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { PASSWORD_RULE } from "../password/const.js";

export default {
  data() {
    const validePhone = (rule, value, callback) => {
      var re = /^1[0-9]{10}$/;
      if (!re.test(value)) {
        callback(new Error(this.$t('module.ownSpace.enterCorrectPhone')));
      } else {
        callback();
      }
    };
    const valideRePassword = (rule, value, callback) => {
      if (value !== this.editPasswordForm.newPWD) {
        callback(new Error(this.$t('module.ownSpace.passNotAccordance')));
      } else {
        callback();
      }
    };
    return {
      userForm: {
        name: "",
        cellphone: "",
        company: "",
        department: "",
      },
      photoFrom: {
        pic: "",
        suffix: ""
      },
      roleList: [],
      languageList: [],
      lang: "",
      roleModel: "",
      uploader: undefined,
      uid: "", // 登录用户的userId
      securityCode: "", // 验证码
      phoneHasChanged: false, // 是否编辑了手机
      save_loading: false,
      identifyError: "", // 验证码错误
      editPasswordModal: false, // 修改密码模态框显示
      savePassLoading: false,
      oldPassError: "",
      identifyCodeRight: false, // 验证码是否正确
      hasGetIdentifyCode: false, // 是否点了获取验证码
      canGetIdentifyCode: false, // 是否可点获取验证码
      checkIdentifyCodeLoading: false,
      uploadPhotoModal: false,
      inforValidate: {
        name: [{ required: true, message: this.$t('module.ownSpace.enterName'), trigger: "blur" }],
        cellphone: [
          { required: true, message: this.$t('module.ownSpace.enterPhone') },
          { validator: validePhone }
        ]
      },
      editPasswordForm: {
        oldPWD: "",
        newPWD: "",
        rePass: ""
      },
      passwordValidate: {
        oldPWD: [{ required: true, message: this.$t('module.ownSpace.enterOriginalPass'), trigger: "blur" }],
        newPWD: [
          { required: true, message: this.$t('module.ownSpace.enterNewPass'), trigger: "blur" },
          {
            message: this.$t('module.ownSpace.passContain'),
            trigger: "blur",
            pattern: PASSWORD_RULE
          }
        ],
        rePass: [
          { required: true, message: this.$t('module.ownSpace.enterAgain'), trigger: "blur" },
          { validator: valideRePassword, trigger: "blur" }
        ]
      },
      inputCodeVisible: false, // 显示填写验证码box
      initPhone: "",
      gettingIdentifyCodeBtnContent: this.$t('module.ownSpace.obtainVc')// “获取验证码”按钮的文字
    };
  },
  computed: {
    user() {
      return this.$store.state.userInfo;
    },
    avatorPath() {
      return this.$store.state.avatar;
    }
  },
  created: function(){
    $store.dispatch("GetRoles").then(res => {
            // 加载用户角色列表
            for (const key in res.userRoleList) {
                if (res.userRoleList.hasOwnProperty(key)) {
                const value = res.userRoleList[key];
                console.log( this.roleList);
                this.roleList.push({"roleId": key, "roleName": value});
                }
            }
        });
      $store.dispatch("GetCurrentLangAndRole", "").then(response => {
          if(response.dataResult){
            this.lang = response.dataResult['SYS.SETTING.LOCALE'];
            this.roleModel = response.dataResult["SYS.SETTING.ROLE"];
          }
         
      });
       $store.dispatch("QueryLanguages", "").then(response => {
        //加载语言列表
        for(const i in response){
                this.languageList.push({"langDesc": response[i].langDesc, "langCode": response[i].langCode });
            }
        })
  },
  mounted() {
    this.init();
  },
  methods: {
    previewImage(file, callback) {
      if (!file || !/image\//.test(file.type)) return; //确保文件是图片
      if (file.type == "image/gif") {
        //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
        var fr = new mOxie.FileReader();
        fr.onload = function() {
          callback(fr.result);
          fr.destroy();
          fr = null;
        };
        fr.readAsDataURL(file.getSource());
      } else {
        var preloader = new mOxie.Image();
        preloader.onload = function() {
          // preloader.downsize(300, 300);//先压缩一下要预览的图片,宽300，高300
          var imgsrc =
            preloader.type == "image/jpeg"
              ? preloader.getAsDataURL("image/jpeg", 80)
              : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
          callback && callback(imgsrc); //callback传入的参数为预览图片的url
          preloader.destroy();
          preloader = null;
        };
        preloader.load(file.getSource());
      }
    },
    showPersonPhotoEdit() {
      this.uploadPhotoModal = true;
      this.$nextTick(() => {
        this.upLoadInit();
      });
    },
    upLoadInit() {
      if (!!this.uploader) {
        this.uploader.destroy();
      }
      this.uploader = new plupload.Uploader({
        //实例化一个plupload上传对象
        browse_button: "person-photo-upload",
        url: `mams-web-admin/sys/account/avatar/upload`,
        headers: {
          crctoken: sessionStorage.crctoken
        },
        // flash_swf_url: 'static/Moxie.swf',
        // silverlight_xap_url: 'static/Moxie.xap',
        filters: {
          mime_types: [
            //只允许上传图片文件
            { title: this.$t('module.ownSpace.picFile'), extensions: "jpg,gif,png" }
          ],
          max_file_size: "3000kb"
        }
      });
      this.uploader.init();
      this.uploader.bind("FilesAdded", (uploader, files) => {
        for (var i = 0, len = files.length; i < len; i++) {
          let file_name = files[i].name.split("."); //文件名
          let suffix = file_name[file_name.length - 1];
          this.previewImage(files[i], imgsrc => {
            this.photoFrom.pic = imgsrc;
            this.photoFrom.suffix = suffix;
          });
        }
      });
      this.uploader.bind("Error", (uploader, errObject) => {});
    },
    uploadPhotoHandle() {
      if (!this.photoFrom.suffix) {
        return;
      }
      $store
        .dispatch("UpdatePersonPhoto", {
          pic: this.photoFrom.pic.split(",")[1],
          suffix: this.photoFrom.suffix
        })
        .then(res => {
          if (!res.success) {
            this.$Message.warning({
              content: res.msg,
              duration: 2
            });
            return;
          }
          //$store.dispatch("GetAvatar");
          this.photoFrom.suffix = null;
          this.uploadPhotoModal = false;
        });
    },
    getIdentifyCode() {
      this.hasGetIdentifyCode = true;
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          this.canGetIdentifyCode = true;
          let timeLast = 60;
          let timer = setInterval(() => {
            if (timeLast >= 0) {
              this.gettingIdentifyCodeBtnContent = timeLast + this.$t('module.ownSpace.tryAgain');
              timeLast -= 1;
            } else {
              clearInterval(timer);
              this.gettingIdentifyCodeBtnContent = this.$t('module.ownSpace.obtainVc');
              this.canGetIdentifyCode = false;
            }
          }, 1000);
          this.inputCodeVisible = true;
          // you can write ajax request here
        }
      });
    },
    showEditPassword() {
      this.editPasswordForm = {
        oldPWD: "",
        newPWD: "",
        rePass: ""
      };
      this.editPasswordModal = true;
    },
    cancelEditUserInfor() {
      this.$store.commit("removeTag", "ownspace_index");
      let lastPageName = "";
      if (this.$store.state.pageOpenedList.length > 1) {
        lastPageName = this.$store.state.pageOpenedList[1].name;
      } else {
        lastPageName = this.$store.state.pageOpenedList[0].name;
      }
      this.$router.push({
        name: lastPageName
      });
    },
    saveEdit() {
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          if (
            this.phoneHasChanged &&
            this.userForm.cellphone !== this.initPhone
          ) {
            // 手机号码修改过了而且修改之后的手机号和原来的不一样
            if (this.hasGetIdentifyCode) {
              // 判断是否点了获取验证码
              if (this.identifyCodeRight) {
                // 判断验证码是否正确
                this.saveInfoAjax();
              } else {
                this.$Message.error(this.$t('module.ownSpace.enterPassAgain'));
              }
            } else {
              this.$Message.warning(this.$t('module.ownSpace.clickGainVc'));
            }
          } else {
            this.saveInfoAjax();
          }
        }
      });
    },
    cancelEditPass() {
      this.editPasswordModal = false;
    },
    saveEditPass() {
      this.$refs["editPasswordForm"].validate(valid => {
        if (valid) {
          this.savePassLoading = true;
          $store
            .dispatch("UpdatePassword", {
              oldPWD: this.editPasswordForm.oldPWD,
              newPWD: this.editPasswordForm.newPWD
            })
            .then(res => {
              this.savePassLoading = false;
              if (!res.success) {
                this.$Message.warning({
                  content: res.msg,
                  duration: 2
                });
            
                return;
              }
               this.$Message.success(
                  {
                    content:this.$t('module.ownSpace.editSuccess'),
                  duration: 2
                  });
              this.editPasswordModal = false;
            });
        }
      });
    },
    init() {
      this.userForm.name = "Lison";
      this.userForm.cellphone = "17712345678";
      this.initPhone = "17712345678";
      this.userForm.company = "TalkingData";
      this.userForm.department = this.$t('module.ownSpace.visualDepart');
    },
    cancelInputCodeBox() {
      this.inputCodeVisible = false;
      this.userForm.cellphone = this.initPhone;
    },
    submitCode() {
      let vm = this;
      vm.checkIdentifyCodeLoading = true;
      if (this.securityCode.length === 0) {
        this.$Message.error(this.$t('module.ownSpace.enterMessageVc'));
      } else {
        setTimeout(() => {
          this.$Message.success(this.$t('module.ownSpace.correctVc'));
          this.inputCodeVisible = false;
          this.checkIdentifyCodeLoading = false;
        }, 1000);
      }
    },
    hasChangePhone() {
      this.phoneHasChanged = true;
      this.hasGetIdentifyCode = false;
      this.identifyCodeRight = false;
    },
    saveInfoAjax() {
      this.save_loading = true;
      setTimeout(() => {
        this.$Message.success(this.$t('module.ownSpace.saveSuccess'));
        this.save_loading = false;
      }, 1000);
    },
    setLangAndRole(){
          $store.dispatch("SetLangAndRole", {roleId: this.roleModel, locale: this.lang}).then(response => {
              if(response.statusCode == "0"){
                  this.$Message.success({
                      content:this.$t('module.ownSpace.preferenceSetSuccess'),
                      duration: 3
                  });
              }else{
                  this.$Message.warning({
                      content: response.msg,
                      duration: 3
                  })
              }
          })
      }  
  }
};
</script>
