<template>
  <div class="page_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <bg-filter-group
        @search="changeSearch"
        v-model="filter.search"
        placeholder="请输入规则名称或规则">
        <template v-slot:left_action>
          <div class="apaas_button">
            <el-button type="primary" @click="addRule">
              <bg-icon
                style="font-size: 12px; color: #fff; margin-right: 8px"
                icon="#bg-ic-add"></bg-icon>
              新增
            </el-button>
            <el-button @click="openDeleteDialog(2)"> 批量删除 </el-button>
            <span class="sleceted_tip"
              >已选<span class="num">{{ selectedNum }}</span
              >项</span
            >
            <span class="clean" @click="cleanSelected">清空</span>
          </div>
        </template>

        <template v-slot:filter_group>
          <div class="left-filter filter_list">
            <div class="filter_item">
              <span class="filter_title">修改时间</span>
              <el-date-picker
                v-model="filter.time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 300px" />
            </div>
          </div>
          <div class="right-action apaas_button">
            <el-button type="primary" @click="filterAction"> 查询 </el-button>
            <el-button type="default" @click="filterClear"> 重置 </el-button>
          </div>
        </template>
      </bg-filter-group>
      <div class="table_container">
        <bg-table
          ref="rulesTable"
          :headers="headers"
          :rows="tableRows"
          :stripe="true"
          select
          @selectAc="selectRows"
          canEdit
          canEditFlag="state">
          <template v-slot:rule_type="{ row }">
            <span>{{ ["", "IP"][row.rule_type] }}</span>
          </template>
          <template v-slot:num_user="{ row }">
            <span class="can_click_text under_line" @click="openUserDialog(row)">{{
              row.num_user
            }}</span>
          </template>
          <template v-slot:state="{ row }">
            <bg-switch
              @click="stateChange(row)"
              :labels="['否', '是']"
              :values="[0, 1]"
              v-model="row.state"></bg-switch>
          </template>

          <template v-slot:updated_time="{ row }">
            <span>{{ dateStringTransform(row.updated_time) }}</span>
          </template>
          <template v-slot:action="{ row }">
            <bg-table-btns2 :limit="3" :key="row.id">
              <bg-table-btn @click="edit(row)">编辑</bg-table-btn>
              <bg-table-btn :disabled="row.state == 1" @click="openDeleteDialog(1, row)"
                >删除</bg-table-btn
              >
            </bg-table-btns2>
          </template>
        </bg-table>
        <bg-pagination
          :page="filter.page"
          :size="filter.limit"
          :total="tableTotal"
          @change-page="changePage"
          @change-size="changeSize">
        </bg-pagination>
      </div>
    </div>

    <el-dialog class="dialog_box_detail" title="用户详情" v-model="dialogDetail" width="1062px">
      <div class="content_detail">
        <div class="form_filter">
          <div class="left">
            <el-select
              v-model="userFilter.isAdmin"
              placeholder="请选择"
              style="width: 200px; margin-left: 16px">
              <el-option
                v-for="(item, index) in userTypeList"
                :key="'pushOptions' + index"
                :label="item.name"
                :value="item.value">
              </el-option>
            </el-select>
            <el-cascader
              v-model="userFilter.organizationId"
              :options="orgList"
              placeholder="请选择组织"
              :props="{
                expandTrigger: 'hover',
                label: 'name',
                value: 'organization_id',
                emitPath: false,
                checkStrictly: true,
                children: 'Child',
              }"
              :clearable="true"
              collapse-tags
              style="width: 200px; margin-left: 16px">
              <template #default="{ data }">
                <span>{{ data.name }}</span>
              </template>
            </el-cascader>
            <el-input
              placeholder="请输入关键词"
              v-model.trim="userFilter.search"
              style="width: 200px; margin-left: 16px"
              :prefix-icon="Search" />
          </div>
          <div class="right">
            <el-button type="primary" @click="searchUsers">查询</el-button>
            <el-button type="default" @click="clearAction">重置</el-button>
          </div>
        </div>

        <div class="table_content">
          <bg-table
            ref="bgUserTable"
            :headers="userHeaders"
            :rows="userTableRows"
            height="430"
            :stripe="true">
            <template v-slot:isAdmin="{ row }">
              <span>{{ ["", "业务系统用户", "组织管理员", "平台用户"][row.isAdmin] }}</span>
            </template>
          </bg-table>
          <bg-pagination
            :page="userFilter.page"
            :size="userFilter.limit"
            :total="userTableTotal"
            @change-page="changeUserPage"
            @change-size="changeUserSize">
          </bg-pagination>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      class="dialog_box"
      :title="deleteDialogConfig.title"
      v-model="dialogDelete"
      width="400px">
      <div style="text-align: center">
        {{ deleteDialogConfig.tips }}
      </div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="dialogDelete = false">取 消</el-button>
          <el-button type="primary" @click="confimDelete">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

