<template>
  <div>
    <div class="tree-box fl">
      <div class="tit"><b>{{ $t1('操作类型') }}</b></div>
      <el-tree
        :props="defaultProps"
        :load="loadNode"
        node-key="id"
        ref="tree"
        highlight-current
        lazy
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        class="tree-list"
        icon-class="el-icon-arrow-down"
      ></el-tree>
    </div>
    <label id="labBtn">
      <div class="icon">
        <i class="el-icon-more"></i>
        <i class="el-icon-more"></i>
      </div>
    </label>
    <div class="main-right fr" style="padding-left:6px;">
      <div class="grid-height">
        <template v-if="logType=='login'">
          <div class="statistics-box">
            <div class="name"><i class="el-icon-user-solid f-blue"></i>{{ $t1('登录成功') }}</div>
            <template>
              <block v-for="(item,index) in accessLogs" :key="index">
                <template v-if="item.flag!=='total'">
                  <div class="item">
                    <span v-html="$t1('{logDate}共有{number}人登录',{
                      logDate: `<span class='date-txt'>${item.logDate}</span>`,
                      number: `<span class='f-red'>${item.numbers}</span>`
                    })"></span>
                  </div>
                </template>
                <template v-else>
                  <div class="last">
                    <span v-html="$t1('合计：{startDate}至{endDate}共有{number}人登录',{
                      startDate: `<span class='d'>${item.startDate}</span>`,
                      endDate: `<span class='d'>${item.endDate}</span>`,
                      number: `<span class='f-red'>${item.numbers}</span>`
                    })"></span>
                  </div>
                </template>
              </block>
            </template>
          </div>
        </template>
        <vxe-grid v-show="logType!=='login'" ref="table-m1" v-bind="vxeOption"
                  @resizable-change="$vxeTableUtil.onColumnWitchChange"
                  @custom="$vxeTableUtil.customHandle">
          <template #form>
            <div class="clearfix screen-btns">
              <div class="fl">
              </div>
              <div class="fr">
                <vxe-button status="warning" icon="el-icon-search" class="button-sty" @click="searchEvent">
                  {{ $t1('搜索') }}
                </vxe-button>
              </div>
            </div>
            <vxe-form ref="form" class="screen-box" title-width="92px" title-align="right" :data="formData"
                      @submit="searchEvent" @reset="searchEvent">
              <vxe-form-item :title="$t1('访问日期')+':'">
                <template v-slot>
                  <el-date-picker
                    v-model="formData.startDate"
                    type="date"
                    placeholder=""
                    size="small"
                    clearable
                    value-format="yyyy-MM-dd"
                    :picker-options="$baseStartPickerOptions(formData.endDate)"
                  ></el-date-picker>
                  <span>-</span>
                  <el-date-picker
                    v-model="formData.endDate"
                    type="date"
                    placeholder=""
                    size="small"
                    clearable
                    value-format="yyyy-MM-dd"
                    :picker-options="$baseEndPickerOptions(formData.startDate)"
                  ></el-date-picker>
                  <el-button style="margin-left: 15px;" icon="el-icon-date" class="button-sty"
                             @click="checkDateButton(7)"
                             type="success"
                  >{{ $t1('近7天') }}
                  </el-button>
                  <el-button icon="el-icon-date" class="button-sty" @click="checkDateButton(30)"
                             type="success"
                  >{{ $t1('近30天') }}
                  </el-button>
                  <el-button icon="el-icon-date" class="button-sty" @click="checkDateButton(90)"
                             type="success"
                  >{{ $t1('近90天') }}
                  </el-button>
                </template>
              </vxe-form-item>
            </vxe-form>
          </template>
        </vxe-grid>
      </div>
    </div>
  </div>
</template>

<script>
import {treeScollx} from '@base/utils/global.js';
import moment from "moment"

export default {
  name: 'access_log:list',
  components: {},
  data() {
    return {
      activeName: 'second',
      dataId: 0,
      showEdit: false,
      vxeOption: {},
      formData: {
        startDate: null,
        endDate: null
      },
      checkNode: {},
      defaultProps: {
        label: 'label', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      showWfDialog: false,
      wfContentOption: {},
      showAdvancedSearch: false,
      advancedFormData: {},
      userLogTypeDictArr: [],
      userLogTypeDicMap: {},
      logType: "login",
      accessLogs: []
    };
  },
  computed: {
    checkNodeData() {
      return this.checkNode && this.checkNode.data ? this.checkNode.data : {};
    }
  },
  async mounted() {
    treeScollx({target: this, type: 'default'});
    this.initTableList();
  },
  methods: {
    doSearch() {
      if (this.logType == "login") {
        this.accessLogs = []
        this.$http({
          url: USER_PREFIX + '/access_log/accessStatistics',
          method: `post`,
          data: {
            logType: this.logType
          },
          isLoading: true,
          modalStrictly: true,
          success: res => {
            this.accessLogs = res.objx || [];
          }
        })
      } else {
        if (!this.formData.startDate || !this.formData.endDate) {
          this.$baseAlert(this.$t1('请选择访问日期'));
          return
        }
        this.$refs['table-m1'].commitProxy('reload');
      }
    },
    searchEvent() {
      this.doSearch();
    },
    resetEvent() {
      this.formData = {};
      this.doSearch();
    },
    openEditDialog(id) {
      this.dataId = !id || typeof id == 'object' ? 0 : id;
      this.activeName = 'first';
      this.$openEditView('showEdit');
    },
    initTableList() {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user_access_statistics_list-m1',
        path: USER_PREFIX + '/access_log/accessStatistics',
        param: () => {
          return {
            ...this.formData,
            logType: this.logType
            // ...checkParam
          };
        },
        config: {
          proxyConfig: {
            props: {
              result: "objx", // 配置响应结果列表字段
              total: "objx.length", // 配置响应结果总页数字段
            },
            autoLoad: false
          }
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('访问菜单名'),
            field: 'businessCode',
            width: 250,
            fixed: 'left',
          },
          {
            field: 'times',
            title: this.$t1('菜单访问总量'),
            width: 150
          },
          {
            field: 'numbers',
            title: this.$t1('菜单访问人数'),
            width: 150
          },
          {
            width: 47,
            fixed: 'right',
            title: '',
            sortable: false
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    handleNodeClick(data, node, v) {
      this.logType = data.value;
      this.checkNode = node;
      this.formData.startTime = null;
      this.formData.endTime = null;
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      let data = [
        {
          label: this.$t1('登录成功'),
          value: "login",
          id: 1,
          leaf: true
        },
        {
          label: this.$t1('访问菜单'),
          value: "accessMenu",
          id: 2,
          leaf: true
        }
      ]
      resolve(data);
      this.$nextTick(() => {
        if (node.childNodes.length) {
          this.checkFirstNode();
          this.checkDateButton(7);
        }
      });
    },
    checkFirstNode() {
      let node = this.$refs.tree.getNode(1);
      this.$refs.tree.setCurrentKey(node);
      this.checkNode = node;
      this.logType = node.data.value;
    },
    checkDateButton(num) {
      const dateArray = [];
      const today = new Date();

      this.formData.startDate = moment(today).add(-num + 1, "days").format("YYYY-MM-DD");
      this.formData.endDate = moment(today).format("YYYY-MM-DD");
      this.searchEvent()
    }

  }
};
</script>
<style scoped>
::v-deep body .tab-box > .el-tabs__content .grid-height {
  height: calc(100vh - 91px);
}
</style>
