<template>
  <div class="personal-center">
    <a-tabs
      v-model="activeKey"
      tab-position="left"
      size="large"
      :tab-bar-style="objStr"
    >
      <a-tab-pane key="1" :tab="$t('BASIC_SETTING')">
        <a-form-model
          ref="userInfo"
          :model="userInfo"
          :rules="addFormRules"
          class="userInfo"
        >
          <a-collapse
            v-model="activeName"
            :bordered="false"
            expand-icon-position="right"
            class="collapse-header-divide"
          >
            <a-collapse-panel key="a" :header="$t('BASE_INFO')">
              <a-row>
                <a-col :span="12">
                  <a-row>
                    <a-form-model-item prop="userName" :label="$t('USER_NAME')">
                      <a-input v-model="userInfo.userName" disabled />
                    </a-form-model-item>
                  </a-row>
                  <a-row>
                    <a-form-model-item prop="name" :label="$t('FULL_NAME')">
                      <a-input v-model="userInfo.name" disabled />
                    </a-form-model-item>
                  </a-row>
                  <a-row>
                    <a-form-model-item
                      prop="employeeNo"
                      :label="$t('JOB_NUMBER')"
                    >
                      <a-input v-model="userInfo.employeeNo" disabled />
                    </a-form-model-item>
                  </a-row>
                  <a-row>
                    <a-form-model-item prop="sex" :label="$t('GENDER')">
                      <a-radio-group v-model="userInfo.sex">
                        <a-radio
                          v-for="(sex, index) in sexTypeList"
                          :key="index"
                          :value="sex.value"
                        >
                          {{ sex.label }}
                        </a-radio>
                      </a-radio-group>
                    </a-form-model-item>
                  </a-row>
                  <a-row>
                    <a-form-model-item
                      prop="workPhone"
                      :label="$t('WORK_PHONE')"
                    >
                      <a-input v-model="userInfo.workPhone" />
                    </a-form-model-item>
                  </a-row>
                  <a-row>
                    <a-form-model-item
                      prop="mobilePhone"
                      :label="$t('PHONE_NO')"
                    >
                      <a-input v-model="userInfo.mobilePhone" />
                    </a-form-model-item>
                  </a-row>
                  <a-row>
                    <a-form-model-item prop="email" :label="$t('EMAIL')">
                      <a-input v-model="userInfo.email" />
                    </a-form-model-item>
                  </a-row>
                </a-col>
                <a-col :span="8" :offset="4">
                  <AvatarUpload
                    v-model="avatarUrl"
                    @uploadSuccess="uploadSuccess"
                  />
                </a-col>
              </a-row>
              <a-button class="mb-5" type="primary" @click="handUpdate">
                {{ $t("UPDATE_BASIC") }}
              </a-button>
            </a-collapse-panel>
          </a-collapse>
        </a-form-model>
      </a-tab-pane>
      <a-tab-pane key="2" :tab="$t('SECURITY_SETTING')">
        <a-collapse
          v-model="activeName"
          :bordered="false"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('SECURITY_SETTING')">
            <div class="editPassword">
              <a-row>
                <a-col>
                  <span>{{ $t("ACCOUNT_PASSWORD") }}</span>
                </a-col>
              </a-row>
              <a-row>
                <a-col>
                  <div class="passwordStr">
                    <span
                      >{{ $t("PASSWORD_STRENGTH")
                      }}{{
                        systemConfig.PWD_LEVEL === "L"
                          ? "弱"
                          : systemConfig.PWD_LEVEL === "M"
                          ? "中"
                          : systemConfig.PWD_LEVEL === "H"
                          ? "高"
                          : ""
                      }}</span
                    >
                    <span class="edit" @click="handEdit">{{
                      $t("MODIFY")
                    }}</span>
                  </div>
                </a-col>
              </a-row>
              <MegaModal
                :visible="modalVisible"
                :title="$t('EDIT_PASSWORD')"
                @cancel="cancelPassword"
                @ok="okPassword"
              >
                <a-form-model
                  ref="editPasswordForm"
                  :model="editPasswordForm"
                  :rules="ruleFormRules"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <!-- 旧密码 -->
                  <a-form-model-item :label="$t('OLD_PASSWORD')" prop="oldPwd">
                    <a-input
                      v-model="editPasswordForm.oldPwd"
                      type="password"
                      :placeholder="$t('PLACEENTER')"
                    />
                  </a-form-model-item>
                  <!-- 新密码  -->
                  <a-form-model-item :label="$t('NEW_PASSWORD')" prop="newPwd">
                    <a-input
                      v-model="editPasswordForm.newPwd"
                      type="password"
                      :placeholder="$t('PLACEENTER')"
                    />
                  </a-form-model-item>
                  <!-- 确认密码 -->
                  <a-form-model-item
                    :label="$t('CONFIRM_PASSWORD')"
                    prop="confirmPwd"
                  >
                    <a-input
                      v-model="editPasswordForm.confirmPwd"
                      type="password"
                      :placeholder="$t('PLACEENTER')"
                    />
                  </a-form-model-item>
                </a-form-model>
              </MegaModal>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-tab-pane>
      <a-tab-pane key="3" :tab="$t('INDIVDUALIZATION')">
        <div class="expect">
          <img src="@/assets/images/expect.png" alt="" />
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" :tab="$t('ACCOUNT_BINDING')">
        <a-collapse
          default-active-key="a"
          :bordered="false"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('ACCOUNT_BINDING')">
            <div class="binding">
              <ul>
                <li class="flex items-center">
                  <div class="left-box mr-5">
                    <img
                      src="@/assets/images/wechat.png"
                      width="48"
                      height="48"
                      alt=""
                    />
                  </div>
                  <div class="flex-1 flex flex-col">
                    <span class="text">{{ $t("WECHAT_OFFICIAL") }}</span>
                    <span class="state">
                      <template v-if="openId">
                        {{ openId }}
                      </template>
                      <template v-else>{{
                        $t("CURRENTLY_WECHAT_OFFICIAL_ACCOUNT_BOUND")
                      }}</template>
                    </span>
                  </div>
                  <div class="dindIng">
                    <span v-if="!openId" @click="checkWxChatQrCode">{{
                      $t("BINDING")
                    }}</span>
                    <span v-else @click="handUnbound('WEO')">{{
                      $t("UNBOUND")
                    }}</span>
                  </div>
                </li>
                <li class="flex items-center">
                  <div class="left-box mr-5">
                    <img
                      src="@/assets/images/ding_talk.png"
                      width="48"
                      height="48"
                      alt=""
                    />
                  </div>
                  <div class="flex-1 flex flex-col">
                    <span class="text">{{ $t("DINGTALK_PUSH") }}</span>
                    <span class="state">
                      <template v-if="ddUnionId">
                        {{ ddUnionId }}
                      </template>
                      <template v-else>{{
                        $t("NO_PINS_AREA_CURRENTLY_BOUND")
                      }}</template>
                    </span>
                  </div>
                  <div class="dindIng">
                    <span v-if="!ddUnionId" @click="handClickDinding">{{
                      $t("BINDING")
                    }}</span>
                    <span v-else @click="handUnbound('DD')">{{
                      $t("UNBOUND")
                    }}</span>
                  </div>
                </li>
                <li class="flex items-center">
                  <div class="left-box mr-5">
                    <img
                      src="@/assets/images/official_account.png"
                      width="48"
                      height="48"
                      alt=""
                    />
                  </div>
                  <div class="flex-1 flex flex-col">
                    <span class="text">{{ $t("WECHAT") }}</span>
                    <span class="state">
                      <template v-if="wechatCorpUserId">
                        {{ wechatCorpUserId }}
                      </template>
                      <template v-else>
                        {{ $t("CURRENTLY_ENTERPRISE_WECHAT_BOUND") }}
                      </template>
                    </span>
                  </div>
                  <div class="dindIng">
                    <span v-if="!wechatCorpUserId" @click="checkWxQrCode">{{
                      $t("BINDING")
                    }}</span>
                    <span v-else @click="handUnbound('WEE')">{{
                      $t("UNBOUND")
                    }}</span>
                  </div>
                </li>
              </ul>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-tab-pane>
    </a-tabs>
    <MegaModal
      :title="$t('DINGTALK_PUSH')"
      :destroy-on-close="true"
      :visible="isQrcode"
      :footer="null"
      @cancel="handClickHide"
    >
      <div id="login_container"></div>
    </MegaModal>
    <MegaModal
      :title="$t('WECHAT')"
      :destroy-on-close="true"
      :visible="isWxHide"
      :footer="null"
      @cancel="handClickWxHide"
    >
      <div id="wx_qrcode"></div>
    </MegaModal>
    <MegaModal
      :title="$t('WECHAT_OFFICIAL')"
      :destroy-on-close="true"
      :visible="isWxChatHide"
      :footer="null"
      @cancel="handClickWxChat"
    >
      <div id="qrCode" ref="qrCodeDiv"></div>
      <p class="wxChatCode">{{ $t("LOG_IN_WITH_WECHAT_SCAN") }}</p>
    </MegaModal>
  </div>
