<!-- 角色管理 -->
<template>
  <div class="page_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <div class="form_content apaas_scroll_nor">
        <el-form
          ref="refForm"
          label-position="left"
          :model="formData"
          :rules="rules"
          label-width="82px">
          <div class="top_content">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input placeholder="请输入" maxlength="100" v-model="formData.ruleName"></el-input>
            </el-form-item>
            <el-form-item label="规则类型" prop="ruleType">
              <el-select placeholder="请选择" style="width: 100%" v-model="formData.ruleType">
                <el-option label="IP" :value="1"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="规则" prop="ruleDetail">
              <el-input
                placeholder="请输入"
                rows="5"
                maxlength="300"
                show-word-limit
                type="textarea"
                v-model="formData.ruleDetail" />
              <el-tooltip placement="top-start" effect="light">
                <template #content>
                  <span>输入IP段，不可重复，例如：192.168.0.0/24</span><br />
                  <span
                    >输入IP地址，例如192.168.0.1（支持ipv4地址，配置多个IP时使用回车符分隔）</span
                  >
                </template>
                <div class="tip-image"></div>
              </el-tooltip>
            </el-form-item>
            <el-form-item class="switch-item" label="是否启用" prop="state" required>
              <bg-switch
                :labels="['否', '是']"
                :values="[0, 1]"
                v-model="formData.state"></bg-switch>
            </el-form-item>
          </div>
          <el-form-item class="userScope" label="用户范围" prop="userScope">
            <el-button type="primary" @click="userMaintain"> 用户维护 </el-button>
            <div class="table_content clearfix">
              <bg-table
                ref="bgTable"
                :headers="detailHeaders"
                :rows="tableRows"
                height="550"
                :stripe="true">
                <template v-slot:isAdmin="{ row }">
                  <span>{{ userTypeConfig[row.isAdmin] }}</span>
                </template>
              </bg-table>
              <bg-pagination
                :page="pageConfig.page"
                :size="pageConfig.limit"
                :total="pageConfig.total"
                @change-page="changePage"
                @change-size="changeSize">
              </bg-pagination>
            </div>
          </el-form-item>
        </el-form>
        <el-dialog
          class="dialog_box_maintain"
          title="用户维护"
          v-model="dialogMaintain"
          width="1062px">
          <div class="content_detail">
            <div class="form_filter">
              <div class="left">
                <span class="sleceted_tip"
                  >已选择<span class="num">{{ selectedNum }}</span
                  >项</span
                >
                <span class="clean" @click="cleanSelected">清空</span>
              </div>
              <div class="right">
                <el-select
                  placeholder="全部类型"
                  v-model="dialogFilterData.isAdmin"
                  style="width: 200px; margin-left: 16px">
                  <el-option
                    v-for="option in userTypeList"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value">
                  </el-option>
                </el-select>
                <el-tree-select
                  style="width: 200px; margin-left: 16px"
                  placeholder="请选择所属组织"
                  v-model="dialogFilterData.organizationId"
                  :data="orgData"
                  :props="treeProps"
                  :render-after-expand="false"></el-tree-select>
                <el-input
                  placeholder="请输入关键词"
                  v-model="dialogFilterData.search"
                  style="width: 200px; margin: 0 16px 0"
                  :prefix-icon="Search" />
                <el-button type="primary" @click="dialogChangePage(1)">查询</el-button>
                <el-button type="default" @click="resetFilter">重置</el-button>
              </div>
            </div>

            <div class="table_content clearfix">
              <bg-table
                ref="dialogBgTable"
                height="430"
                select
                rowKey="systemId"
                :headers="detailHeaders"
                :rows="dialogTableRows"
                :stripe="true"
                @selectAc="selectChange">
                <template v-slot:isAdmin="{ row }">
                  <span>{{ userTypeConfig[row.isAdmin] }}</span>
                </template>
              </bg-table>
              <bg-pagination
                :page="dialogPageConfig.page"
                :size="dialogPageConfig.limit"
                :total="dialogPageConfig.total"
                @change-page="dialogChangePage"
                @change-size="dialogChangeSize">
              </bg-pagination>
            </div>
            <div class="operate_btns" style="border-top: none">
              <el-button @click="dialogMaintain = false"> 取消 </el-button>
              <el-button type="primary" @click="save"> 保存 </el-button>
            </div>
          </div>
        </el-dialog>
      </div>
      <div class="operate_btns">
        <el-button type="primary" @click="submit"> 保存 </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { reactive, toRefs, computed, ref, onBeforeMount, nextTick } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import axios from "../../../../../request/http.js";
