<template>
  <div id="containt">
    <el-tabs v-model="activeName" class="tab-box">
      <el-tab-pane :label="$t1('常规')" name="first">
        <editView v-if="showEdit" visible-key="showEdit" :_dataId.sync="dataId" :parent-target="_self"
                  @reload="$reloadHandle"></editView>
      </el-tab-pane>
      <el-tab-pane :label="$t1('列表')" name="second">
        <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">
            <vxe-grid ref="table-m1" v-bind="vxeOption" @resizable-change="$vxeTableUtil.onColumnWitchChange"
                      @custom="$vxeTableUtil.customHandle">
              <template #form>
                <div class="clearfix screen-btns">
                  <div class="fl">
                    <base-table-export :option="{ title: $t1('访问统计导出'), targetRef: 'table-m1'}"
                                       :parent-target="_self"/>
                  </div>
                  <div class="fr">
                    <vxe-button status="warning" icon="iconfont icon-shaixuan" class="button-sty orgn"
                                @click="showAdvancedSearch = true">{{ $t1('高级筛选') }}
                    </vxe-button>
                    <vxe-button icon="el-icon-brush" class="button-sty" @click="resetEvent" type="text" status="primary"
                                plain>{{ $t1('重置') }}
                    </vxe-button>
                    <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-input v-model="checkNode.label" :disabled="true"></el-input>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('访问日期')+':'">
                    <template v-slot>
                      <el-date-picker
                        v-model="formData.startTime"
                        type="date"
                        placeholder=""
                        size="small"
                        clearable
                        value-format="yyyy-MM-dd"
                        :picker-options="$baseStartPickerOptions(formData.endTime)"
                      ></el-date-picker>
                      <span>-</span>
                      <el-date-picker
                        v-model="formData.endTime"
                        type="date"
                        placeholder=""
                        size="small"
                        clearable
                        value-format="yyyy-MM-dd"
                        :picker-options="$baseEndPickerOptions(formData.startTime)"
                      ></el-date-picker>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>
            </vxe-grid>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t1('统计')" name="third">
        <statistics_list v-if="showStatisticsList"></statistics_list>
      </el-tab-pane>
    </el-tabs>
    <advancedSearchDialog v-if="showAdvancedSearch" :visiable.sync="showAdvancedSearch"
                          :formData.sync="advancedFormData" @confirm="searchEvent">
      <template #form>
        <vxe-form :model="advancedFormData" title-width="102px" :inline="true" class="adSearchForm">
          <vxe-form-item :title="$t1('操作内容') + ':'" class-name="block">
            <template v-slot>
              <el-input v-model="advancedFormData.content" size="small" clearable></el-input>
            </template>
          </vxe-form-item>
          <vxe-form-item :title="$t1('冗余字段1') +':'">
            <template v-slot>
              <el-input v-model="advancedFormData.param1" size="small" clearable></el-input>
            </template>
          </vxe-form-item>
          <vxe-form-item :title="$t1('冗余字段2') +':'">
            <template v-slot>
              <el-input v-model="advancedFormData.param2" size="small" clearable></el-input>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
    </advancedSearchDialog>

  </div>
</template>

<script>
import {treeScollx} from '@base/utils/global.js';
import editView from './edit.vue';
import statistics_list from "./statistics_list.vue";


