<template>
  <div>
    <el-breadcrumb separator="/" class="bread_crumb1 bread_left">
      <el-breadcrumb-item :to="{ path: '/user' }">{{ $t("lang.personal_center") }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t("lang.profile") }}</el-breadcrumb-item>
    </el-breadcrumb>
    <block-radius class="info_block">
      <el-tabs v-if="is_admin == 3 || is_admin == 4" v-model="activeName" @tab-click="changeTab">
        <el-tab-pane label="个人信息详情" name="0"></el-tab-pane>
        <el-tab-pane label="业务系统详情" name="1"></el-tab-pane>
      </el-tabs>
      <div v-show="activeName == '0'">
        <el-form ref="form" :model="user_data" :rules="rules_user">
          <el-form-item class="info_item" prop="accountNo">
            <p>账号：</p>
            <el-input v-model="user_data.accountNo" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item class="info_item info_item_right_btn">
            <p>密码：</p>
            <el-input type="password" v-model="user_data.password" :disabled="true"></el-input>
            <el-button class="option_btn" @click="changePassword">修改密码</el-button>
          </el-form-item>
          <el-form-item class="info_item" prop="nickname">
            <p>昵称：</p>
            <el-input v-model="user_data.nickname"></el-input>
          </el-form-item>
          <el-form-item class="info_item">
            <p>头像：</p>
            <upload-file
              :multiple="false"
              :max="1"
              type="cropper"
              :readOnly="false"
              :list="imgList"
              @getNewList="getNewList"
            ></upload-file>
          </el-form-item>
          <el-form-item class="info_item" prop="contactPerson">
            <p>联系人：</p>
            <el-input v-model="user_data.contactPerson"></el-input>
          </el-form-item>
          <el-form-item class="info_item" prop="phone">
            <p>手机号：</p>
            <el-input v-model="user_data.phone"></el-input>
          </el-form-item>
          <el-form-item class="info_item" prop="email">
            <p>邮箱：</p>
            <el-input v-model="user_data.email"></el-input>
          </el-form-item>
          <el-form-item class="info_item">
            <p>组织机构：</p>
            <el-input v-model="user_data.organization" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item
            :class="user_data.userType == 3 ? 'info_item info_item_right_btn' : 'info_item'"
          >
            <p>当前用户类型：</p>
            <el-input v-model="user_data.userTypeName" :disabled="true"></el-input>
            <el-button
              v-if="user_data.userType == 3 && user_data.is_apply == 0"
              class="option_btn"
              @click="showUpLevel"
            >升级为开发者</el-button>
            <el-button
              v-else-if="user_data.userType == 3 && user_data.is_apply == 1"
              type="info"
              class="option_btn_gray_dis"
              disabled
            >升级为开发者</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-show="activeName == '1'">
        <el-form ref="formBusiness" :model="formBusiness" :rules="rules_bussiness">
          <el-form-item class="info_item" prop="businessSystemName">
            <p>业务系统名：</p>
            <el-input v-model="formBusiness.businessSystemName"></el-input>
          </el-form-item>
          <el-form-item class="info_item">
            <p>域名：</p>
            <el-input v-model="formBusiness.domainName"></el-input>
          </el-form-item>
          <el-form-item class="info_item">
            <p>IP（白名单）：</p>
            <div class="ip_block">
              <div v-for="(item, index) in formBusiness.ip_white" :key="item" class="ip_item">
                {{ item }}
                <i class="el-icon-close ip_del" @click="delIp(index, 'white')"></i>
              </div>
              <el-input
                v-if="whiteAddShow"
                class="ip_input"
                v-model="newIpWhite"
                @keyup.enter.native="watchKeyboardWhite"
              ></el-input>
              <el-button class="add_ip" @click="addIp('white')" icon="el-icon-plus">增加</el-button>
            </div>
          </el-form-item>
          <el-form-item class="info_item">
            <p>IP（黑名单）：</p>
            <div class="ip_block">
              <div v-for="(item, index) in formBusiness.ip_black" :key="item" class="ip_item">
                {{ item }}
                <i class="el-icon-close ip_del" @click="delIp(index, 'black')"></i>
              </div>
              <el-input
                v-if="blackAddShow"
                class="ip_input"
                v-model="newIpBlack"
                @keyup.enter.native="watchKeyboardBlack"
              ></el-input>
              <el-button class="add_ip" @click="addIp('black')" icon="el-icon-plus">增加</el-button>
            </div>
          </el-form-item>
          <el-form-item class="info_item info_item_right_btn_2">
            <p>密钥：</p>
            <el-input id="keys" v-model="formBusiness.private_token" :disabled="true"></el-input>
            <el-button class="option_btn" @click="copyKey">复制</el-button>
            <el-button class="option_btn_gray" @click="resetKey">重置</el-button>
          </el-form-item>
          <el-form-item class="info_item" prop="description">
            <p>描述：</p>
            <el-input type="textarea" :rows="2" v-model="formBusiness.description"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="btn_footer">
        <el-button class="registe" @click="registe">修改</el-button>
      </div>
      <el-dialog
        title="修改密码"
        :visible.sync="diaPassWord"
        width="440px"
        :modal-append-to-body="false"
      >
        <div class="change_psw">
          <el-form ref="form1" :model="form" :rules="passRules">
            <el-form-item class="dia_item">
              <p>旧密码：</p>
              <el-input v-model="form.passwordOld" autocomplete="new-password"></el-input>
            </el-form-item>
            <el-form-item prop="passwordNew" class="dia_item">
              <p>新密码：</p>
              <el-input
                v-model="form.passwordNew"
                autocomplete="new-password"
                :type="visible1 ? 'password':'text'"
              >
                <span
                  slot="suffix"
                  :title="visible1 ? '显示密码':'隐藏密码'"
                  @click="changePass1()"
                  style="cursor:pointer;"
                  :class="visible1 ? 'eye_dis':'eye'"
                ></span>
              </el-input>
            </el-form-item>
            <el-form-item prop="nextname" class="dia_item">
              <p>请再次输入密码：</p>
              <el-input
                v-model="form.nextname"
                autocomplete="new-password"
                :type="visible2 ? 'password':'text'"
              >
                <span
                  slot="suffix"
                  :title="visible2 ? '显示密码':'隐藏密码'"
                  @click="changePass2()"
                  style="cursor:pointer;"
                  :class="visible2 ? 'eye_dis':'eye'"
                ></span>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="dia_btn_footer">
          <el-button class="previous" @click="cancelChangePwd">取消</el-button>
          <el-button class="registe" @click="check_pass_form">修改</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="升级为开发者"
        :visible.sync="upLevelDia"
        width="440px"
        :modal-append-to-body="false"
      >
        <div class="change_psw">是否升级为开发者？</div>
        <div class="dia_btn_footer">
          <el-button class="previous" @click="cancelUpLevel">取消</el-button>
          <el-button class="registe" @click="submitUpLevel">升级</el-button>
        </div>
      </el-dialog>
    </block-radius>
  </div>
