<template>
  <es-form
    ref="form"
    class="es-user-info"
    :validate-on-rule-change="false"
    :model="model"
    :contents="forms"
    :autocomplete="false"
    :rules="formRules"
    :events="events"
    :resetValue="false"
    @submit="handleFormSubmit"
  >
    <template slot="other">
      <slot></slot>
    </template>
  </es-form>
</template>
<script>
import { updateUserInfo } from 'eoss-ui/src/config/api.js';
import util from 'eoss-ui/src/utils/util';

export default {
  name: 'UserInfo',
  props: {
    secret: {
      type: Boolean,
      default: true
    },
    contents: Array,
    value: {
      type: Object,
      default() {
        return {};
      }
    },
    rules: {
      type: Object,
      default() {
        return {};
      }
    },
    rules: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      model: this.value,
      defaultValues: JSON.parse(JSON.stringify(this.value)),
      events: {
        oldpassword: {
          change: () => {
            if (
              !this.model.repassword &&
              !this.model.oldpassword &&
              !this.model.repassword
            ) {
              this.$refs.form.clearValidate();
            }
          }
        },
        password: {
          change: () => {
            if (
              !this.model.repassword &&
              !this.model.oldpassword &&
              !this.model.repassword
            ) {
              this.$refs.form.clearValidate();
            }
          }
        },
        repassword: {
          change: () => {
            if (
              !this.model.repassword &&
              !this.model.oldpassword &&
              !this.model.repassword
            ) {
              this.$refs.form.clearValidate();
            }
          }
        }
      }
    };
  },
  computed: {
    formRules() {
      console.log(this.value);
      return {
        idCard: [
          {
            required:
              this.defaultValues.idCard !== null &&
              this.defaultValues.idCard !== undefined &&
              this.defaultValues.idCard !== '',
            message: '请输入身份证号',
            trigger: 'blur'
          },
          {
            pattern: new RegExp('(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)'),
            message: '身份证号不合法',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required:
              this.defaultValues.phone !== null &&
              this.defaultValues.phone !== undefined &&
              this.defaultValues.phone !== '',
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            pattern: new RegExp('^[1][3, 4, 5, 6, 7, 8, 9][0-9]{9}$'),
            message: '手机号不合法',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required:
              this.defaultValues.email !== null &&
              this.defaultValues.email !== undefined &&
              this.defaultValues.email !== '',
            message: '请输入邮箱地址',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: 'blur'
          }
        ],
        officeTel: [
          {
            required:
              this.defaultValues.officeTel !== null &&
              this.defaultValues.officeTel !== undefined &&
              this.defaultValues.officeTel !== '',
            message: '请输入座机号',
            trigger: 'blur'
          },
          {
            pattern: new RegExp(
              '^(?:\\(?0([1-9]\\d{1,2})\\)?[- ]?)?([2-9]\\d{6,7})$'
            ),
            message: '座机号不合法',
            trigger: 'blur'
          }
        ],

        oldpassword:
          this.model.password || this.model.repassword
            ? {
                required: true,
                message: '请输入旧密码'
              }
            : {},

        password: [
          this.model.repassword || this.model.oldpassword
            ? {
                required: true,
                message: '请输入新密码'
              }
            : {},
          ,
          {
            pattern: this.checkPassword,
            message: this.checkPasswordMsg
              ? this.checkPasswordMsg
              : '密码格式不合法',
            trigger: 'blur'
          }
        ],
        repassword: [
          this.model.password || this.model.oldpassword
            ? {
                required: true,
                message: '请再次输入新密码'
              }
            : {},
          { validator: this.repassword, trigger: 'blur' },
          this.checkPassword
            ? {
                pattern: this.checkPassword,
                message: this.checkPasswordMsg
                  ? this.checkPasswordMsg
                  : '密码格式不合法',
                trigger: 'blur'
              }
            : {}
        ],
        ...this.rules
      };
    },
    forms() {
      return this.contents
        ? this.contents
        : [
            {
              name: 'orgName',
              label: '所属机构',
              type: 'text',
              disabled: true,
              col: 6
            },
            {
              name: 'depName',
              label: '所属部门',
              type: 'text',
              disabled: true,
              col: 6
            },
            {
              name: 'idCard',
              label: '身份证号',
              type: 'text',
              disabled: true,
              maxlength: 18,
              col: 6
            },
            {
              name: 'outCode',
              label: '工号',
              type: 'text',
              disabled: true,
              col: 6
            },
            {
              name: 'phone',
              placeholder: '联系电话',
              label: '联系电话',
              type: 'text',
              col: 6
            },
            {
              name: 'email',
              placeholder: '电子邮箱',
              label: '电子邮箱',
              type: 'text',
              col: 6
            },
            {
              name: 'officeTel',
              placeholder: '座机号',
              label: '座机号',
              type: 'text',
              col: 6
            },
            {
              name: 'oldpassword',
              placeholder: '旧密码',
              label: '旧密码',
              type: 'text',
              col: 6
            },
            {
              name: 'password',
              placeholder: '新密码',
              label: '新密码',
              type: 'text',
              col: 6
            },
            {
              name: 'repassword',
              placeholder: '确认新密码',
              label: '确认新密码',
              type: 'text',
              col: 6
            }
          ];
    },
    formKey() {
      let keys = this.forms
        .filter((item) => {
          return (
            item.disabled !== true &&
            item.readonly !== true &&
            !['oldpassword', 'password', 'repassword'].includes(item.name)
          );
        })
        .map((item) => item.name);
      return keys;
    }
  },
  created() {},
  mounted() {},
  methods: {
    handleFormSubmit() {
      let initLogin = util.getStorage('initLogin');
      initLogin && (initLogin = JSON.parse(initLogin));
      let { oldpassword, password } = this.model;
      let data = {
        ...Object.fromEntries(
          Object.entries(this.model).filter(([key]) =>
            this.formKey.includes(key)
          )
        )
      };
      util
        .ajax({
          url: updateUserInfo,
          params: {
            ...data,
            oldPassword:
              this.secret && initLogin && initLogin.secret && oldpassword
                ? util.esmEncrypt({
                    data: oldpassword,
                    key: initLogin.secret
                  })
                : oldpassword,
            password:
              this.secret && initLogin && initLogin.secret && password
                ? util.esmEncrypt({
                    data: password,
                    key: initLogin.secret
                  })
                : password
          }
        })
        .then((res) => {
          if (res.rCode === 0) {
            if (oldpassword && password) {
              this.$confirm('密码修改成功,请重新登录！', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'warning'
              })
                .then(() => {
                  const loginPage =
                    util.getStorage('login') || util.getStorage('loginPage');
                  try {
                    const topWin = util.getWinTop();
                    if (loginPage) {
                      let src;
                      if (!util.startWith(loginPage, ['http', '/'], true)) {
                        let pathname = topWin.location.pathname;
                        if (pathname !== '/') {
                          pathname = pathname.split('/');
                          pathname.splice(pathname.length - 1);
                          pathname = pathname.join('/');
                          src = pathname + '/' + loginPage.replace('./', '');
                        } else {
                          src = pathname + loginPage.replace('./', '');
                        }
                      } else {
                        src = loginPage;
                      }
                      topWin.location.href = src;
                    } else if (topWin.location.href.indexOf('main.html') > -1) {
                      topWin.location.href = './login.html';
                    } else {
                      const hash = topWin.location.hash;
                      if (hash) {
                        const len = topWin.location.href.indexOf(hash);
                        topWin.location.href =
                          util.win.location.href.slice(0, len) + '#/login';
                      } else {
                        topWin.location.href = '/login.html';
                      }
                    }
                  } catch (error) {
                    console.warn('Failed to handle login redirect:', error);
                    try {
                      util.getWinTop().postMessage({ type: 1 }, '*');
                    } catch (postMessageError) {
                      console.warn(
                        'Failed to send postMessage:',
                        postMessageError
                      );
                    }
                  }
                })
                .catch((e) => {});
            } else {
              this.$message({
                message: res.msg,
                type: 'success',
                onClose: () => {
                  this.$emit('success', this.model);
                }
              });
            }
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        });
    },
    repassword(rule, value, callback) {
      if (this.model.oldpassword && this.model.password && value) {
        util.identical({ value: [value, this.model.password], callback });
      } else {
        callback();
        return true;
      }
    }
  }
};
</script>