import { ElMessage } from "element-plus";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";

const router = useRouter();

const { getters } = useStore();

const userTypeConfig = computed(() => getters.getUserTypeConfig || {});

const userTypeList = computed(() =>
  Object.keys(userTypeConfig.value).map((key) => ({
    label: userTypeConfig.value[key],
    value: +key,
  }))
);
const dialogBgTable = ref(null);
const state = reactive({
  //表单数据
  formData: {
    ruleName: "",
    ruleType: "",
    ruleDetail: "",
    state: 0,
    userScope: [],
  },
  //表单校验规则
  rules: {
    ruleName: [
      {
        required: true,
        message: "请输入",
        trigger: "blur",
      },
    ],
    ruleType: [
      {
        required: true,
        message: "请选择",
        trigger: "blur",
      },
    ],
    ruleDetail: [
      {
        required: true,
        message: "请输入",
        trigger: "blur",
      },
    ],
    userScope: [
      {
        required: true,
        message: "请选择",
        blur: "change",
      },
    ],
  },
  dialogFilterData: {
    isAdmin: "",
    organizationId: "",
    search: "",
  },
  pageConfig: {
    page: 1,
    limit: 10,
    total: 0,
  },
  //弹框中表格分页配置项
  dialogPageConfig: {
    page: 1,
    limit: 10,
    total: 0,
  },
  //表格数据
  tableRows: [],
  //被选中的所有数据
  selectedRows: {},
  //弹框中表格数据
  dialogTableRows: [],
  //已选择数据条数
  selectedNum: 0,
  detailHeaders: [
    {
      label: "账号",
      prop: "systemAccount",
      // minWidth: 280,
    },
    {
      label: "类型",
      prop: "isAdmin",
      // minWidth: 360,
    },
    {
      label: "用户手机号",
      prop: "phone",
      // width: 200,
    },
    {
      label: "所属组织",
      prop: "name",
      // width: 120,
    },
  ],
  orgData: [],
  treeProps: {
    label: "name",
    children: "Child",
    value: "organization_id",
  },
  //用户维护弹框
  dialogMaintain: false,
});
const {
  formData,
  rules,
  dialogFilterData,
  pageConfig,
  dialogPageConfig,
  tableRows,
  dialogTableRows,
  selectedNum,
  detailHeaders,
  orgData,
  treeProps,
  dialogMaintain,
} = toRefs(state);

