<template>
  <div class="page_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="parent_container">
      <div class="left_container bgc_white">
        <el-menu default-active="1" @select="switchMenu">
          <el-menu-item index="1">
            <span>授权信息</span>
          </el-menu-item>
          <el-menu-item index="2">
            <span>安全相关</span>
          </el-menu-item>
          <el-menu-item index="3">
            <span>登录注册配置</span>
          </el-menu-item>
        </el-menu>
      </div>
      <div class="right_container bgc_white">
        <!-- 授权信息表单 -->
        <el-form
          v-if="activeIndex == 1"
          ref="authorizeFormRef"
          :model="authorizeFormData"
          :rules="authorizeRules"
          label-width="110px"
          class="authorizeForm">
          <el-form-item label="当前版本号" prop="system_version">
            <el-input disabled v-model="authorizeFormData.system_version" />
          </el-form-item>
          <el-form-item label="User" prop="system_user">
            <el-input placeholder="统一管理用户认证平台" v-model="authorizeFormData.system_user" />
          </el-form-item>
          <el-form-item label="Key" prop="license">
            <el-input placeholder="请输入" rows="5" v-model="authorizeFormData.license" type="textarea" />
          </el-form-item>
          <el-form-item label="有效期至" prop="license_dead_date">
            <el-input disabled v-model="authorizeFormData.license_dead_date" />
          </el-form-item>
          <el-form-item label="剩余有效期提醒" prop="license_inform_day">
            <el-input placeholder="请输入" v-model="authorizeFormData.license_inform_day">
              <template #append>天</template>
            </el-input>
            <el-tooltip placement="top-start" effect="light">
              <template #content>
                范围（0~90），单位：天， 当剩余有效期在配置区间内时，系统会在用户登录系统时发出提醒，0表示不提醒
              </template>
              <div class="tip-image"></div>
            </el-tooltip>
          </el-form-item>
        </el-form>
        <!-- 安全相关表单 -->
        <el-form
          v-if="activeIndex == 2"
          ref="secureFormRef"
          :model="secureFormData"
          :rules="secureRules"
          label-width="110px"
          class="secureForm">
          <div class="passwordItem">
            <el-form-item label="最低密码强度" prop="min_pwd_level">
              <el-select v-model="secureFormData.min_pwd_level" placeholder="请选择">
                <el-option label="弱" :value="1" />
                <el-option label="中" :value="2" />
                <el-option label="强" :value="3" />
              </el-select>
              <el-tooltip placement="top-start" effect="light">
                <template #content>
                  <span>支持大写字母/小写字符/数字/特殊符号</span>
                  <br />
                  <span>密码长度应至少8位字符</span>
                  <br />
                  <span>弱：包含两种或两种以下的组合。</span>
                  <br />
                  <span>中：包含三种的组合。</span>
                  <br />
                  <span>强：包含四种的组合。</span>
                </template>
                <div class="tip-image"></div>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="是否强制修改" prop="force_update_state">
              <bg-switch
                :labels="['否', '是']"
                :values="[0, 1]"
                v-model="secureFormData.force_update_state"></bg-switch>
            </el-form-item>
          </div>
          <el-form-item label="密码有效期" prop="pwd_validity">
            <el-input placeholder="请输入" v-model.number="secureFormData.pwd_validity">
              <template #append>天</template>
            </el-input>
            <el-tooltip placement="top-start" effect="light">
              <template #content>
                <span>单位，天</span>
                <br />
                <span>密码有效期是指强制修改密码的周期，例如60天表示用户需要每60天修改一次密码。</span>
                <br />
                <span>若配置为0，表示密码有效期为永久</span>
              </template>
              <div class="tip-image"></div>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="会话有效期" prop="session_validity">
            <el-input placeholder="请输入" v-model.number="secureFormData.session_validity">
              <template #append>分钟</template>
            </el-input>
            <el-tooltip placement="top-start" effect="light">
              <template #content>
                <span>范围（10~30）</span>
                <br />
                <span>单位，分钟</span>
                <br />
                <span>会话有效期是指您登录后，一定时间内无操作，系统将自动登出</span>
              </template>
              <div class="tip-image"></div>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="访问规则模式" prop="access_rule_state">
            <el-select placeholder="请选择" v-model="secureFormData.access_rule_state">
              <el-option label="关闭" :value="0"> </el-option>
              <el-option label="打开" :value="1"> </el-option>
            </el-select>
            <el-tooltip placement="top-start" effect="light">
              <template #content>
                <span>访问规则模式开启后，按照【访问规则管理】配置执行。</span>
                <br />
                <span>该模式针对超管无效</span>
              </template>
              <div class="tip-image"></div>
            </el-tooltip>
          </el-form-item>
        </el-form>
        <!-- 登录注册配置表单 -->
        <el-form
          v-if="activeIndex == 3"
          ref="registerFormRef"
          :model="registerFormData"
          :rules="registerRules"
          label-width="125px"
          class="registerForm">
          <bg-form-gap title="登录受限配置"></bg-form-gap>
          <el-form-item label="登录受限是否启用" prop="login_config_state">
            <bg-switch
              :labels="['否', '是']"
              :values="[0, 1]"
              v-model="registerFormData.login_config_state"></bg-switch>
          </el-form-item>
          <div class="input_password_config" v-if="registerFormData.login_config_state == 1">
            <span>在</span>
            <el-form-item prop="login_limit_time" label-width="0">
              <el-input placeholder="请输入小时数" v-model.number="registerFormData.login_limit_time"></el-input>
            </el-form-item>
            <span>小时内</span>
            <el-form-item prop="login_pwd_error" label-width="0">
              <el-input placeholder="请输入密码输错次数" v-model.number="registerFormData.login_pwd_error"></el-input>
            </el-form-item>
            <span>次输错密码，自动锁定</span>
            <el-form-item prop="login_lock_time" label-width="0">
              <el-input placeholder="请输入分钟数" v-model.number="registerFormData.login_lock_time"></el-input>
            </el-form-item>
            <span>分钟</span>
            <el-button type="primary" @click="restoreLimited">一键还原受限</el-button>
          </div>
          <bg-form-gap title="注册配置"></bg-form-gap>
          <el-form-item label="允许注册" prop="register_config_state">
            <el-radio-group v-model="registerFormData.register_config_state">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="operate_btns">
          <el-button type="primary" @click="save"> 保存 </el-button>
        </div>
      </div>
    </div>
    <el-dialog
      class="dialog_box"
      title="提示"
      v-model="restoreDialog"
      width="420px">
      <div>该操作将还原所有锁定账号和输错次数，是否继续？</div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="restoreDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, toRefs, onBeforeMount, ref } from "vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