const router = useRouter();

const rulesTable = ref(null);
const state = reactive({
  filter: {
    search: "",
    page: 1,
    limit: 10,
    time: [],
  },
  headers: [
    {
      label: "规则名称",
      prop: "rule_name",
    },
    {
      label: "规则类型",
      prop: "rule_type",
    },
    {
      label: "用户数量",
      prop: "num_user",
    },
    {
      label: "规则",
      prop: "rule_detail",
    },
    {
      label: "是否启用",
      prop: "state",
    },
    {
      label: "修改时间",
      prop: "updated_time",
      width: 240,
    },
    {
      label: "操作",
      prop: "action",
      width: 120,
      fixed: "right",
    },
  ],
  tableRows: [],
  tableTotal: 0,
  selectedNum: 0,
  actionRow: {},
  dialogDetail: false,
  userFilter: {
    page: 1,
    limit: 10,
    search: "",
    isAdmin: "",
    organizationId: "",
    disp: 0,
  },
  userTypeList: [
    {
      name: "全部类型",
      value: "",
    },
    {
      name: "业务系统用户",
      value: 1,
    },
    {
      name: "组织管理员",
      value: 2,
    },
    {
      name: "平台用户",
      value: 3,
    },
  ],
  orgList: [],
  userHeaders: [
    {
      label: "账号",
      prop: "systemAccount",
    },
    {
      label: "类型",
      prop: "isAdmin",
    },
    {
      label: "用户手机号",
      prop: "phone",
    },
    {
      label: "所属组织",
      prop: "name",
    },
  ],
  userTableRows: [],
  userTableTotal: 0,
  selection: [],
  dialogDelete: false,
  deleteDialogConfig: {
    title: "删除",
    ruleId: [],
    tips: "确定要删除当前行数据吗？",
  },
});

const getOrgList = () => {
  axios.get(`/apaas/system/v5/org/tree`).then((res) => {
    if (res.data.code == 200) {
      state.orgList = res.data.data || [];
    } else {
      ElMessage.error(res.data.data);
    }
  });
}; // 获取组织

const changeSearch = (val) => {
  state.filter.search = val;
  changePage(1);
}; // 关键字
const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
}; // 改变页码
const changeSize = (size) => {
  state.filter.limit = size;
  changePage(1);
}; // 改变每页条数
const filterAction = () => {
  changePage(1);
}; // 高级搜索中查询
const filterClear = () => {
  state.filter = {
    search: "",
    page: 1,
    limit: 10,
    time: [],
  };
  changePage(1);
}; // 高级搜索中重置
const getTableRows = () => {
  let params = { ...state.filter };
  params.updatedTimeFrom = params.time ? params.time[0] || "" : "";
  params.updatedTimeTo = params.time ? params.time[1] || "" : "";
  delete params.time;
  axios
    .get(`/apaas/system/v5/accessRule/listAccessRule`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        state.tableRows = res.data.data || [];
        state.tableTotal = res.data.total;
      } else {
        ElMessage.error(res.data.data);
      }
    });
}; // 获取表格数据

const selectRows = (data) => {
  state.selectedNum = data.allLength;
  state.selection = data.selection;
};

// 新增规则跳转
const addRule = () => {
  router.push("/config/accessRule/add");
};

const cleanSelected = () => {
  rulesTable.value.clearTable();
}; //清空

// 改变规则状态
const stateChange = (row) => {
  axios
    .put(`/apaas/system/v5/accessRule/updateState?id=${row.id}&state=${row.state}`)
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        changePage(1);
      } else {
        ElMessage.error(res.data.data);
        row.state = row.state == 0 ? 1 : 0;
      }
    });
};

