<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="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="channelCode">
        <el-select v-model="queryParams.channelCode" clearable filterable placeholder="请选择设备名称">
          <el-option
            v-for="item in deviceNameList"
            :key="item.channelCode"
            :label="item.cameraName"
            :value="item.channelCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" prop="operateType">
        <el-select v-model="queryParams.operateType" clearable filterable placeholder="请选择操作类型">
          <el-option
            v-for="dict in dict.type.operate_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间">
        <el-date-picker
          v-model="operateTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="queryPickerOptions"
        ></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
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handMovement"
        >同步数据
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出数据
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="logList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="用户名" align="center" prop="userName"/>
      <el-table-column label="操作ip" align="center" prop="terminalIp"/>
      <el-table-column label="设备名称" align="center" prop="deviceName"/>
      <el-table-column label="操作类型" align="center" prop="operateType"/>
      <el-table-column label="事件内容" align="center" prop="detail"/>
      <el-table-column label="操作时间" align="center" prop="operateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改云台日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24" class="mb8">
          <el-col :span="16">
            <el-form-item label="选择时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 280px"
                value-format="yyyy-MM-dd"
                type="daterange"
                :picker-options="pickerOptions"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="操作类型">
              <el-select v-model="operateTypeValue" clearable filterable placeholder="请选择操作类型">
                <el-option
                  v-for="dict in dict.type.operate_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改云台日志对话框 -->
    <el-dialog title="云台日志详情" :visible="detailsOpen" width="800px" append-to-body :before-close="handleClose">
      <el-form ref="refForm" :model="form" label-width="80px" disabled>
        <el-row :gutter="24" class="mb8">
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作者ip" prop="terminalIp">
              <el-input v-model="form.terminalIp"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="mac地址" prop="macAddr">
              <el-input v-model="form.macAddr"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通道名" prop="channelName">
              <el-input v-model="form.channelName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模块名称" prop="operateName">
              <el-input v-model="form.operateName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作结果" prop="operateResult">
              <el-input v-model="form.operateResult"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务标识" prop="serviceCode">
              <el-input v-model="form.serviceCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="form.serviceName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作耗时" prop="responseTime">
              <el-input v-model="form.responseTime"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通道编码" prop="detail">
              <el-input v-model="form.channelCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备ip" prop="detail">
              <el-input v-model="form.deviceIp"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务操作" prop="behavior">
              <el-input v-model="form.behavior"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作时间" prop="operateTime">
              <el-date-picker clearable
                              style="width: 288px"
                              v-model="form.operateTime"
                              type="date"
                              format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="mb8">
          <el-col :span="24">
            <el-form-item label="事件内容" prop="detail">
              <el-input v-model="form.detail"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormDetails">确 定</el-button>
        <el-button @click="cancelDetails">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLog, getLog, delLog, getAllDataLog, getDeviceNameList } from '@/api/dahuaLog/dahuaLog'
import { formatDate } from '@/utils'

