<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="exportFile">
              <bg-icon
                style="font-size: 12px; color: #fff; margin-right: 8px"
                icon="#bg-ic-file-send"></bg-icon>
              导出
            </el-button>
            <el-button @click="deleteBatch"> 批量删除 </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-select v-model="filter.is_admin" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in userTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <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 class="filter_item">
              <span class="filter_title">操作类型</span>
              <el-select v-model="filter.operate_type" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in operateTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">请求方式</span>
              <el-select v-model="filter.req_method" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in reqMethodList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="filter_item">
              <span class="filter_title">操作状态</span>
              <el-select v-model="filter.operate_status" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in operateStatusList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </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="userTable"
          :headers="headers"
          :rows="tableRows"
          :stripe="true"
          select
          @selectAc="selectChange">
          <template v-slot:is_admin="{ row }">
            <span>{{ userTypeConfig[row.is_admin] }}</span>
          </template>
          <template v-slot:req_method="{ row }"
            ><span>{{ filterReqMethod(row.req_method) }}</span></template
          >
          <template v-slot:operate_status="{ row }">{{
            filterOperateStatus(row.req_method)
          }}</template>
          <template v-slot:action="{ row }">
            <bg-table-btns2 :limit="3" :key="row.id">
              <bg-table-btn @click="goDetail(row)">详情</bg-table-btn>
              <bg-table-btn @click="deleteCurrent(row)">删除</bg-table-btn>
            </bg-table-btns2>
          </template>
        </bg-table>
        <bg-pagination
          :page="filter.page"
          :size="filter.limit"
          :total="filter.total"
          @change-page="changePage"
          @change-size="changeSize">
        </bg-pagination>
      </div>
    </div>

    <el-dialog class="dialog_box" title="提示" v-model="deleteDialog" width="400px">
      <div style="font-size: 16px; color: #404a62">{{ deleteTips }}</div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="deleteDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

const { getters } = useStore();
const router = useRouter();

const userTable = ref(null);
const userTypeConfig = computed(() => getters.getUserTypeConfig || {});
const userTypeList = computed(() => {
  const temp = getters.getUserTypeConfig || {};
  return Object.keys(temp).map((key) => ({
    label: temp[key],
    value: +key,
  }));
});
const state = reactive({
  filter: {
    search: "",
    is_admin: "",
    time: [],
    operate_type: "",
    req_method: "",
    operate_status: "",
    page: 1,
    limit: 10,
    total: 0,
  },
  operateStatusList: [
    { label: "全部", value: "" },
    { label: "成功", value: 1 },
    { label: "失败", value: 2 },
  ],

  headers: [
    {
      label: "账号",
      prop: "system_account",
      // minWidth: 280,
    },
    {
      label: "用户类型",
      prop: "is_admin",
      // minWidth: 360,
    },
    {
      label: "系统模块",
      prop: "system_module",
      // width: 200,
    },
    {
      label: "操作类型",
      prop: "operate_type",
      // width: 120,
    },
    {
      label: "请求方式",
      prop: "req_method",
      // width: 120,
    },
    {
      label: "操作状态",
      prop: "operate_status",
      // width: 240,
    },
    {
      label: "操作地点",
      prop: "operate_addr",
      // width: 240,
    },
    {
      label: "操作时间",
      prop: "created_time",
      // width: 240,
    },
    {
      label: "操作",
      prop: "action",
      width: 120,
    },
  ],
  //选中数量
  selectedNum: 0,
  detailHeaders: [
    {
      label: "账号",
      prop: "ability_name",
      // minWidth: 280,
    },
    {
      label: "类型",
      prop: "synopsis",
      // minWidth: 360,
    },
    {
      label: "用户手机号",
      prop: "created_time",
      // width: 200,
    },
    {
      label: "所属组织",
      prop: "ability_state",
      // width: 120,
    },
  ],
  tableRows: [],
  tableTotal: 0,
  //选中项
  selectedRows: [],
  actionRow: {},
  dialogDetail: false,
  deleteDialog: false,
  deleteTips: "",
});

const { filter, operateStatusList, headers, selectedNum, tableRows, deleteDialog, deleteTips } =
  toRefs(state);
