<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="系统模块" prop="title">
        <el-input
          maxlength="50"
          v-model="queryParams.title"
          placeholder="请输入系统模块"
          clearable
          style="width: 240px;"
        />
      </el-form-item>
      <el-form-item label="操作人员" prop="operName">
        <el-input
          maxlength="50"
          v-model="queryParams.operName"
          placeholder="请输入操作人员"
          clearable
          style="width: 240px;"
        />
      </el-form-item>
      <el-form-item label="审计类型" prop="auditType">
        <el-select
          v-model="queryParams.auditType"
          placeholder="请选择审计类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in auditTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" prop="businessType">
        <el-select
          v-model="queryParams.businessType"
          placeholder="请选择操作类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in operTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择操作状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          style="display:none"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['auditManager:operlog:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          style="display:none"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          v-hasPermi="['auditManager:operlog:remove']"
        >清空
        </el-button>
      </el-col>
    </el-row>

    <div style="padding-top: 10px">
      <vxe-table
        ref="tables"
        align="center"
        :loading="loading"
        class="mytable-style"
        auto-resize
        border
        resizable
        export-config
        highlight-current-row
        show-overflow
        max-height="700"
        :data="list"
        :radio-config="{trigger: 'row'}"
        @sort-change="sortChangeEvent"
        :sort-config="{remote:'true'}"
      >