// 打开用户弹窗
const openUserDialog = (row) => {
  state.dialogDetail = true;
  state.actionRow = row;
  clearAction();
};

const searchUsers = () => {
  changeUserPage(1);
}; // 用户弹窗查询

// 用户弹窗重置
const clearAction = () => {
  state.userFilter = {
    page: 1,
    limit: 10,
    search: "",
    isAdmin: "",
    organizationId: "",
    disp: 0,
  };
  changeUserPage(1);
};

// 用户详情改变分页
const changeUserPage = (page) => {
  state.userFilter.page = page;
  getUserTableRows();
};

const changeUserSize = (size) => {
  state.userFilter.limit = size;
  changeUserPage(1);
};

// 用户详情弹窗数据
const getUserTableRows = () => {
  let params = {
    ...state.userFilter,
    id: state.actionRow.id,
  };
  axios.get(`/apaas/system/v5/accessRule/listRuleUser`, { params }).then((res) => {
    if (res.data.code == 200) {
      state.userTableRows = res.data.data || [];
      state.userTableTotal = res.data.total;
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const edit = (row) => {
  router.push({
    path: "/config/accessRule/edit",
    query: {
      id: row.id,
      ruleId: row.rule_id,
      ruleName: row.rule_name,
      state: row.state,
      ruleType: row.rule_type,
      ruleDetail: row.rule_detail,
    },
  });
}; //编辑

//打开删除弹窗
const openDeleteDialog = (type, row) => {
  if (type === 2) {
    const res = rulesTable.value.dealSelectData();
    const list = Object.values(res);
    if (list.length === 0) return ElMessage.warning("请选择要删除的数据");
    state.dialogDelete = true;
    const ruleId = list.map((item) => item.rule_id);
    state.deleteDialogConfig = { title: "批量删除", ruleId, tips: "确定要删除所选数据吗？" };
    return;
  }
  state.dialogDelete = true;
  state.deleteDialogConfig = {
    title: "删除",
    ruleId: [row.rule_id],
    tips: "确定要删除当前行数据吗？",
  };
};
//确定删除
const confimDelete = () => {
  axios
    .delete("/apaas/system/v5/accessRule/delAccessRule", {
      data: {
        ruleId: state.deleteDialogConfig.ruleId,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("删除成功");
        changePage(1);
      } else {
        ElMessage.error(res.data.data);
      }
    })
    .finally(() => {
      state.dialogDelete = false;
    });
};

const {
  filter,
  headers,
  userHeaders,
  tableRows,
  tableTotal,
  selectedNum,
  dialogDetail,
  userTableRows,
  userTableTotal,
  userFilter,
  userTypeList,
  orgList,
  selection,
  dialogDelete,
  deleteDialogConfig,
} = toRefs(state);

onBeforeMount(() => {
  getTableRows();
  getOrgList();
});
</script>

<style lang="scss" scoped>
.page_container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  width: 100%;
  padding: 0 24px;
  min-height: 100%;
  .main_container {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    flex-grow: 1;
    width: 100%;
    background-color: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0, 7, 101, 0.15);
    border-radius: 6px;
    padding: 0 0 16px 0;
    margin-bottom: 16px;
    position: relative;
    .sleceted_tip {
      margin: 0 24px 0 40px;
      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;
    }
    .filter-group {
      .left-filter {
        flex: 1;
        display: flex;
        justify-content: start;
        flex-wrap: wrap;
        .filter_item {
          display: flex;
          align-items: center;
          .filter_title {
            width: 84px;
            white-space: pre-wrap;
            font-weight: normal;
          }
        }
      }
      .right-action {
        width: 144px;
        padding-bottom: 16px;
        .el-button {
          width: 64px;
        }
      }
    }
    .table_container {
      padding: 0 16px;
      .el-table {
        flex: 1;
        .under_line {
          text-decoration: underline;
        }
      }
    }
  }

  :deep() .dialog_box_detail {
    .el-dialog__body {
      padding: 0 0 18px 0;
      height: 580px;
    }

    .form_filter {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 69px;
      border-bottom: 1px solid #e6e9ef;
      .right {
        margin-right: 16px;
        .el-button {
          width: 64px;
          &:last-child {
            margin-left: 16px;
          }
        }
      }
    }
    .table_content {
      padding: 0 16px;
    }
  }
}
</style>