</template>

<script>
import { Modal as MegaModal } from "@mega-design/ui-vue";
import { validCellphone, validEmail } from "@mega-apps/utils";
import { mapState } from "vuex";
import ApiConstant from "~/api/ApiConstant";
import QRCode from "qrcodejs2";
import AvatarUpload from "@/components/uploadPicture/avatarUpload";

export default {
  components: {
    AvatarUpload,
    MegaModal,
  },
  data() {
    return {
      activeKey: this.$route.query.activeKey
        ? this.$route.query.activeKey
        : "1",
      isQrcode: false,
      isWxHide: false,
      isWxChatHide: false,
      redirect: undefined,
      ddUnionId: "", // 钉钉绑定id
      wechatCorpUserId: "", //  企业微信绑定id
      appid: "dingu1swe9e6o1td0vgy",
      redirectUrl: `${window.location.protocol}//${window.location.host}/personal-center?activeKey=4&dd=true`,
      redirectUrlWx: `${window.location.protocol}//${window.location.host}/personal-center?activeKey=4&wx=true`,
      dingCodeConfig: {
        id: "login_container",
        style: "border:none;background-color:#FFFFFF;",
        width: "365",
        height: "400",
      },
      activeName: "a",
      avatarUrl: "",
      modalVisible: false,
      objStr: {
        width: "220px",
      },
      editPasswordForm: {
        oldPwd: "",
        newPwd: "",
        confirmPwd: "",
      },
      sexTypeList: [],
      isSave: true,
      wxappid: "",
      wxagentid: "",
      wxChatAppid: "",
      openId: "",
      wxChatInterval: undefined,
      userInfo: {
        userName: "", // 用户名
        password: "", // 密码
        employeeNo: "", // 员工工号
        name: "", // 姓名
        sex: "UNKNOWN", // 性别
        mobilePhone: "", // 手机号码
        email: "", // 邮箱
        workPhone: "", // 办公电话
      },
    };
  },
  computed: {
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
      user: (state) => state.auth.user?.user || {},
    }),
    addFormRules() {
      return {
        mobilePhone: [
          {
            validator: (rule, value, callback) => {
              if (value && !validCellphone(value)) {
                callback(new Error(this.$t("PHONE_FORMAT_ERROR")));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              if (value && !validEmail(value)) {
                callback(new Error(this.$t("EMAIL_FORMAT_ERROR")));
              }
              callback();
            },
            trigger: "blur",
          },
        ],
      };
    },
    // 表单校验
    ruleFormRules() {
      return {
        oldPwd: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        newPwd: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        confirmPwd: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
      };
    },
    getRedirectUrl() {
      return encodeURIComponent(this.redirectUrl);
    },
    getRedirectUrlWx() {
      return encodeURIComponent(this.redirectUrlWx);
    },
    getAuthUrl() {
      return `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.getRedirectUrl}`;
    },
    getGoto() {
      return encodeURIComponent(this.getAuthUrl);
    },
    getDingCodeConfig() {
      return { ...this.dingCodeConfig, goto: this.getGoto };
    },
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
        if (route.query.wx) {
          this.$axios
            .get(
              `${ApiConstant.PREFIX_CORE}/api/building/build-we?userId=${this.user?.id}&state=STATE&code=${route.query.code}`
            )
            .then((res) => {
              this.$router.push({ query: {} });
              this.initPageData();
            });
        }
        if (route.query.dd) {
          this.$axios
            .get(
              `${ApiConstant.PREFIX_CORE}/api/building/build-dd?userId=${this.user?.id}&code=${route.query.code}`
            )
            .then((res) => {
              this.$router.push({ query: {} });
              this.initPageData();
            });
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.initPageData();
    this.queryBuilding();
  },
  methods: {
    checkWxQrCode() {
      this.isWxHide = true;
      setTimeout(() => {
        // eslint-disable-next-line no-new
        window.WwLogin({
          id: "wx_qrcode",
          appid: this.wxappid,
          agentid: this.wxagentid,
          redirect_uri: this.getRedirectUrlWx,
        });
      });
    },
    // 解绑
    handUnbound(type) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/building/unbound?userId=${this.user?.id}&type=${type}`
        )
        .then((res) => {
          this.initPageData();
        });
    },
    handClickWxHide() {
      this.isWxHide = false;
    },
    checkWxChatQrCode() {
      this.isWxChatHide = true;
      this.$nextTick(() => {
        // eslint-disable-next-line no-new
        new QRCode(this.$refs.qrCodeDiv, {
          text: `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.wxChatAppid}&redirect_uri=${window.location.protocol}//${window.location.host}/core/api/building/build-weo?userId=${this.user?.id}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`,
          width: 210,
          height: 210,
          colorDark: "#333", // 二维码颜色
          colorLight: "#fff", // 二维码背景色
          correctLevel: QRCode.CorrectLevel.L, // 容错率，L/M/H
        });
      });
      this.wxChatInterval = window.setInterval(() => {
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/mdm/user/info`, {
            params: {
              isCancelApiLoad: true,
            },
          })
          .then((res) => {
            this.openId = res.data.data?.user?.openId;
            if (res.data.data?.user?.openId) {
              this.handClickWxChat();
            }
          });
      }, 10000);
    },
    handClickWxChat() {
      this.isWxChatHide = false;
      window.clearInterval(this.wxChatInterval);
    },
    queryBuilding() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/building/list-third-config`)
        .then((res) => {
          this.appid = res.data?.data?.DD_ASSESS_KEY;
          this.wxappid = res.data?.data?.WEE_CORP_ID;
          this.wxagentid = res.data?.data?.WEE_AGENT_ID;
          this.wxChatAppid = res.data?.data?.WEO_APP_ID;
        });
    },
    initPageData() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/user/info`)
        .then((res) => {
          this.userInfo = res.data.data?.user;
          this.avatarUrl = res.data.data?.user?.avatar;
          this.ddUnionId = res.data.data?.user?.ddUnionId;
          this.openId = res.data.data?.user?.openId;
          this.wechatCorpUserId = res.data.data?.user?.wechatCorpUserId;
        });
      // 获取性别列表
      this.getDictByCode("DIC:COMMON:SEX_TYPE").then((res) => {
        this.sexTypeList = res.data.data;
      });
    },
    uploadSuccess(fileUrl) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/mdm/user/avatar?url=${fileUrl}`)
        .then(() => {
          this.$message.success(this.$t("UPLOAD_SUCCESS"));
          this.initPageData();
        });
    },
    handEdit() {
      this.modalVisible = true;
    },
    cancelPassword() {
      this.modalVisible = false;
      this.$refs.editPasswordForm.resetFields();
      this.editPasswordForm.oldPwd = "";
      this.editPasswordForm.newPwd = "";
      this.editPasswordForm.confirmPwd = "";
    },
    handUpdate() {
      this.$refs.userInfo.validate((valid) => {
        if (valid) {
          const params = {
            ...this.userInfo,
          };
          delete params.password;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/mdm/user/update-person`,
              params
            )
            .then((res) => {
              this.$message.success(this.$t("SAVE_SUCCESS")); // 保存成功
            });
        }
      });
    },
    okPassword() {
      this.$refs.editPasswordForm.validate((valid) => {
        if (valid) {
          this.verification(
            this.editPasswordForm.newPwd,
            this.systemConfig.PWD_LENGTH,
            this.systemConfig.PWD_LEVEL
          );
          if (this.isSave) {
            if (
              this.editPasswordForm.newPwd !== this.editPasswordForm.confirmPwd
            ) {
              this.$message.error(this.$t("PASSWORD_SAMEWARN")); // 两次输入的密码必须相同
              return;
            }
            const { oldPwd, newPwd } = this.editPasswordForm;
            const req = {
              newPwd,
              oldPwd,
              passwordLevel: this.systemConfig.PWD_LEVEL,
            };
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/mdm/user/change-pwd`, req)
              .then(() => {
                this.modalVisible = false;
                this.$message.success(this.$t("SAVE_SUCCESS")); // 保存成功
              });
          }
        }
      });
    },
    verification(val, length, level) {
      if (val.length < length) {
        this.isSave = false;
        this.$message.error(this.$t("PASSWORD_LENGTH"));
      } else {
        if (level === "M") {
          const reg = /^(?![^a-zA-Z]+$)(?!\D+$)/;
          if (!reg.test(val)) {
            this.isSave = false;
            this.$message.error(this.$t("PASSWORD_LETTER"));
          } else {
            this.isSave = true;
          }
        }
        if (level === "H") {
          const res =
            /([0-9].*([a-zA-Z].*[!$#%?.&@~^]|[!$#%?.&~^].*[a-zA-Z])|[a-zA-Z].*([0-9].*[!$#%?.&~^]|[!$#%?.&~^].*[0-9])|[!$#%?.&].*([0-9].*[a-zA-Z]|[a-zA-Z].*[0-9]))/;
          if (!res.test(val)) {
            this.isSave = false;
            this.$message.error(this.$t("PASSWORD_SPECIAL"));
          } else {
            this.isSave = true;
          }
        }
        if (level === "L") {
          this.isSave = true;
        }
      }
    },
    initDingJs() {
      /* eslint-disable */
      !(function (window, document) {
        function d(a) {
          var e,
            c = document.createElement("iframe"),
            d = "https://login.dingtalk.com/login/qrcode.htm?goto=" + a.goto;
          (d += a.style ? "&style=" + encodeURIComponent(a.style) : ""),
            (d += a.href ? "&href=" + a.href : ""),
            (c.src = d),
            (c.frameBorder = "0"),
            (c.allowTransparency = "true"),
            (c.scrolling = "no"),
            (c.width = a.width ? a.width + "px" : "365px"),
            (c.height = a.height ? a.height + "px" : "400px"),
            (e = document.getElementById(a.id)),
            (e.innerHTML = ""),
            e.appendChild(c);
        }
        window.DDLogin = d;
      })(window, document);
      /* eslint-enable */
    },
    addDingListener() {
      // eslint-disable-next-line
      const self = this;
      const handleLoginTmpCode = function (loginTmpCode) {
        window.location.href = `${self.getAuthUrl}&loginTmpCode=${loginTmpCode}`;
      };

      const handleMessage = function (event) {
        if (event.origin === "https://login.dingtalk.com") {
          handleLoginTmpCode(event.data);
        }
      };
      if (typeof window.addEventListener !== "undefined") {
        window.addEventListener("message", handleMessage, false);
      } else if (typeof window.attachEvent !== "undefined") {
        window.attachEvent("onmessage", handleMessage);
      }
    },
    initDingLogin() {
      window.DDLogin(this.getDingCodeConfig);
    },
    handClickDinding() {
      this.isQrcode = true;
      setTimeout(() => {
        this.initDingJs();
        this.addDingListener();
        this.initDingLogin();
      });
    },
    handClickHide() {
      this.isQrcode = false;
    },
  },
};
</script>

<style lang="less" scoped>
@import (optional, once) "@/theme/index.less";

.personal-center {
  padding-top: 20px;
  padding-right: 40px;
}
/deep/.ant-tabs .ant-tabs-left-bar .ant-tabs-tab {
  text-align: left;
  margin: 0;
  line-height: 40px;
  font-size: 14px;
  padding: 8px 24px 8px 34px;
}
/deep/.ant-tabs-nav .ant-tabs-tab-active {
  background: fade(@primary-color, 10%);
  border-right: 5px solid @primary-color;
}
/deep/.ant-upload.ant-upload-select {
  width: 100%;
  height: 100%;
}
.editPassword {
  padding: 0 10px;
}
.passwordStr {
  display: flex;
  justify-content: space-between;
  padding: 10px 0 15px 0;
  border-bottom: 1px solid #d9d9d9;
  .edit {
    cursor: pointer;
    color: @primary-color;
  }
}
.expect {
  display: flex;
  justify-content: center;
  align-items: center;
}
/deep/.mb-5 {
  margin-bottom: 15px;
}
#login_container,
#wx_qrcode {
  display: flex;
  justify-content: center;
  align-items: center;
}
#qrCode {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 50px;
}
.wxChatCode {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 50px;
}
.binding {
  ul {
    li {
      border-bottom: 1px solid #eff2f5;
      margin-bottom: 20px;
      padding-bottom: 20px;
      .text {
        font-size: 14px;
        font-family: Source Han Sans CN-Regular, Source Han Sans CN;
        font-weight: 400;
        color: #333333;
      }
      .state {
        font-size: 14px;
        font-family: Source Han Sans CN-Regular, Source Han Sans CN;
        font-weight: 400;
        color: #b7b7b7;
      }
      .dindIng {
        span {
          cursor: pointer;
          font-size: 20px;
          font-family: Source Han Sans CN-Regular, Source Han Sans CN;
          font-weight: 400;
          color: #006896;
        }
      }
    }
  }
}
</style>