<!--        <vxe-column type="radio" width="60"/>-->
        <vxe-table-column field="operId" title="日志编号"/>
        <vxe-table-column field="title" title="系统模块" :sortable="true"/>
        <vxe-table-column field="auditType" title="审计类型" :formatter="auditTypeFormat"/>
        <vxe-table-column field="businessType" title="操作类型" :formatter="operTypeFormat"/>
        <vxe-table-column field="operName" title="操作人员" :sortable="true"/>
        <vxe-table-column field="operIp" title="操作地址"/>
        <vxe-table-column field="operLocation" title="操作地点"/>
        <vxe-table-column field="status" title="操作状态" :formatter="statusFormat"/>
        <vxe-table-column field="operTime" title="操作日期" :sortable="true"/>
        <vxe-table-column field="costTime" title="消耗时间(毫秒)"/>
        <vxe-table-column title="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row,scope.index)"
            >详细
            </el-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager
        perfect
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :total="total"
        :page-sizes="[10,50,100]"
        :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
        @page-change="handlePageChange"
      >
      </vxe-pager>
    </div>

    <!-- 操作日志详细 -->
    <el-dialog title="操作日志详细" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作模块：">{{ form.title }}</el-form-item>
            <el-form-item
              label="登录信息："
            >{{ form.operName }} / {{ form.operIp }} / {{ form.operLocation }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求地址：">{{ form.operUrl }}</el-form-item>
            <el-form-item label="请求方式：">{{ form.requestMethod }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作方法：">{{ form.method }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请求参数：">{{ form.operParam }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="返回参数：">{{ form.jsonResult }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="操作状态：">
              <div v-if="form.status === 0">正常</div>
              <div v-else-if="form.status === 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="消耗时间：">{{ form.costTime }}毫秒</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="操作时间：">{{ parseTime(form.operTime) }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常信息：" v-if="form.status === 1">{{ form.errorMsg }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {debounce} from "lodash";

export default {
  name: "Operlog",
  dicts: ['sys_oper_type', 'sys_common_status'],
  data() {
    return {
      showTable: true,
      currentPage: 1,
      pageSize: 10,
      ///** 操作类型（0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据） */
      operTypeOptions: [
        {value: '1', label: '新增'},
        {value: '2', label: '修改'},
        {value: '3', label: '删除'},
        {value: '4', label: '授权'},
        {value: '9', label: '清空数据'},
        {value: '0', label: '其他'}
      ],
      ///** 审计类型（0=系统,1=业务） */
      auditTypeOptions: [
        // {value: '0', label: '系统'},
        // {value: '1', label: '业务'}
      ],
      statusOptions: [
        {value: '0', label: '成功'},
        {value: '1', label: '失败'}
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示弹出层
      open: false,
      sortOrder: 'operTime&asc',
      // 日期范围
      dateRange: [],
      // 默认排序
      defaultSort: {prop: 'operTime', order: 'descending'},
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        title: undefined,
        operName: undefined,
        businessType: undefined,
        auditType: undefined,
        status: undefined
      }
    };
  },
  created() {
    // 获取审计类型
    this.$axios.get('/sysOperlogController/getAuditType').then((res) => {
      this.auditTypeOptions = res.data
    }).catch((error) => {
    })

    this.getList();
  },
  methods: {
    sortChangeEvent({column, property, order}) {
      if (order == null) {
        order = 'asc'
      }
      this.currentPage = 1
      this.sortOrder = property+'&'+order
      this.getList()
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.getList()
    },
    // 列表状态格式化
    statusFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.statusOptions.length; i++) {
        if (cellValue == "0") {
          belongTo = "成功"
        } else if (cellValue == "1") {
          belongTo = "失败"
        }
      }
      return belongTo
    },
    // 列表状态格式化
    operTypeFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.operTypeOptions.length; i++) {
        if (cellValue == "1") {
          belongTo = "新增"
        } else if (cellValue == "2") {
          belongTo = "修改"
        } else if (cellValue == "3") {
          belongTo = "删除"
        } else if (cellValue == "4") {
          belongTo = "授权"
        } else if (cellValue == "9") {
          belongTo = "清空数据"
        } else if (cellValue == "0") {
          belongTo = "其他"
        }
      }
      return belongTo
    },
    // 列表状态格式化
    auditTypeFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.auditTypeOptions.length; i++) {
        if (cellValue == "0") {
          belongTo = "系统"
        } else if (cellValue == "1") {
          belongTo = "业务"
        }
      }
      return belongTo
    },
    /** 查询操作日志列表 */
    getList: debounce(function () {
      this.loading = true;
      let _startOperTime;
      let _endOperTime;
      if (this.dateRange == null) {
        _startOperTime = ''
        _endOperTime = ''
      } else {
        _startOperTime = this.dateRange[0]
        _endOperTime = this.dateRange[1]
      }
      var searchParams = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        title: this.queryParams.title,
        operName: this.queryParams.operName,
        businessType: this.queryParams.businessType,
        auditType: this.queryParams.auditType,
        status: this.queryParams.status,
        startOperTime: _startOperTime,
        endOperTime: _endOperTime,
        sortOrder: this.sortOrder
      }
      this.$axios.get('/sysOperlogController/getAll',
        {params: searchParams}).then((res) => {
        this.list = res.data.records
        this.total = res.data.total
        if (res.data.records == '') {
          this.showTable = false
        } else {
          this.showTable = true
        }
        this.loading = false
      }).catch((error) => {
        this.loading = false;
        // this.$message.error(error)
      })
    }, 1000),
    // 操作日志类型字典翻译
    typeFormat(row, column) {
      // return this.selectDictLabel(this.dict.type.sys_oper_type, row.businessType);
      return ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.operId)
      this.multiple = !selection.length
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.open = true;
      this.form = row;
    },
    /** 删除按钮操作 */
    handleDelete() {
      const _selectData = this.$refs.tables.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      this.$confirm('是否确认删除操作日志?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete(_selectData)
      }).catch(() => {
      });
    },
    /**
     * 删除提交
     */
    doDelete: debounce(function (_selectData) {
      const param = {
        operId: _selectData.operId
      }
      this.$axios.post('/sysOperlogController/delOperlog', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
        this.loading = false
      })
    }, 1000),
    /** 清空按钮操作 */
    handleClean() {
      if (this.list == '') {
        this.$message({
          type: 'warning',
          message: '没有记录不能清空!'
        });
        return
      }
      this.$confirm('是否确认清空所有操作日志数据项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.cleanOperLog();
      }).catch(() => {
      })
    },
    /**
     * 清空提交
     */
    cleanOperLog: debounce(function () {
      this.$axios.post('/sysOperlogController/cleanOperLog', {}).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '清空成功!'
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '清空失败!'
        });
        this.loading = false
      })
    }, 1000)
  }
};
</script>

