<template>
  <Navbar :title="$t('lang.UserParameters.personalSettings')" :is-go-back="true" />
  <div style="margin-top: 2rem;" class="container">
    <div>
      <!-- <div
      class="row m-row"
      style="margin-top:10px"
    >
      <div class="col-md-12">
        <h4 class="title page-header">用户角色<span class="label label-warning title-addon">{{ loginInfo.roleName }}</span></h4>
      </div>
    </div> -->

      <div
        class="row m-row"
      >
        <div class="col-md-12">
          <h4 class="title page-header">{{ $t("lang.UserParameters.userAvatar") }}</h4>
          <div>
            <ImageUpload
              v-model="loginUserDto.imageName"
              :class-name="'com.leanwo.prodog.base.model.User'"
              @update:model-value="uploadUserImage"
            />
          </div>
        </div>
      </div>

      <div class="row m-row">
        <div class="col-md-12">
          <h4 class="title page-header">{{ $t("lang.UserParameters.userPasswordModification") }}</h4>
          <div>
            <div class="form-group">
              <label class="control-label" for="oldPassword">{{ $t("lang.UserParameters.originalPassword") }}:</label>
              <input
                id="oldPassword"
                v-model="oldPassword"
                autocomplete="off"
                class="form-control"
                type="password"
                :placeholder="$t('lang.UserParameters.inputOriginalPassword')"
              />
            </div>

            <div class="form-group" :class="{'has-error has-feedback': (newPasswordCheckResult.length > 0)}">
              <label class="control-label" for="newPassword">{{ $t("lang.UserParameters.newPassword") }}:</label>
              <input
                id="newPassword"
                v-model="newPassword"
                autocomplete="off"
                class="form-control"
                type="password"
                :placeholder="$t('lang.UserParameters.inputNewPassword')"
                @input="handlerPasswordStrength1"
              />
              <span v-if="newPasswordCheckResult.length > 0" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true" />
              <span v-if="newPasswordCheckResult.length > 0" class="control-label" for="newPassword">{{ newPasswordCheckResult }}</span>
            </div>

            <div class="form-group" :class="{'has-error has-feedback': (newPassword2CheckResult.length > 0)}">
              <label class="control-label" for="newPassword2">{{ $t("lang.UserParameters.confirmPassword") }}:</label>
              <input
                id="newPassword2"
                v-model="newPassword2"
                autocomplete="off"
                class="form-control"
                type="password"
                :placeholder="$t('lang.UserParameters.againInputNewPassword')"
                @input="handlerPasswordStrength2"
              />
              <span v-if="newPassword2CheckResult.length > 0" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true" />
              <span v-if="newPassword2CheckResult.length > 0" class="control-label" for="newPassword">{{ newPassword2CheckResult }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- <div
      v-if="isShowUserParamter"
      class="row m-row"
    >
      <div class="col-md-12">
        <h4 class="title page-header">用户参数设置</h4>
        <div v-if="isShowUserParamter">
          <div
            v-for="item in parameterValues"
            :key="item.id"
            class="form-group"
          >
            <label>{{ item.displayName }}</label>
            <input
              v-if="item.displayType == 'CheckBoxEditor'"
              v-model="item.value"
              autocomplete="off"
              type="checkbox"
            />
            <input
              v-else
              v-model="item.value"
              autocomplete="off"
              type="text"
              class="form-control"
            />
          </div>
        </div>
      </div>
    </div> -->

      <div class="row m-row">
        <div class="col-md-12">
          <button
            type="button"
            class="btn btn-success"
            @click="saveUserParamter"
          >
            {{ $t("lang.UserParameters.save") }}
          </button>
          <button
            type="button"
            class="btn btn-danger"
            @click="clear"
          >
            {{ $t("lang.UserParameters.clearUserSettings") }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';

import UserStorageResource from '../api/base/UserStorageResource.js';
import UserResourceV2 from '../api/base/UserResourceV2.js';
import UserResource from '../api/base/UserResource.js';
import AuthSettingResource from '../api/commom/AuthSettingResource.js';
import ImageUpload from '../widget/image-upload.vue';
import { requestFailed, requestSuccess} from '../common/request-result.js';
import { notificationSuccess} from '../common/notification.js';
import PasswordService from '../common/PasswordService.js';
import { Notify, Uuid } from 'pc-component-v3';

export default {
  components: {
    ImageUpload,
  },
  data: function () {
    return {
      oldPassword: '',
      newPassword: '',
      newPasswordCheckResult: '',
      newPassword2: '',
      newPassword2CheckResult: '',
      parameterValues: [],
      isShowUserParamter: false,
      loginInfo: '',
      loginUserDto: '',
    };
  },
  mounted: function () {
    // this.getParameterValue();
    this.getLoginInfo();
  },
  methods: {
    /**
         * 获取用户参数
         */
    getParameterValue: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('userParamResource/query'),
        dataType: 'json',
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.showParameterValue(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(
            XMLHttpRequest,
            textStatus,
            errorThrown,
          );
        },
      });
    },

    /**
         * 渲染用户参数
         */
    showParameterValue: function (data) {
      var _self = this;
      // 清空数据
      _self.parameterValues.splice(0, _self.parameterValues.length);
      // 修复用户头像不显示的BUG
      _self.isShowUserParamter = true;
      if (data == undefined || data.length == 0) {
        return;
      }

      for (var i = 0, len = data.length; i < len; i++) {
        _self.parameterValues.push(data[i]);
        if (data[i].displayType == 'CheckBoxEditor') {
          if (data[i].value == 'true') {
            data[i].value = true;
          } else {
            data[i].value = false;
          }
        }
      }
    },
    /**
         * 保存用户参数
         */
    saveUserParamter: function () {
      var _self = this;
      var id;
      var value;
      var userParams = [];
      for (var i = 0, len = _self.parameterValues.length; i < len; i++) {
        id = _self.parameterValues[i].id;
        if (_self.parameterValues[i].displayType == 'CheckBoxEditor') {
          value =
                        _self.parameterValues[i].value == true
                          ? 'true'
                          : 'false';
        } else {
          value = _self.parameterValues[i].value;
        }
        var aa = {
          id: id,
          value: value,
        };
        userParams.push(aa);
      }
      console.log(userParams);
      $.ajax({
        url: Common.getApiURL('userParamResource/update'),
        dataType: 'json',
        type: 'post',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(userParams),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.getParameterValue();
        },
      });

      // 修改密码
      var oldPassword = _self.oldPassword;
      var newPassword = _self.newPassword;
      var newPassword2 = _self.newPassword2;

      if (oldPassword != null && oldPassword != '') {
        if (newPassword == '') {
          Notify.error('错误', '新密码不能为空', false);
          return;
        }

        if (newPassword.indexOf(' ') > -1) {
          Notify.error('错误', '新密码中不允许包含空格字符', false);
          return;
        }

        if (newPassword != newPassword2) {
          Notify.error('错误',
            '确认密码与新密码不一致，请核对后再提交',
            false,
          );
          return;
        }

        if (oldPassword == newPassword) {
          Notify.error('错误', '新密码与原密码一致', false);
          return;
        }

        let message = PasswordService.handlerPasswordStrength(this.$i18n.locale,newPassword);
        if(message != null && message.length > 0){
          Notify.error('警告', message, false);
          return;
        }

        $.ajax({
          url: Common.getApiURL('userResource/updateUserPassword'),
          async: false,
          type: 'post',
          dataType: 'text',
          data: {
            oldPassword: oldPassword,
            newPassword: newPassword,
            newPassword2: newPassword2,
          },
          beforeSend: function (request) {
            Common.addTokenToRequest(request);
          },
          success: function (data) {
            if (data != null && data != '') {
              Notify.success('操作成功', data, 1500);
              _self.oldPassword = '';
              _self.newPassword = '';
              _self.newPassword2 = '';
              _self.getParameterValue();
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {
            Common.processException(
              XMLHttpRequest,
              textStatus,
              errorThrown,
            );
          },
        });
      } else if (
        (newPassword == null && newPassword == '') ||
                (newPassword2 == null && newPassword2 == '')
      ) {
        Notify.error('错误', '请填写完整再提交', false);
        return;
      }

     
    },

    /**
     * 上传用户的图片
     */
    uploadUserImage: function(){
      UserResource.updateImageName(this.loginUserDto.id, this.loginUserDto.imageName).then(successData => {
        if(successData.errorCode !== 0){
          requestFailed(successData);
        }else{
          notificationSuccess('用户图片上传成功', '操作成功');
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },

    /**
         * 清空用户自定义设置
         */
    clear: function () {
      UserStorageResource.clearUserStorage().then(successData => {
        Notify.success('成功', '用户自定义设置删除成功', 1500);
      }, errorData => {
        Common.processException(errorData);
      });
    },


    /**
         * 获取loginInfo
         * @return {void}
         */
    getLoginInfo: function () {
      var _self = this;
      var json = localStorage.getItem('#LoginInfo');
      this.loginInfo = JSON.parse(json);
      let userId = this.loginInfo.userId;
      // add here
      UserResourceV2.uniqueById(userId).then(successData => {
        if(successData.errorCode === 0){
          _self.loginUserDto = successData.data;
        }else{
          requestSuccess(successData);
        }
      }, errorData => {
        Common.processException(errorData);
      });
    },

    
    handlerPasswordStrength1: function(){
      if(this.newPassword == null || this.newPassword.length == 0){
        this.newPasswordCheckResult = '';
        return;
      }

      let message = PasswordService.handlerPasswordStrength(this.$i18n.locale,this.newPassword);
      if(message != null && message.length > 0){
        this.newPasswordCheckResult = message;
      }else{
        this.newPasswordCheckResult = '';
      }
    },

    
    handlerPasswordStrength2: function(){
      if(this.newPassword2 == null || this.newPassword2.length2 == 0){
        this.newPassword2CheckResult = '';
        return;
      }

      if(this.newPassword != this.newPassword2){
        this.newPassword2CheckResult = '两次密码输入不一致!';
      }else{
        this.newPassword2CheckResult = '';
      }
    },
  },
};
</script>

<style scoped>
.title {
    margin: 0px 0px 10px 0px;
}

.title-addon {
    font-size: large;
    margin-left: 20px;
}

.divClass {
    text-align: center;
    font-size: 30px;
    color: red;
}
</style>