const check_time = (rule, value, callback) => {
  let reg = /^(0|[1-9][0-9]*)$/;
  setTimeout(() => {
    if (!reg.test(value)) {
      callback(new Error("请输入0到90以内的整数且不能以0开头"));
    } else if (value > 90) {
      callback(new Error("请输入0到90以内的整数且不能以0开头"));
    } else {
      callback();
    }
  });
};
const check_valid_time = (rule, value, callback) => {
  let reg = /^(0|[1-9][0-9]*)$/;
  setTimeout(() => {
    if (!reg.test(value)) {
      callback(new Error("请输入整数且不能以0开头"));
    } else {
      callback();
    }
  });
};
const check_value = (rule, value, callback) => {
  let reg = /^([1-9][0-9]*)$/;
  setTimeout(() => {
    if (!reg.test(value)) {
      callback(new Error("请输入正整数"));
    } else {
      callback();
    }
  });
};
const authorizeFormRef = ref(null);
const secureFormRef = ref(null);
const registerFormRef = ref(null);
const state = reactive({
  //授权信息表单
  authorizeFormData: {
    id: "",
    system_version: "",
    system_user: "",
    license: "",
    license_dead_date: "",
    license_inform_day: "",
  },
  //授权表单校验规则
  authorizeRules: {
    license_inform_day: [{ validator: check_time, trigger: "blur" }],
  },

  //安全相关信息表单
  secureFormData: {
    id: "",
    min_pwd_level: "",
    force_update_state: 0,
    pwd_validity: "",
    session_validity: "",
    access_rule_state: "",
  },

  //安全相关表单校验规则
  secureRules: {
    pwd_validity: [
      {
        validator: check_valid_time,
        trigger: "blur",
      },
    ],
    session_validity: [
      {
        validator: (rule, value, callback) => {
          if (value >= 10 && value <= 30) {
            callback();
          } else {
            callback(new Error("请输入正整数，且会话有效期范围为10分钟至30分钟"));
          }
        },
        trigger: "blur",
      },
    ],
  },
  //登录注册配置表单
  registerFormData: {
    id: "",
    login_config_state: 0,
    login_limit_time: "",
    login_pwd_error: "",
    login_lock_time: "",
    register_config_state: 0,
  },
  //登录注册配置表单校验规则
  registerRules: {
    login_limit_time: [
      {
        validator: check_value,
        trigger: "blur",
      },
    ],
    login_pwd_error: [
      {
        validator: check_value,
        trigger: "blur",
      },
    ],
    login_lock_time: [
      {
        validator: check_value,
        trigger: "blur",
      },
    ],
  },
  //选中项索引
  activeIndex: 1,
  restoreDialog: false,
});
const {
  authorizeFormData,
  authorizeRules,
  secureFormData,
  secureRules,
  registerFormData,
  registerRules,
  activeIndex,
  restoreDialog,
} = toRefs(state);
onBeforeMount(() => {
  getPreferenceConfig();
});
//切换菜单选项
const switchMenu = (index) => {
  state.activeIndex = index;
};
//获取首选项配置
const getPreferenceConfig = () => {
  axios.get("/apaas/system/v5/sysOptions").then((res) => {
    if (res.data.code == 200) {
      let data = res.data.data;
      Object.keys(state.authorizeFormData).forEach((item) => {
        state.authorizeFormData[item] = data[item];
      });
      Object.keys(state.secureFormData).forEach((item) => {
        state.secureFormData[item] = data[item];
      });
      Object.keys(state.registerFormData).forEach((item) => {
        state.registerFormData[item] = data[item];
      });
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
//保存表单项
const save = () => {
  let params = {};
  if (state.activeIndex == 1) {
    authorizeFormRef.value.validate((valid) => {
      if (valid) {
        params = {
          ...state.authorizeFormData,
        };
        postData("/apaas/system/v5/sysOptions/licenseOpts", params);
      } else {
        ElMessage.error("请先将表单填写完整");
      }
    });
  } else if (state.activeIndex == 2) {
    secureFormRef.value.validate((valid) => {
      if (valid) {
        params = {
          ...state.secureFormData,
        };
        postData("/apaas/system/v5/sysOptions/safeOpts", params);
      } else {
        ElMessage.error("请先将表单填写完整");
      }
    });
  } else {
    registerFormRef.value.validate((valid) => {
      if (valid) {
        params = {
          ...state.registerFormData,
        };
        if (params.login_config_state == 0) {
          params.login_limit_time = 0;
          params.login_pwd_error = 0;
          params.login_lock_time = 0;
        }
        postData("/apaas/system/v5/sysOptions/loginOpts", params);
      } else {
        ElMessage.error("请先将表单填写完整");
      }
    });
  }
};
// 请求接口发送消息
const postData = (url, params) => {
  axios.post(url, params).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      getPreferenceConfig();
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

// 一键还原受限
const restoreLimited = () => {
  state.restoreDialog = true
}

const confirm = () => {
  axios.post(`/apaas/system/v5/sysOptions/reStartConfig`).then(res => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg)
      state.restoreDialog = false
    }else {
      ElMessage.error(res.data.data)
    }
  })
}
</script>

<style lang="scss" scoped>
.parent_container {
  display: flex;
  justify-content: space-between;
  height: calc(100% - 46px - 20px);
  .left_container {
    width: 240px;
    height: 100%;
    padding: 24px 16px 0;
    .el-menu {
      border: none;
      .el-menu-item {
        justify-content: center;
        height: 36px;
        color: #404a62 !important;
        &.is-active,
        &:hover {
          background-color: #f2f3f7;
          border-radius: 4px;
        }
      }
    }
  }
  .right_container {
    position: relative;
    width: calc(100% - 256px);
    height: 100%;
    padding: 32px 0 68px 24px;

    .authorizeForm,
    .secureForm,
    .registerForm {
      :deep() .el-form-item {
        margin-bottom: 24px;
        width: 750px;
        font-size: 14px;
        .el-form-item__label,
        .el-radio__label {
          color: var(--el-text-color-primary);
        }
        .el-select {
          width: 100%;
        }
        .el-input-group__append {
          width: 60px;
          color: #404a62;
          border-radius: 0 6px 6px 0;
          background: #f7f7f9;
        }
      }
    }
    .secureForm {
      .passwordItem {
        display: flex;
        align-items: center;
        .el-form-item:nth-of-type(1) {
          flex-shrink: 0;
          margin-right: 56px;
        }
      }
    }

    .registerForm {
      .input_password_config {
        position: relative;
        display: flex;
        align-items: center;
        width: 798px;
        margin-bottom: 24px;
        font-size: 14px;
        color: var(--el-text-color-primary);
        .el-form-item {
          margin: 0px 8px;
          &:nth-of-type(1),
          &:nth-of-type(3) {
            width: 120px;
          }
          &:nth-of-type(2) {
            width: 150px;
          }
        }
        .el-button {
          margin-left: 18px;
        }
      }
      .el-radio {
        margin-right: 54px;
      }
    }

    .operate_btns {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 68px;
      padding-right: 16px;
      line-height: 68px;
      text-align: right;
      border-top: solid 1px #e6e9ef;
      .el-button {
        width: 92px;
      }
    }
  }
}
</style>
