<template>
  <div class="personal-center">
    <a-tabs 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>账户密码</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="个性化">
        <div class="expect">
          <img src="@/assets/images/expect.png" alt="" />
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" tab="账户绑定">
        <div class="expect">
          <img src="@/assets/images/expect.png" alt="" />
        </div>
      </a-tab-pane>
    </a-tabs>
  </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 AvatarUpload from "@/components/uploadPicture/avatarUpload";

export default {
  components: {
    AvatarUpload,
    MegaModal,
  },
  data() {
    return {
      activeName: "a",
      avatarUrl: "",
      modalVisible: false,
      objStr: {
        width: "220px",
      },
      editPasswordForm: {
        oldPwd: "",
        newPwd: "",
        confirmPwd: "",
      },
      sexTypeList: [],
      isSave: true,
      userInfo: {
        userName: "", // 用户名
        password: "", // 密码
        employeeNo: "", // 员工工号
        name: "", // 姓名
        sex: "UNKNOWN", // 性别
        mobilePhone: "", // 手机号码
        email: "", // 邮箱
        workPhone: "", // 办公电话
      },
    };
  },
  computed: {
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
    }),
    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",
          },
        ],
      };
    },
  },
  mounted() {
    this.initPageData();
  },
  methods: {
    initPageData() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/user/info`)
        .then((res) => {
          this.userInfo = res.data.data.user;
          this.avatarUrl = res.data.data.user.avatar;
        });
      // 获取性别列表
      this.getDictByCode("DIC:COMMON:SEX_TYPE").then((res) => {
        this.sexTypeList = res.data.data;
      });
    },
    uploadSuccess(fileUrl) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/sys/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/sys/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/sys/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;
        }
      }
    },
  },
};
</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;
}
</style>