</template>

<script>
import BlockRadius from "@/components/general/block-radius";
import UploadFile from "@/components/general/upload_file";
export default {
  components: {
    BlockRadius,
    UploadFile,
  },
  data() {
    var checkNewPass = (rule, value, callback) => {
      let reg = new RegExp(
        /^.*(?=.{6,50})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,}).*$/
      );
      if (value == "") {
        callback(new Error("请输入新密码"));
      } else if (value == this.form.passwordOld) {
        callback(new Error("新密码不应与旧密码一致"));
      } else if (!reg.test(value)) {
        callback(new Error("密码包含大小写字母、数字，长度不小于6位"));
      } else {
        callback();
      }
    };
    var checkNextPass = (rule, value, callback) => {
      if (value !== this.form.passwordNew) {
        callback(new Error("密码和确认密码不一致"));
      } else {
        callback();
      }
    };
    var user_name_pass = (rule, value, callback) => {
      var reg = /^[a-zA-Z0-9|\-|_|\.]+$/;
      setTimeout(() => {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("只支持字母、数字、-、_、."));
        }
      }, 100);
    };
    return {
      activeName: "0",
      userId: "",
      is_admin: 0,
      user_data: {
        accountNo: "",
        password: "12345678",
        nickname: "",
        contactPerson: "",
        phone: "",
        email: "",
        organization: "",
        userType: "",
        userTypeName: "",
      },
      visible1: true,
      visible2: true,
      form: {
        passwordOld: "",
        passwordNew: "",
        nextname: "",
      },
      passRules: {
        passwordNew: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { validator: checkNewPass, trigger: "blur" },
        ],
        nextname: [
          { required: true, message: "请再次输入新密码", trigger: "blur" },
          { validator: checkNextPass, trigger: "blur" },
        ],
      },
      imgList: [],
      formBusiness: {
        businessSystemName: "",
        domainName: "",
        ip_white: [],
        ip_black: [],
        private_token: "",
        description: "",
      },
      whiteAddShow: false,
      blackAddShow: false,
      newIpWhite: "",
      newIpBlack: "",
      diaPassWord: false,
      upLevelDia: false,
      rules_user: {
        accountNo: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { max: 16, message: "长度请不大于16个字符", trigger: "blur" },
          { min: 3, message: "长度请不小于3个字符", trigger: "blur" },
          { validator: user_name_pass, trigger: "blur" },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { max: 8, message: "长度请小于8个字符", trigger: "blur" },
        ],
        contactPerson: [
          { max: 6, message: "长度请小于6个字符", trigger: "blur" },
        ],
        phone: [
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
          },
        ],
        email: [
          {
            pattern: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[-|_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
            message: "请输入正确的邮箱",
          },
        ],
      },
      rules_bussiness: {
        businessSystemName: [
          { max: 16, message: "长度请小于16个字符", trigger: "blur" },
        ],
        description: [
          { max: 500, message: "长度请小于500个字符", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getCurrentUser();
  },
  methods: {
    getCurrentUser() {
      this.$api.user.getNowUser().then((response) => {
        if (response.data.success == 1) {
          this.is_admin = response.data.data.is_admin;
          this.userId = response.data.data.user_id;
          this.getUserInfo();
        } else {
          console.log(response.data.errMsg);
        }
      });
    },
    getUserInfo() {
      this.$api.user.getUserDetail({ id: this.userId }).then((response) => {
        if (response.data.success == 1) {
          let data = response.data.data;
          this.user_data.accountNo = data.user_id;
          this.user_data.nickname = data.user_name;
          this.user_data.contactPerson = data.link_man;
          this.user_data.phone = data.phone;
          this.user_data.email = data.email;
          this.user_data.organization = data.department;
          this.user_data.userType = data.is_admin;
          this.user_data.userTypeName =
            this.user_data.userType == 1
              ? "超级管理员"
              : this.user_data.userType == 2
              ? "组织管理员"
              : this.user_data.userType == 3
              ? "普通用户"
              : "开发者";
          this.user_data.is_apply = data.is_apply;
          this.imgList = [];
          this.imgList.push(data.picture_path);
          this.formBusiness.businessSystemName = data.system_name;
          this.formBusiness.domainName = data.domain_name;
          this.formBusiness.ip_white = data.ip_whitelist;
          this.formBusiness.ip_black = data.ip_blacklist;
          this.formBusiness.private_token = data.private_token;
          this.formBusiness.description = data.description;
        }
      });
    },
    changeTab() {},
    getNewList(val) {
      this.imgList[0] = val[0].url;
    },
    registe() {
      let query = {};
      if (this.activeName == 0) {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            query = {
              pageType: "personalFile", // this page is user info
              user_id: this.user_data.accountNo,
              user_name: this.user_data.nickname,
              phone: this.user_data.phone,
              email: this.user_data.email,
              is_admin: this.user_data.userType,
              link_man: this.user_data.contactPerson,
              picture_path: this.imgList[0],
            };
            this.$api.authority.setUserInfo(query).then((response) => {
              if (response.data.success == 1) {
                this.$message({
                  message: "修改个人信息成功",
                  type: "success",
                });
                this.getUserInfo();
                this.getNowCurrentUser();
              } else {
                this.$message({
                  message: response.data.errMsg,
                  type: "error",
                });
              }
            });
          } else {
            return false;
          }
        });
      } else if (this.activeName == 1) {
        this.$refs["formBusiness"].validate((valid) => {
          console.log(valid);
          if (valid) {
            query = {
              pageType: "systemFile", // this page is system info
              user_id: this.user_data.accountNo,
              system_name: this.formBusiness.businessSystemName,
              domain_name: this.formBusiness.domainName,
              ip_whitelist: this.formBusiness.ip_white,
              ip_blacklist: this.formBusiness.ip_black,
              description: this.formBusiness.description,
            };
            this.$api.authority.setUserInfo(query).then((response) => {
              if (response.data.success == 1) {
                this.$message({
                  message: "修改个人信息成功",
                  type: "success",
                });
                this.getUserInfo();
                this.getNowCurrentUser();
              } else {
                this.$message({
                  message: response.data.errMsg,
                  type: "error",
                });
              }
            });
          } else {
            return false;
          }
        });
      }
    },
    getNowCurrentUser() {
      this.$api.user.getNowUser().then(({ data }) => {
        if (data.success == 1) {
          this.$store.commit("userInfofun", data.data);
          this.now_user = this.level;
        } else {
          console.log(data.errMsg);
        }
      });
    },
    changePassword() {
      this.diaPassWord = true;
    },
    changePass1() {
      this.visible1 = !this.visible1;
    },
    changePass2() {
      this.visible2 = !this.visible2;
    },
    cancelChangePwd() {
      this.$refs.form1.resetFields();
      this.diaPassWord = false;
    },
    check_pass_form() {
      this.$refs["form1"].validate((valid) => {
        if (valid) {
          this.submitChangePwd();
        } else {
          this.$message.error("请检查表单");
          return false;
        }
      });
    },
    submitChangePwd() {
      let query = {
        id: this.user_data.accountNo,
        form: {
          origin_password: this.form.passwordOld,
          new_password: this.form.passwordNew,
        },
      };
      this.$api.user.editUserPassword(query).then((response) => {
        if (response.data.success == 1) {
          this.$message({
            message: "修改密码成功",
            type: "success",
          });
          this.$refs.form1.resetFields();
          this.diaPassWord = false;
          this.getUserInfo();
        } else {
          this.$message({
            message: response.data.errMsg,
            type: "error",
          });
        }
      });
    },
    cancelUpLevel() {
      this.upLevelDia = false;
    },
    submitUpLevel() {
      this.upLevelDia = false;
      this.$api.authority.updateLevel().then((response) => {
        if (response.data.success == 1) {
          this.$message({
            message: "申请升级开发者成功",
            type: "success",
          });
          this.getUserInfo();
        } else {
          this.$message({
            message: "申请升级开发者失败",
            type: "error",
          });
        }
      });
    },
    resetKey() {
      this.$confirm("此操作将重置您的密钥, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        cancelButtonClass: "msg_btn_gray",
        confirmButtonClass: "msg_btn",
        type: "warning",
      })
        .then(() => {
          this.$api.authority
            .resetUserKey({ user_id: this.user_data.accountNo })
            .then((response) => {
              if (response.data.success == 1) {
                this.$message({
                  message: "重置密钥成功",
                  type: "success",
                });
                this.getUserInfo();
                this.getCurrentUser();
              } else {
                this.$message({
                  message: "重置密钥失败",
                  type: "error",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置",
          });
        });
    },
    showUpLevel() {
      this.upLevelDia = true;
    },
    copyKey() {
      const input = document.createElement("input");
      document.body.appendChild(input);
      input.setAttribute("value", this.formBusiness.private_token);
      input.select();
      if (document.execCommand("copy")) {
        document.execCommand("copy");
        this.$message({
          message: "复制成功",
          type: "success",
        });
      }
      document.body.removeChild(input);
    },
    delIp(index, type) {
      if (type == "white") {
        this.formBusiness.ip_white.splice(index, 1);
      } else if (type == "black") {
        this.formBusiness.ip_black.splice(index, 1);
      }
    },
    addIp(type) {
      if (type == "white") {
        this.whiteAddShow
          ? this.$message({
              message: "请按回车完善本次ip填写",
              type: "error",
            })
          : (this.whiteAddShow = true);
      } else if (type == "black") {
        this.blackAddShow
          ? this.$message({
              message: "请按回车完善本次ip填写",
              type: "error",
            })
          : (this.blackAddShow = true);
      }
    },
    watchKeyboardWhite() {
      let self = this;
      if (self.newIpWhite != "") {
        self.formBusiness.ip_white.push(self.newIpWhite);
        self.whiteAddShow = false;
        self.newIpWhite = "";
      }
    },
    watchKeyboardBlack() {
      let self = this;
      if (self.newIpBlack != "") {
        self.formBusiness.ip_black.push(self.newIpBlack);
        self.blackAddShow = false;
        self.newIpBlack = "";
      }
    },
  },
};
</script>
<style scoped>
.info_block {
  margin: 0 20px 20px;
  position: relative;
}
.btn_footer {
  display: flex;
  justify-content: flex-end;
  margin: 60px 20px 10px;
}
.previous {
  width: 100px;
  background-color: #c3caf8;
  color: #0f2683;
}
.registe {
  width: 100px;
  background-color: #0f2683;
  color: #f8f9fd;
}
.option_btn {
  width: 124px;
  background-color: #495feb;
  border-radius: 8px;
  color: #f8f9fd;
}
.option_btn_gray {
  width: 124px;
  background-color: #e3e5ef;
  border-radius: 8px;
  color: #0f2683;
}
.option_btn_gray_dis {
  width: 124px;
  border-radius: 8px;
}
.info_item {
  width: 70%;
  min-width: 600px;
  max-width: 1200px;
  margin-bottom: 12px;
}
.info_item p {
  padding-left: 15px;
  color: #242c43;
}
.change_psw {
  text-align: left;
}
.dia_item {
  width: 100%;
  margin-bottom: 12px;
}
.dia_item p {
  padding-left: 15px;
  color: #242c43;
}
.dia_btn_footer {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0 0;
}
.ip_block {
  border-radius: 8px;
  border: solid 1px #e3e5ef;
  padding: 10px 0 0 10px;
  line-height: 24px;
}
.ip_item {
  display: inline-block;
  position: relative;
  background-color: #e6ebfe;
  border-radius: 4px;
  color: #0f2683;
  font-size: 12px;
  line-height: 24px;
  padding: 0 26px 0 8px;
  margin-right: 10px;
  margin-bottom: 10px;
}
.ip_del {
  position: absolute;
  right: 8px;
  top: 6px;
  font-size: 14px;
  color: #6573ae;
  cursor: pointer;
}
.ip_del:hover {
  color: #e56600;
}
.add_ip {
  background-color: #495feb;
  border-radius: 4px;
  color: #f8f9fd;
  font-size: 12px;
  line-height: 24px;
  padding: 0 8px;
  margin-right: 10px;
  margin-bottom: 10px;
}
.ip_input {
  width: 110px;
  margin-right: 10px;
  margin-bottom: 10px;
}
.eye {
  display: inline-block;
  width: 20px;
  height: 20px;
  position: relative;
  top: 4px;
  cursor: pointer;
  background: url("~@/assets/imgs/login_eye.png") no-repeat center center;
}
.eye_dis {
  display: inline-block;
  width: 20px;
  height: 20px;
  position: relative;
  top: 6px;
  cursor: pointer;
  background: url("~@/assets/imgs/login_eye_dis.png") no-repeat center center;
}
</style>
<style>
.info_item_right_btn .el-input {
  width: calc(100% - 140px);
  margin-right: 10px;
}
.info_item_right_btn .el-select {
  width: calc(100% - 140px);
  margin-right: 10px;
}
.info_item_right_btn .el-select .el-input {
  width: 100%;
}
.info_item_right_btn_2 .el-input {
  width: calc(100% - 280px);
  margin-right: 10px;
}
.info_block .el-dialog__wrapper {
  padding-left: 180px;
}
.info_block .v-modal {
  position: absolute;
  border-radius: 8px;
  width: 100%;
  height: 100%;
}
.info_block .el-dialog__body {
  padding: 15px 20px 20px;
}
.ip_input .el-input__inner {
  border-radius: 4px;
  padding: 0 8px;
  font-size: 12px;
  line-height: 24px;
  height: 24px;
}
.msg_btn {
  width: 70px;
  background-color: #495feb;
  border-radius: 8px;
  color: #f8f9fd;
}
.msg_btn:hover {
  background-color: #596ffb;
}
.msg_btn_gray {
  width: 70px;
  background-color: #e3e5ef;
  border-radius: 8px;
  color: #0f2683;
}
.msg_btn_gray:hover {
  background-color: #e8eaf4;
  color: #0f2683;
}
.change_psw .el-input__suffix {
  width: 20px;
  right: 10px;
}
</style>