<template>
  <Navbar
    :title="$t('lang.UserParameters.personalSettings')"
    :is-go-back="true"
  />
  <div style="margin-top: 1rem" class="container">
    <div>
      <div>
        <Navbar :title="$t('lang.UserParameters.userAvatar')" />
        <div>
          <ImageUpload
            v-model="loginUserDto.imageName"
            :class-name="'com.leanwo.prodog.base.model.User'"
            @update:model-value="uploadUserImage"
          />
        </div>
      </div>

      <div>
        <Navbar :title="$t('lang.UserParameters.roleTemplate')" />
        <div class="role-templates">
          <li v-for="template in loginUserDto.roleTemplates" :key="template.no">
            {{ template.name }}
          </li>
        </div>
      </div>

      <div>
        <Navbar :title="$t('lang.UserParameters.role')" />
        <div class="role-templates">
          <li v-for="role in loginUserDto.roles" :key="role.id">
            {{ role.name }}
          </li>
        </div>
      </div>

      <div>
        <Navbar :title="$t('lang.UserParameters.userPasswordModification')" />
        <a-form layout="vertical">
          <!-- 原密码 -->
          <a-form-item :label="$t('lang.UserParameters.originalPassword')">
            <a-input-password
              id="oldPassword"
              v-model:value="oldPassword"
              :placeholder="$t('lang.UserParameters.inputOriginalPassword')"
              autocomplete="off"
            />
          </a-form-item>

          <!-- 新密码 -->
          <a-form-item
            :label="$t('lang.UserParameters.newPassword')"
            :validate-status="newPasswordCheckResult ? 'error' : ''"
            :help="newPasswordCheckResult"
          >
            <a-input-password
              id="newPassword"
              v-model:value="newPassword"
              :placeholder="$t('lang.UserParameters.inputNewPassword')"
              autocomplete="off"
              @input="handlerPasswordStrength1"
            />
          </a-form-item>

          <!-- 确认密码 -->
          <a-form-item
            :label="$t('lang.UserParameters.confirmPassword')"
            :validate-status="newPassword2CheckResult ? 'error' : ''"
            :help="newPassword2CheckResult"
          >
            <a-input-password
              id="newPassword2"
              v-model:value="newPassword2"
              :placeholder="$t('lang.UserParameters.againInputNewPassword')"
              autocomplete="off"
              @input="handlerPasswordStrength2"
            />
          </a-form-item>
        </a-form>
      </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> -->

      <a-space style="margin-top: 12px;">
        <a-button type="primary" @click="saveUserParamter">
          {{ $t("lang.UserParameters.save") }}
        </a-button>
        <a-button danger @click="clear">
          {{ $t("lang.UserParameters.clearUserSettings") }}
        </a-button>
      </a-space>
    </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';
import store from '../store/index.js';

export default {
  components: {
    ImageUpload,
  },
  data: function () {
    return {
      oldPassword: '',
      newPassword: '',
      newPasswordCheckResult: '',
      newPassword2: '',
      newPassword2CheckResult: '',
      parameterValues: [],
      isShowUserParamter: false,
      loginInfo: null,
      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 != '') {
              if (data.includes('修改密码成功')){
                Notify.info('成功', data, 1500);
              } else {
                Notify.error('失败', data, false);
              }
              _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 {
            let data = JSON.parse(localStorage.getItem('#LoginInfo'));
            const newData = {
              ...data,
              userImageUrl: this.loginUserDto.imageName,
            };
            localStorage.setItem('#LoginInfo', JSON.stringify(newData));
            this.$store.commit('updateImageSrc', this.loginUserDto.imageName);
            notificationSuccess('用户图片上传成功', '操作成功');
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },

    /**
     * 清空用户自定义设置
     */
    clear: function () {
      UserStorageResource.clearUserStorage().then(
        successData => {
          if (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;
}
.role-templates {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* 设置间隔 */
  list-style: none;
}
:deep(.ant-form-item-label > label){
  font-size: 14px !important;
  font-weight: 500 !important;
}
</style>