//导出
const exportFile = () => {
  let params = { ...state.filter };
  params.start_at = params.time ? params.time[0] || "" : "";
  params.end_at = params.time ? params.time[1] || "" : "";
  delete params.time;
  delete params.total;
  axios
    .get(`/apaas/system/v5/log/userBehavior/list/export`, {
      params,
      responseType: "blob",
    })
    .then((res) => {
      if (res.status === 200) {
        const type =
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
        downloadBlob(res.data, type);
      } else {
        ElMessage.error(res.statusText);
      }
    });
};
//请求方式过滤器
const filterReqMethod = (value) => {
  const findItem = reqMethodList.find((item) => item.value === value);
  return (findItem || {}).label;
};
//操作状态过滤器
const filterOperateStatus = (value) => {
  const findItem = operateTypeList.find((item) => item.value === value);
  return (findItem || {}).label;
};
//选择项发生变化
const selectChange = (params) => {
  state.selectedNum = params.allLength;
};
//批量删除
const deleteBatch = () => {
  state.selectedRows = [];
  const selectedObj = userTable.value.dealSelectData();
  state.selectedRows = Object.values(selectedObj);
  if (!state.selectedRows.length) return ElMessage.warning("请先选择删除项");
  state.deleteTips = "确定要删除选中项吗？";
  state.deleteDialog = true;
};
//删除当前行
const deleteCurrent = (row) => {
  state.selectedRows = [row];
  state.deleteTips = "确定要删除当前行吗？";
  state.deleteDialog = true;
};
//确定删除
const confirmDelete = () => {
  const ids = state.selectedRows.map((item) => item.id);
  axios
    .delete(`/apaas/system/v5/log/userBehavior/delete?ids=${ids.join(",")}`)
    .then((res) => {
      if (res.data.code === 200) {
        ElMessage.success(res.data.data);
        cleanSelected();
        getTableRows();
      } else {
        ElMessage.error(res.data.data);
      }
    })
    .finally(() => {
      state.deleteDialog = false;
    });
};
//清空
const cleanSelected = () => {
  userTable.value.clearTable();
};
const changeSearch = (val) => {
  state.filter.search = val;
  changePage(1);
};
const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
};
const getTableRows = () => {
  let params = { ...state.filter };
  params.start_at = params.time ? params.time[0] || "" : "";
  params.end_at = params.time ? params.time[1] || "" : "";
  delete params.time;
  axios
    .get(`/apaas/system/v5/log/userBehavior/list`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        state.tableRows = res.data.data || [];
        state.filter.total = res.data.total;
      } else {
        ElMessage.error(res.data.data);
      }
    });
};
const filterAction = () => {
  changePage(1);
};
const changeSize = (size) => {
  state.filter.limit = size;
  changePage(1);
};
const filterClear = () => {
  state.filter = {
    search: "",
    is_admin: "",
    time: [],
    operate_type: "",
    req_method: "",
    operate_status: "",
    page: 1,
    limit: 10,
    total: 0,
  };
  changePage(1);
};

const goDetail = (row) => {
  router.push({
    path: "/log/userBehavior/detail",
    query: {
      id: row.id,
    },
  });
};
onBeforeMount(() => {
  getTableRows();
});
</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;
        .circle {
          display: inline-block;
          width: 6px;
          height: 6px;
          border-radius: 3px;
          margin-right: 8px;
          transform: translateY(-2px);
        }
        .bgc_1 {
          background-color: #48ad97;
        }
        .bgc_2 {
          background-color: #d75138;
        }
        .bgc_3 {
          background-color: #3759be;
        }
        .bgc_4 {
          background-color: #ea7d19;
        }
        .bgc_0 {
          background-color: #9e9e9e;
        }
        .mock_tip {
          display: inline-block;
          margin-left: 4px;
          width: 43px;
          height: 20px;
          font-size: 12px;
          color: #2b4695;
          text-align: center;
          background-color: #eff2fa;
          border-radius: 3px;
          border: solid 1px #b0bee8;
        }
        :deep() td {
          padding: 9px 0 !important;
        }
        :deep() .el-switch {
          height: 20px;
          width: 44px;
          .el-switch__core {
            height: 20px;
            min-width: 44px;
          }
        }
      }
    }
  }

  :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>