export default {
  name: 'Log',
  dicts: ['operate_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 云台日志表格数据
      logList: [],
      // 获取设备名称
      deviceNameList: [],
      // 日期范围
      dateRange: [],
      operateTimeRange: [formatDate(new Date(), 'yyyy-MM-dd'), formatDate(new Date(), 'yyyy-MM-dd')],
      selectData: '', // 记录初始点击DatePicker日期选择器的时间
      queryPickerOptions: {
        // onPick：选中日期后会执行的回调。写成箭头函数否则this.selectData会报错
        // 点击时，选择的是初始时间，也就是minDate
        onPick: ({ maxDate, minDate }) => {
          this.selectData = minDate.getTime()
          if (maxDate) {
            // 第二次点击日期选择器，选好初始时间和结束时间后，解除禁用限制
            this.selectData = ''
          }
        },
        // 设置禁用状态，参数为当前日期，要求返回 Boolean。同理写成箭头函数
        disabledDate: (time) => {
          // 是否限制的判断条件，if里写点击了初始时间后的判断条件
          // 即第二个选择的时间前后不能超过初始时间的一个月
          if (this.selectData) {
            return time.getTime() > new Date() || time.getTime() > this.selectData + 15 * 24 * 3600 * 1000 || time.getTime() < this.selectData - 15 * 24 * 3600 * 1000
            // time.getTime() > new Date() 为所选时间不能超过今日
            // 30 * 24 * 3600 * 1000则为一个月的毫秒数，根据自己的需求修改限制的时间范围
          } else {
            return time.getTime() > new Date()
            // 如果不需要限制所选时间不能超过今日，则直接return false即可
          }
        }
      },
      operateTypeValue: null,
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime()
          if (maxDate) {
            this.selectDate = ''
          }
        },
        disabledDate: (time) => {
          if (this.selectDate !== '') {
            const one = 15 * 24 * 3600 * 1000
            const minTime = this.selectDate - one
            const maxTime = this.selectDate + one
            return time.getTime() < minTime || time.getTime() > maxTime
          }
        }
      },
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      detailsOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        terminalIp: null,
        macAddr: null,
        channelName: null,
        deviceName: null,
        operateName: null,
        operateType: null,
        operateResult: null,
        serviceCode: null,
        serviceName: null,
        responseTime: null,
        detail: null,
        behavior: null,
        channelCode: null,
        deviceIp: null,
        operateTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
    this.getDeviceNameList()
  },
  methods: {
    handleClose() {
      this.detailsOpen = false
    },
    /** 查询云台日志列表 */
    getList() {
      this.loading = true
      listLog(this.addDateRange(this.queryParams, this.operateTimeRange)).then(response => {
        this.logList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取设备名称 */
    getDeviceNameList() {
      getDeviceNameList().then(response => {
        console.log(response)
        this.deviceNameList = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      // this.operateTimeRange = []
      this.form = {
        id: null,
        userName: null,
        terminalIp: null,
        macAddr: null,
        channelName: null,
        deviceName: null,
        operateName: null,
        operateType: null,
        operateResult: null,
        serviceCode: null,
        serviceName: null,
        responseTime: null,
        detail: null,
        behavior: null,
        operateTime: null,
        createTime: null,
        operateTimeRange: []
      }
      this.operateTimeRange = [formatDate(new Date(), 'yyyy-MM-dd'), formatDate(new Date(), 'yyyy-MM-dd')]
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.operateTimeRange = [formatDate(new Date(), 'yyyy-MM-dd'), formatDate(new Date(), 'yyyy-MM-dd')]
      this.getDeviceNameList()
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 查看详情 */
    handleView(row) {
      console.log('row', row)
      this.reset()
      const id = row.id || this.ids
      let params = {
        operateTime: row.operateTime,
        id: id
      }
      getLog(params).then(response => {
        this.form = response.data
        this.detailsOpen = true
      })
    },
    submitFormDetails() {
      this.detailsOpen = false
      this.reset()
    },
    cancelDetails() {
      this.detailsOpen = false
      this.reset()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除云台日志编号为"' + ids + '"的数据项？').then(function() {
        return delLog(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    handMovement() {
      this.selectDate = ''
      console.log('this.selectDate', this.selectDate)
      this.dateRange = []
      this.operateTypeValue = null
      this.open = true
      this.title = '同步数据'
    },
    /**
     * 手动同步
     */
    submitForm() {
      let that = this
      that.loading = true
      if (that.dateRange.length === 0) {
        that.loading = false
        that.open = false
        return that.$modal.msgWarning('请选择您要同步的时间范围')
      }
      let params = {
        startTime: that.dateRange[0],
        endTime: that.dateRange[1],
        operateTypeValue: that.operateTypeValue
      }
      getAllDataLog(params).then(response => {
        if (response.code == 200) {
          that.$modal.msgSuccess('同步成功')
        } else {
          that.$modal.msgWarning('同步失败')
        }
        that.loading = false
        that.getList()
        that.getDeviceNameList()
      })
      that.open = false
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/center-monitor/dahuaOperateLog/export', {
        ...this.queryParams
      }, `云台日志-${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