export default {
  name: 'access_log:list',
  components: {editView, statistics_list},
  data() {
    return {
      activeName: 'second',
      dataId: 0,
      showEdit: false,
      vxeOption: {},
      formData: {
        startTime: null,
        endTime: null
      },
      checkNode: {},
      defaultProps: {
        label: 'label', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      showWfDialog: false,
      wfContentOption: {},
      showAdvancedSearch: false,
      advancedFormData: {},
      showStatisticsList: false,
      logTypeMap: {}
    };
  },
  watch: {
    activeName(val) {
      if (this.showStatisticsList === false && val === "third") {
        this.showStatisticsList = true;
      }
    }
  },
  computed: {
    checkNodeData() {
      return this.checkNode && this.checkNode.data ? this.checkNode.data : {};
    },
    logType() {
      let checkNodeData = this.checkNode && this.checkNode.data ? this.checkNode.data : {};
      return checkNodeData.value ?? null
    }
  },
  async mounted() {
    treeScollx({target: this, type: 'default'});
    this.initTableList();
  },
  methods: {
    searchEvent() {
      this.$refs['table-m1'].commitProxy('reload');
    },
    resetEvent() {
      this.formData = {};
      this.advancedFormData = {};
      this.checkFirstNode();
      this.$refs['table-m1'].commitProxy('reload');
    },
    openEditDialog(id) {
      this.dataId = !id || typeof id == 'object' ? 0 : id;
      this.activeName = 'first';
      this.$openEditView('showEdit');
    },
    initTableList() {
      let that = this;
      let logTypeMap = this.logTypeMap;
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user_access_log_list-m1',
        path: USER_PREFIX + '/access_log/listPage',
        param: () => {
          return {
            ...this.formData,
            ...this.advancedFormData,
            logType: this.logType
            // ...checkParam
          };
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('操作类型'),
            field: 'logTypeName',
            fixed: 'left',
            width: 150
          },
          {
            title: this.$t1('操作内容'),
            field: 'content',
            width: 200
          },
          {
            title: this.$t1('请求地址'),
            field: 'path',
            width: 200
          },
          {
            title: this.$t1('客户端'),
            field: 'client',
            width: 150
          },
          {
            title: this.$t1('冗余字段1'),
            field: 'param1',
            width: 150
          },
          {
            title: this.$t1('冗余字段2'),
            field: 'param2',
            width: 150
          },
          {
            title: this.$t1('操作人'),
            field: 'nickName',
            width: 150
          },
          {
            title: this.$t1('服务名'),
            field: 'serverName',
            width: 250
          },
          {
            title: this.$t1('请求IP'),
            field: 'ip',
            width: 150
          },
          {
            title: this.$t1('创建时间'),
            field: 'createDate',
            width: 150
          },
          {
            width: 47,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: ({row, rowIndex}) => {
                return [
                  <div>
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onclick={() => {
                        this.openEditDialog(row.id);
                      }}
                    >
                      <el-tooltip enterable={false} effect="dark" content={this.$t1('查看')} placement="top"
                                  popper-class="tooltip-skin">
                        <i class="el-icon-edit"/>
                      </el-tooltip>
                    </a>
                  </div>
                ];
              }
            }
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    clearNodeClick() {
      this.checkNode = null;
      this.formData.startTime = null;
      this.formData.endTime = null;
      this.$refs.tree.setCurrentKey();
      this.searchEvent();
    },
    handleNodeClick(data, node, v) {
      this.checkNode = node;
      this.formData.startTime = data.all ? null : data.logDate;
      this.formData.endTime = data.all ? null : data.logDate;
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      this.$http({
        url: USER_PREFIX + `/user_log_classify/listPage`,
        method: `post`,
        data: {
          enabled: true
        },
        success: res => {
          let logTypeMap = {};
          let rows = res.objx?.records || [];
          let items = rows.map(item => {
            logTypeMap[item.classifyCode] = item.classifyName;
            return {
              label: item.classifyName,
              value: item.classifyCode,
              id: item.classifyCode,
              leaf: true,
            }
          })
          this.logTypeMap = logTypeMap;
          let data = [
            {
              label: this.$t1('全部类型'),
              all: true,
              id: -1,
              leaf: true,
            },
            ...items
          ]
          resolve(data);
          this.$nextTick(() => {
            if (node.childNodes.length) {
              this.checkFirstNode();
              this.$forceUpdate();
            }
          });
        }
      });

    },
    checkFirstNode() {
      let node = this.$refs.tree.getNode(-1);
      this.$refs.tree.setCurrentKey(node);
      this.checkNode = node;
    }
  }
};
</script>