onBeforeMount(() => {
  getOrgTree();
  getTableList();
});
//用户维护
const userMaintain = () => {
  state.dialogMaintain = true;
};
//获取所属组织级联数据
const getOrgTree = () => {
  axios.get(`/apaas/system/v5/org/tree`).then((res) => {
    if (res.data.code == 200) {
      const orgDataTemp = res.data.data || [];
      state.orgData = orgDataTemp;
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
const changePage = (page) => {
  state.pageConfig.page = page;
  state.tableRows = state.selectedRows.slice(
    (page - 1) * state.pageConfig.limit,
    page * state.pageConfig.limit
  );
};

const changeSize = (size) => {
  state.pageConfig.limit = size;
  changePage(1);
};
const dialogChangePage = (page) => {
  state.dialogPageConfig.page = page;
  getTableList();
};

const dialogChangeSize = (size) => {
  state.dialogPageConfig.limit = size;
  dialogChangePage(1);
};

//获取用户维护数据
const getTableList = () => {
  const params = {
    limit: state.dialogPageConfig.limit,
    page: state.dialogPageConfig.page,
    disp: 1,
    ...state.dialogFilterData,
  };
  axios.get("/apaas/system/v5/accessRule/listRuleUser", { params }).then((res) => {
    if (res.data.code == 200) {
      state.dialogTableRows = res.data.data || [];
      state.dialogPageConfig.total = res.data.total || 0;
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
//重置查询参数
const resetFilter = () => {
  Object.keys(state.dialogFilterData).forEach((key) => {
    state.dialogFilterData[key] = "";
  });
  dialogChangePage(1);
};
//用户维护弹框中清空
const cleanSelected = () => {
  dialogBgTable.value.clearTable();
};
//用户维护选择项发生变化
const selectChange = (params) => {
  state.selectedNum = params.allLength;
};
//保存
const save = () => {
  state.dialogMaintain = false;
  const res = dialogBgTable.value.dealSelectData();
  state.selectedRows = Object.values(res);
  state.formData.userScope = state.selectedRows.map((item) => ({
    systemId: item.systemId,
  }));
  state.pageConfig.total = state.formData.userScope.length;
  changePage(1);
};
//提交
const submit = () => {
  axios.post("/apaas/system/v5/accessRule/addAccessRule", state.formData).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      router.push("/config/accessRule");
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
</script>

<style lang="scss" scoped>
.page_container {
  .main_container {
    position: relative;
    margin: 0 0 16px;
    width: 100%;
    height: calc(100% - 62px);
    padding: 40px 0 70px;
    overflow: auto;
    background-color: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
    border-radius: 6px;
    .form_content {
      overflow: auto;
      height: 100%;
      padding-left: 40px;
      .el-form {
        ::v-deep .el-form-item {
          display: block;
          margin-bottom: 24px;
          width: 60%;
          .el-form-item__label {
            display: block;
            margin-bottom: 6px;
            height: 14px;
            line-height: 14px;
          }
          &.switch-item {
            display: flex;
            align-items: center;
            .el-form-item__label {
              display: inline-flex;
              margin-bottom: 0px;
            }
            .el-switch {
              height: 24px;
            }
          }
          &.userScope {
            width: 100%;
            margin-bottom: 16px;

            .el-button {
              width: 92px;
            }
            .el-form-item__label {
              margin-bottom: 16px;
            }
            .el-form-item__content {
              display: block;
            }
            .table_content {
              padding-right: 40px;
              margin-top: 16px;
            }
          }
        }
      }
    }

    ::v-deep .dialog_box_maintain {
      .el-dialog__body {
        padding: 0 0 70px 0;
        height: 630px;
      }

      .form_filter {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        height: 69px;
        border-bottom: 1px solid #e6e9ef;
        .left {
          font-size: 0px;
          .sleceted_tip {
            margin: 0 24px 0;
            vertical-align: middle;
            font-size: 14px;
            color: #404a62;
            .num {
              margin: 0 3px 0 3px;
              font-weight: 600;
              color: #202531;
            }
          }
          .clean {
            vertical-align: middle;
            font-size: 14px;
            color: #3759be;
            cursor: pointer;
          }
        }
        .right {
          margin-right: 16px;
          .el-button {
            width: 64px;
            &:last-child {
              margin-left: 16px;
            }
          }
        }
      }
      .table_content {
        padding: 0 16px;
      }
      .operate_btns {
        .el-button {
          width: 64px;
          &:first-child {
            margin-right: 4px;
          }
        }
      }
    }
    .operate_btns {
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 70px;
      text-align: right;
      line-height: 68px;
      border-top: solid 1px #e6e9ef;
      .el-button {
        width: 92px;
        margin-right: 16px;
      }
    }
  }
}
</style>
