<template>
  <es-form
    ref="form"
    class="es-user-info"
    :model="values"
    :contents="forms"
    :autocomplete="false"
    @change="handleFormChange"
    @submit="handleFormSubmit"
  >
    <template slot="other">
      <slot></slot>
    </template>
  </es-form>
</template>
<script>
import {
  initUserSet,
  updateUserCustomInfo,
  updateUserInfo,
  downloadByAdjunctId,
  switchUserTo
} from 'eoss-ui/src/config/api.js';
import store from 'eoss-ui/src/utils/store';
import util from 'eoss-ui/src/utils/util';

export default {
  props: {
    // showNotify: {
    //   type: Boolean,
    //   default: true
    // },
    secret: {
      type: Boolean,
      default: true
    },
    contents: {
      type: Array,
      default() {
        return [
          {
            title: '用户信息',
            contents: [
              {
                type: 'upload',
                name: 'userHeadUrl',
                label: '头像',
                portrait: true,
                code: 'USER_IMG',
                col: 12,
                weixinQrcode: true,
                class: 'es-flex-none'
              },
              {
                type: 'select',
                name: 'job',
                label: '切换职务',
                valueType: 'object',
                class: 'es-user-info-job',
                row: true,
                col: 12
              },
              {
                name: 'orgName',
                label: '所属机构',
                type: 'text',
                disabled: true,
                col: 6
              },
              {
                name: 'depName',
                label: '所属部门',
                type: 'text',
                disabled: true,
                col: 6
              },
              {
                name: 'idCard',
                label: '身份证号',
                maxlength: 18,
                type: 'text',
                disabled: true,
                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',
                rules: {
                  type: 'email',
                  message: '请输入正确的邮箱地址',
                  trigger: 'blur'
                },
                col: 6
              },
              {
                name: 'officetel',
                placeholder: '座机号',
                label: '座机号',
                type: 'text',
                rules: {
                  type: 'telephone'
                  //message: '请输入正确的邮箱地址',
                  //trigger: 'blur'
                },
                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
              }
            ]
          }
        ];
      }
    }
  },
  data() {
    return {
      results: '',
      userScanBindImgUrl: '',
      qrcode: '',
      notify: store.get('userStyle') ? store.get('userStyle').notify : '',
      checkPassword: '',
      checkPasswordMsg: '',
      values: {
        userHeadUrl: store.get('userModel').userHeadUrl
          ? store.get('userModel').userHeadUrl
          : 'data:image/png;base64, ',
        job: '',
        orgName: '',
        depName: '',
        idCard: '',
        phone: '',
        email: '',
        officeTel: '',
        oldpassword: '',
        password: '',
        notify: []
      }
    };
  },
  computed: {
    forms() {
      let page = JSON.parse(JSON.stringify(this.contents));
      for (let i = 0; i < page.length; i++) {
        for (let x = 0; x < page[i].contents.length; x++) {
          let item = page[i].contents[x];
          if (item.name == 'userHeadUrl') {
            page[i].contents[x].ownId = store.get('userModel').personId;
            page[i].contents[x].onSuccess = this.handleUploadSuccess;
            if (item.weixinQrcode && this.qrcode) {
              page[i].contents[x].inline = {
                range: false,
                class: 'weixinQrcode',
                type: 'image',
                url: this.qrcode,
                event: this.getQrcode
              };
            }
          }
          if (item.name == 'job') {
            page[i].contents[x].data = store.get('userModel').identityList;
          }
          if (item.name == 'oldpassword') {
            page[i].contents[x].rules = {
              required: true,
              message: '请输入旧密码'
            };
          }
          if (item.name == 'password' && this.checkPassword) {
            page[i].contents[x].rules = {
              pattern: this.checkPassword,
              message: this.checkPasswordMsg
                ? this.checkPasswordMsg
                : '密码格式不合法',
              trigger: 'blur'
            };
          }
          if (item.name == 'repassword') {
            let rules = [{ validator: this.repassword, trigger: 'blur' }];
            if (this.checkPassword) {
              rules.push({
                pattern: this.checkPassword,
                message: this.checkPasswordMsg
                  ? this.checkPasswordMsg
                  : '密码格式不合法',
                trigger: 'blur'
              });
            }
            page[i].contents[x].rules = rules;
          }
        }
      }
      // if (this.showNotify) {
      //   page.push({
      //     title: '接收消息类型',
      //     contents: [
      //       {
      //         type: 'checkbox',
      //         labelHide: true,
      //         name: 'notify',
      //         col: 12,
      //         data: store.get('notifyList')
      //       }
      //     ]
      //   });
      // }
      page.push({
        type: 'submit',
        contents: [
          {
            type: 'primary',
            event: 'submit',
            text: '保存'
          }
        ]
      });
      return page;
    }
  },
  created() {
    this.getData();
    store.get('userModel').identityList.forEach((item) => {
      if (item.id === store.get('userModel').identityId) {
        this.values.job = item;
        return;
      }
    });
  },
  mounted() {
    this.values.notify = this.notify ? this.notify.split(',') : [];
  },
  methods: {
    getQrcode() {
      this.qrcode =
        util.getStorage('host') +
        this.userScanBindImgUrl +
        '&_tt=' +
        Math.random().toString().split('.')[1];
    },
    getData() {
      util
        .ajax({
          url: initUserSet
        })
        .then((res) => {
          if (res.rCode === 0) {
            const results = JSON.parse(JSON.stringify(res.results));
            if (results.checkPassword) {
              this.checkPassword = new RegExp(results.checkPassword);
            }
            if (results.checkPasswordMsg) {
              this.checkPasswordMsg = results.checkPasswordMsg;
            }
            this.results = results.simpleUserInfo;
            this.values = { ...this.values, ...results.simpleUserInfo };
            // this.values.orgName = results.simpleUserInfo.orgName;
            // this.values.depName = results.simpleUserInfo.depName;
            // this.values.idCard = results.simpleUserInfo.idCard;
            // this.values.phone = results.simpleUserInfo.phone;
            // this.values.email = results.simpleUserInfo.email;
            // this.values.officeTel = results.simpleUserInfo.officeTel;
            if (results.userScanBindImgUrl) {
              this.userScanBindImgUrl = results.userScanBindImgUrl;
              this.qrcode =
                util.getStorage('host') + results.userScanBindImgUrl;
            } else {
              this.qrcode = '';
            }
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          if (err.message && err.message !== 'canceled') {
            this.$message.error(err.message);
          }
        });
    },
    handleUploadSuccess(results, file) {
      const res = file.response;
      let url;
      if (res.url) {
        url = res.url;
      } else {
        url = downloadByAdjunctId + '?adjunctId=' + res.adjunctId;
      }
      this.$emit('change', 'userHeadUrl', url);
    },
    handleFormChange(type, value) {
      switch (type) {
        case 'job':
          util
            .ajax({ url: switchUserTo, params: { userId: value.value } })
            .then((res) => {
              if (res.rCode == 0) {
                util.setStorage({
                  type: this.storage,
                  key: 'userId',
                  value: value.value
                });
                util.removeStorage(['mainConfig', 'jump']);
                this.$message({
                  message: res.msg,
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    if (
                      util.win.location.href.indexOf('#/main') > -1 ||
                      util.win.location.href.indexOf('/main.html') > -1
                    ) {
                      location.reload();
                    } else {
                      this.$router.replace('/main');
                    }
                  }
                });
              } else {
                this.$message({
                  message: res.msg || '系统错误，请联系管理员！',
                  type: 'error'
                });
              }
            })
            .catch((err) => {
              if (err.message && err.message !== 'canceled') {
                this.$message.error(err.message);
              }
            });
          break;
      }
    },
    handleFormSubmit() {
      let initLogin = util.getStorage('initLogin');
      initLogin && (initLogin = JSON.parse(initLogin));
      util
        .ajax({
          url: updateUserInfo,
          params: {
            email: this.values.email,
            officeTel: this.values.officeTel,
            phone: this.values.phone,
            oldPassword:
              this.secret &&
              initLogin &&
              initLogin.secret &&
              this.values.oldpassword
                ? util.esmEncrypt({
                    data: this.values.oldpassword,
                    key: initLogin.secret
                  })
                : this.values.oldpassword,
            password:
              this.secret &&
              initLogin &&
              initLogin.secret &&
              this.values.password
                ? util.esmEncrypt({
                    data: this.values.password,
                    key: initLogin.secret
                  })
                : this.values.password
          }
        })
        .then((res) => {
          if (res.rCode === 0) {
            if (this.values.oldpassword && this.values.password) {
              this.$confirm('密码修改成功,请重新登录！', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                closeOnClickModal: false,
                type: 'warning'
              })
                .then(() => {
                  const loginPage =
                    util.getStorage('login') || util.getStorage('loginPage');
                  const topWin = util.getWinTop();
                  try {
                    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 =
                          topWin.location.href.slice(0, len) + '#/login';
                      } else {
                        topWin.location.href = '/login.html';
                      }
                    }
                  } catch (error) {
                    console.warn('Failed to handle login redirect:', error);
                    try {
                      // Fallback to postMessage if direct access fails
                      topWin.postMessage({ type: 1 }, '*');
                    } catch (postMessageError) {
                      console.warn(
                        'Failed to send postMessage:',
                        postMessageError
                      );
                    }
                  }
                })
                .catch((e) => {});
            } else {
              const notify = this.values.notify.sort().join(',');
              if (notify != this.notify.split(',').sort().join(',')) {
                util
                  .ajax({
                    url: updateUserCustomInfo,
                    params: {
                      notify: notify
                    }
                  })
                  .then((results) => {
                    if (results.rCode === 0) {
                      this.$message({
                        message: results.msg,
                        type: 'success',
                        onClose: () => {
                          this.$emit('success', this.values);
                        }
                      });
                    } else {
                      this.$message.error(
                        results.msg || '系统错误，请联系管理员！'
                      );
                    }
                  })
                  .catch((err) => {
                    if (err.message && err.message !== 'canceled') {
                      this.$message.error(err.message);
                    }
                  });
              } else {
                this.$message({
                  message: res.msg,
                  type: 'success',
                  onClose: () => {
                    this.$emit('success', this.values);
                  }
                });
              }
            }
          } else {
            let msg = res.msg || '系统错误，请联系管理员！';
            this.$message.error(msg);
          }
        });
      if (this.values.notify.length !== this.notify.split(',').length) {
      }
    },
    repassword(rule, value, callback) {
      if (this.values.oldpassword && this.values.password && value) {
        util.identical({ value: [value, this.values.password], callback });
      } else {
        callback();
        return true;
      }
    }
  }
};
</script>
