<template>
  <a-spin class="fixHeight" :spinning="cardLoading">
    <a-table
      id="warnTable"
      ref="table"
      :scroll="{ y: 'calc(100% - 106px)', x: '100%' }"
      bordered
      :pagination="false"
      :columns="columns"
      :dataSource="dataSource"
      :loading="loading"
      style="height: calc(100% - 56px)"
      @change="handleTableChange"
      size="small"
    >
      <template slot="action" slot-scope="text, record">
        <a v-if="true" @click="handleSelect(record)">{{ text }}</a>
      </template>
      <span slot="moxing" slot-scope="text">
        <a-tag :color="text === '默认' ? '' : '#f56c6c'" v-if="text != null && text !== ''">
          {{ text }}
        </a-tag>
      </span>
      <template slot="getWarnDetail" slot-scope="text, record">
        <a @click="getWarnDetail(record)">{{ text }}</a>
<!--        <p>{{ text }}</p>-->
      </template>
      <!--      <template slot="editRemark" slot-scope="text, record">-->
      <!--        <a-button type="link" size="small" @click="toEdit(record)">编辑</a-button>-->
      <!--      </template>-->
    </a-table>
    <a-modal v-model="showWarnDetail" title="预警详情" width="1400px" :footer="null">
      <a-table
        size="small"
        :scroll="{ y: 500 }"
        bordered
        :pagination="detailPagination"
        :columns="detailColumns"
        :dataSource="detailDataSource"
        :loading="detailLoading"
        @change="handleDetailTableChange"
      >
        <template slot="detailAction" slot-scope="text, record">
          <a v-if="true" @click="handleSelect(record)">{{ text }}</a>
        </template>
        <template slot="editRemark" slot-scope="text, record">
          <a-button type="link" size="small" @click="toEdit(record)">编辑</a-button>
        </template>
      </a-table>
    </a-modal>
    <template>
      <a-modal title="编辑" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
        <div style="">
          <a-button @click="fillDay">补充1天的预警数据</a-button>
          <div style="margin-bottom: 20px; display: flex">
            <div style="padding-top: 4px; padding-right: 10px">判&nbsp;&nbsp;&nbsp;别&nbsp; :</div>
            <div>
              <a-select v-model="defaultSelect" style="width: 120px" @change="handleChange">
                <a-select-option value="报警属实"> 报警属实 </a-select-option>
                <a-select-option value="误报"> 误报 </a-select-option>
              </a-select>
            </div>
          </div>

          <div style="margin-bottom: 20px; display: flex">
            <div style="padding-top: 4px; padding-right: 10px">备&nbsp;&nbsp;&nbsp;注&nbsp; :</div>
            <div>
              <a-input v-model="remark" placeholder="请输入备注" />
            </div>
          </div>

          <div style="display: flex">
            <div style="padding-top: 4px; padding-right: 10px">记录人 :</div>
            <div>
              <a-input v-model="recorder" placeholder="请输入记录人" />
            </div>
          </div>
        </div>
      </a-modal>
    </template>
  </a-spin>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterObj, filterBjnr } from '@/utils/util'
import moment from 'moment'
import events from '@/views/top/events'
import vue from 'vue'
import { TOP_WELL_CHOOSEN, USER_NAME } from '@/store/mutation-types'
import { editWarning, refillWarning, refillWarningDay } from '@/api/api'
import warnApi from '@/api/warnApi'
import _ from 'lodash'
import { EVENT_ALL_WARN, sendMsg } from '@/WsMgr'

const lsJhKey = 'TOPLEFT_JH_SELECTED'
const highLightSecondsLimit = 60
const gcyjRefreshInterval = 10000
const highLightClass = 'high-light-row'

export default {
  name: 'FocusListRightPage',
  mixins: [JeecgListMixin],
  components: {},
  props: {
    value: {
      type: Array,
      default: []
    },
    queryParam: {
      type: Object,
      default: () => {
        return {
          warnTimeRange: [
            moment()
              .add(-2, 'days')
              .format('YYYY-MM-DD'),
            moment().format('YYYY-MM-DD')
          ],
          source: '工程预警'
        }
      }
    }
  },
  data() {
    return {
      description: '用户信息',
      xcsyj: '新参数预警',
      remark: '',
      id: 0,
      defaultSelect: '',
      cardLoading: true,
      visible: false,
      positionInfo: {},
      columns: [
        {
          title: '序号',
          key: 'rowIndex',
          dataIndex: '',
          width: 50,
          align: 'center',
          customRender: (t, r, i) => parseInt(i) + 1
        },
        {
          title: '井号',
          width: 80,
          align: 'center',
          dataIndex: 'JH',
          scopedSlots: { customRender: 'action' }
        },
        {
          title: '预警模型',
          dataIndex: 'MX',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'moxing' }
        },
        {
          title: '报警类别',
          width: 70,
          align: 'center',
          dataIndex: 'SOURCE'
        },
        {
          title: '异常类型',
          width: 120,
          align: 'center',
          customRender: (t, r) => (r.MX === '定制' && '井涌,井漏'.indexOf(t) >= 0 ? '疑似' + t : t),
          dataIndex: 'CATOGARY'
        },
        {
          title: '时间区间报警总和',
          width: 100,
          align: 'center',
          dataIndex: 'COUNT',
          scopedSlots: { customRender: 'getWarnDetail' }
        },
        {
          title: '最新报警时间',
          width: 120,
          dataIndex: 'WARN_TIME',
          align: 'center',
          sorter: true
        },
        {
          title: '异常描述',
          align: 'left',
          dataIndex: 'BJNR',
          ellipsis: false,
          width: 500,
          customRender: t => {
            var text = filterBjnr(t)
            return <span style="white-space: pre-line">{text}</span>
          }
        }

        // {
        //   title: '现场判别',
        //   width: 100,
        //   dataIndex: 'judge',
        //   align: 'center'
        // },

        // {
        //   title: '记录人',
        //   width: 80,
        //   dataIndex: 'recorder',
        //   align: 'center'
        // },
        // {
        //   title: '记录时间',
        //   width: 150,
        //   dataIndex: 'updated',
        //   align: 'center'
        // },
        // {
        //   title: '备注',
        //   width: 100,
        //   dataIndex: 'remark',
        //   align: 'center'
        // },
        // {
        //   title: '操作',
        //   width: 60,
        //   dataIndex: 'remark',
        //   align: 'center',
        //   scopedSlots: { customRender: 'editRemark' }
        // }
      ],
      detailDataSource: [],
      /* 分页参数 */
      detailPagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* table加载状态 */
      detailLoading: false,
      detailColumns: [
        {
          title: '序号',
          key: 'rowIndex',
          dataIndex: '',
          width: 80,
          align: 'center',
          customRender: (t, r, i) =>
            (this.detailPagination.current - 1) * this.detailPagination.pageSize + parseInt(i) + 1
        },
        {
          title: '井号',
          width: 100,
          align: 'center',
          dataIndex: 'JH',
          scopedSlots: { customRender: 'detailAction' }
        },
        {
          title: '报警类别',
          width: 90,
          align: 'center',
          dataIndex: 'SOURCE'
        },
        {
          title: '异常类型',
          width: 80,
          align: 'center',
          dataIndex: 'CATOGARY'
        },
        {
          title: '异常描述',
          align: 'center',
          dataIndex: 'BJNR',
          width: 300,
          customRender: t => filterBjnr(t)
        },
        {
          title: '报警时间',
          width: 120,
          dataIndex: 'WARN_TIME',
          align: 'center',
          sorter: true
        },
        {
          title: '现场判别',
          width: 100,
          dataIndex: 'JUDGE',
          align: 'center'
        },
        {
          title: '记录人',
          width: 80,
          dataIndex: 'RECORDER',
          align: 'center'
        },
        {
          title: '记录时间',
          width: 150,
          dataIndex: 'UPDATED',
          align: 'center'
        },
        {
          title: '备注',
          width: 100,
          dataIndex: 'REMARK',
          align: 'center'
        },
        {
          title: '操作',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'editRemark' }
        }
      ],

      url: {
        list: '/focusJh/listWarning'
      },
      jhRecordList: [],
      showWarnDetail: false,
      detailJH: '',
      detailType: '',
      addCount: 0,
      updateCount: 0
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(orgCode) {
        this.dataSource = []
        console.log(orgCode)
        this.loadData(1, orgCode)
      }
    }
  },
  created() {
    this.loadAllJh()
    this.$bus.on(EVENT_ALL_WARN, this.setWebsocketWarn)
  },
  methods: {
    loadAllJh() {
      var params = {} //查询条件
      getAction('/focusJh/list', params).then(res => {
        if (res.success) {
          this.jhRecordList = res.result.records || res.result
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
      })
    },
    loadData(pageNum, jhList, intervalCallee = false) {
      this.loading = true
      if (this.queryParam.source == this.xcsyj) {
        let m_jhList = []
        if (jhList != '') {
          m_jhList = jhList.split(',')
        }
        console.log(m_jhList)
        postAction('/ginger/newParameterWarning', {
          jhs: jhList,
          strDate: this.queryParam.warnTimeRange[0].replace(/-/g, '/'),
          endDate: this.queryParam.warnTimeRange[1].replace(/-/g, '/')
        }).then(res => {
          if (res && res.length > 0) {
            this.dataSource = res.map(x => {
              return {
                'JH': x.JH,
                'MX': x.YJMX,
                'SOURCE': x.BJLB,
                'BJNR': x.YCMS,
                'CATOGARY': x.YCLX,
                'COUNT': x.LSBJCS,
                'WARN_TIME': x.BJSJ
              }
            })
            if (m_jhList.length > 0 && m_jhList[0] != '') {
              this.dataSource = this.dataSource.filter(item => {
                if (m_jhList.indexOf(item.JH) != -1) {
                  return item
                }

              })
            }
          } else {
            this.dataSource = res
          }
          this.loading = false
          this.cardLoading = false
        })
      } else {
        getAction('/focusJh/newListWarning', {
          group: 1,
          jh: jhList,
          source: this.queryParam.source,
          warn_s: this.queryParam.warnTimeRange[0],
          warn_e: this.queryParam.warnTimeRange[1],
          field: 'id,,jh,source,catogary,bjnr,warnTime,judge,recorder,updated,remark,remark',
          pageNo: 1,
          pageSize: 999999
        })
          .then(res => {
            if (!res.success) {
              return
            }
            this.addCount = 0
            this.loadCount = 0
            res.result.records.forEach(k => (k.mapKey = `${k.JH}_${k.CATOGARY}_${k.SOURCE}`))
            this.dataSource = res.result.records
          })
          .finally(() => {
            this.loading = false
            this.cardLoading = false
          })
      }
    },
    loadDetailData(pageNum) {
      this.detailLoading = true
      if (pageNum === 1) {
        this.detailPagination.current = 1
      }
      getAction('/focusJh/newListWarning', {
        group: 0,
        jh: this.detailJH,
        catogary: this.detailType,
        // source: this.detailType,
        // warnTime_begin: this.queryParam.warnTime_begin,
        // warnTime_end: this.queryParam.warnTime_end,
        field: 'id,,jh,source,catogary,bjnr,warnTime,judge,recorder,updated,remark,remark',
        pageNo: this.detailPagination.current,
        pageSize: this.detailPagination.pageSize
      })
        .then(res => {
          if (res.success) {
            this.detailDataSource = res.result.records
            this.detailPagination.total = res.result.total
          }
        })
        .finally(() => {
          this.detailLoading = false
        })
    },

    handleSelect(record1) {
      console.log(record1.toString() + 'record1')
      let record = record1
      let exist = false
      this.jhRecordList.forEach(item => {
        if (record1.JH == item.JH) {
          exist = true
          record = { ...item }
        }
      })

      console.log(exist + '(exist)')

      const time = new Date(record1.WARN_TIME)
      const timeStr = moment(time).format('YYYY-MM-DD')
      if (!exist) {
        warnApi.getInfoByJh({ jh: record1.JH }).then(res => {
          console.log(res.result)
          let parmams = res.result
          this.$store.commit('serchJhSet', parmams.JH)
          vue.ls.set(lsJhKey, parmams)
          this.$store.commit(TOP_WELL_CHOOSEN, parmams)
          // events.$emit('jhSelected', { jh: parmams.JH, record: parmams, tid: moment().unix(),serchTime: timeStr,gcyj:1})
          // this.$emit('ok');
          this.$router.push({ name: 'top', query: { jh: parmams.JH, serchTime: timeStr, gcyj: 1 } })
        })
      } else {
        const parmams = {
          ID: record.id,
          DH: record.dh,
          zjy: record.zjy,
          SGYQ: record.sgyq,
          SJDW: record.sjdw,
          zjyDay: record.zjyDay,
          DT: record.dt,
          EJDW: record.ejdw,
          ltd: record.ltd,
          ltdDay: record.ltdDay,
          JH: record.jh
        }
        this.$store.commit('serchJhSet', parmams.JH)
        vue.ls.set(lsJhKey, parmams)
        this.$store.commit(TOP_WELL_CHOOSEN, parmams)
        events.$emit('jhSelected', {
          jh: parmams.JH,
          record: parmams,
          tid: moment().unix(),
          serchTime: timeStr,
          gcyj: 1
        })
        this.$emit('ok')
        console.log({ jh: parmams.JH, serchTime: timeStr, gcyj: 1, test: 1111 })
        this.$router.push({ name: 'top', query: { jh: parmams.JH, serchTime: timeStr, gcyj: 1 } })
      }
    },
    getQueryParams2() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.filters)
      param.field = this.getQueryField()
      param.pageNo = 1
      param.pageSize = 99999
      delete param.warnTimeRange // 时间参数不传递后台
      return filterObj(param)
    },
    searchQuery() {
      this.loadData(1, this.value)
    },
    searchReset() {
      this.queryParam = {
        warnTimeRange: ['', ''],
        source: '工程预警'
      }
      this.loadData(1, this.value)
    },
    handleOk(e) {
      if (!this.defaultSelect) {
        this.$message.warning('辨别不能为空')
        return
      }
      let data = {
        id: this.id,
        remark: this.remark,
        judge: this.defaultSelect,
        recorder: this.recorder
      }

      editWarning(data).then(res => {
        if (res.success) {
          this.visible = false
          this.$message.success(res.message)
        } else {
          this.visible = false
          this.$message.warning(res.message)
        }
        console.log(223)
        this.loadDetailData(1)
        this.remark = null
        this.defaultSelect = null
        this.recorder = null
        this.id = 0
      })
    },
    handleCancel(e) {
      this.remark = null
      this.defaultSelect = null
      this.recorder = null
      this.id = 0
      this.visible = false
    },
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.loadData(null, this.value)
    },
    resetDetailDialog() {
      this.detailLoading = false
      this.detailDataSource = []
      this.detailPagination.current = 1
    },
    handleDetailTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.detailPagination = pagination
      this.loadDetailData(null)
    },
    onDateChange: function (value, dateString) {
      this.queryParam.warnTime_begin = dateString[0]
      this.queryParam.warnTime_end = dateString[1]
    },
    toEdit(data) {
      let userName = vue.ls.get(USER_NAME)
      if (data.JUDGE === '报警属实' || data.JUDGE === '误报') {
        this.defaultSelect = data.JUDGE
      }

      this.recorder = data.RECORDER

      if (data.RECORDER === null || data.RECORDER === undefined || data.RECORDER === '') {
        this.recorder = userName
      }

      this.remark = data.REMARK
      this.id = data.ID
      this.visible = true
    },
    async getWarnDetail(record) {
      console.log(record)
      if (this.queryParam.source == this.xcsyj) {
        let jh = record.JH
        let lb = record.CATOGARY
        //let time=record.WARN_TIME.substring(0,10)
        let time = ''
        this.$dialog(
          () => import('./YjTableDialogNew'),
          { jh: jh, date: time, lb: lb,warnTimeRange:this.queryParam.warnTimeRange
          },
          {
            title: `${jh} ${time}  预警信息`,
            width: document.body.offsetWidth * 0.75,
            height: document.body.offsetHeight *1,
            centered: true,
            maskClosable: true,
            okButtonProps: { style: { display: 'none' } },
            cancelText: '关闭'
          }
        )
      } else {
        this.resetDetailDialog()
        this.detailJH = record.JH
        this.detailType = record.CATOGARY
        await this.loadDetailData(1)
        this.showWarnDetail = true
      }

    },
    highLightCheck(data) {
      const rows = document.getElementById('warnTable').getElementsByClassName('ant-table-row')
      Array.prototype.forEach.call(rows, row => {
        const rowData = data[parseInt(row.getAttribute('data-row-key'))]
        const canHighLight =
          rowData.highLightStart && moment().diff(rowData.highLightStart, 'seconds') <= highLightSecondsLimit
        const isHighLight = row.classList.contains(highLightClass)
        if (canHighLight && !isHighLight) {
          row.classList.add(highLightClass)
        }
        if (!canHighLight && isHighLight) {
          row.classList.remove(highLightClass)
        }
      })
    },
    // 填充工程预警 单井 某一天的数据，手动调用，可删除  20220919
    fillTest() {
      refillWarning({ jh: '埕北斜397', startTime: '2022-09-05' })
        .then(res => { })
        .catch(e => {
          this.$message.error(e)
        })
    },
    // 填充工程预警 所有井 一天的数据，可删除
    fillDay() {
      debugger
      refillWarningDay({ startTime: '2022-10-22 00:00:00' }) // 17
        .then(res => { })
        .catch(e => {
          this.$message.error(e)
        })
    },
    setWebsocketWarn(data) {
      const now = moment()
      if (this.queryParam.source !== '全部') {
        data = _.filter(data, p => p.SOURCE === this.queryParam.source)
      }
      data.forEach(k => {
        k.mapKey = `${k.JH}_${k.CATOGARY}_${k.SOURCE}`
        k.WARN_TIME = moment(k.WARN_TIME).format('YYYY-MM-DD HH:mm:ss')
        const match = _.findIndex(this.dataSource, p => p.mapKey === k.mapKey)
        if (match !== -1) {
          const exist = this.dataSource[match]
          const objectChanged = k.COUNT !== exist.COUNT || k.WARN_TIME !== exist.WARN_TIME
          if (objectChanged) {
            vue.set(this.dataSource, match, Object.assign(exist, k, { highLightStart: now }))
            this.updateCount++
          }
        } else {
          this.dataSource.splice(0, 0, Object.assign(k, { highLightStart: now }))
          this.addCount++
        }
        this.highLightCheck([...this.dataSource])
      })

      let topCardTitleAppend = `上次更新 ${now.format('HH:mm:ss')} 新增 `
      topCardTitleAppend += `${this.addCount === 0 ? '无' : this.addCount} 更新 ${this.updateCount === 0 ? '无' : this.updateCount} `
      this.$emit('refreshMsgChanged', topCardTitleAppend)
    }
  },
  mounted() {
    // this.timer = window.setInterval(() => {
    //   setTimeout(() => {
    //     this.loadData(null, this.value, true)
    //     if (this.showWarnDetail) {
    //       this.loadDetailData(null)
    //     }
    //   }, 0)
    // }, gcyjRefreshInterval)
    setTimeout(() => {
      sendMsg(JSON.stringify({ 'isMultipleWellWarn': true }))
    }, 1500);
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.$bus.off(EVENT_ALL_WARN, this.setWebsocketWarn)
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  padding: 7px;
}


.fixHeight {
  height: 100%;
  /deep/ .ant-spin-nested-loading {
    height: calc(100% - 35px);
    .ant-spin-container {
      height: 100%;
      .ant-table {
        height: 100%;
        .ant-table-content {
          height: 100%;
          .ant-table-scroll {
            height: 100%;
            overflow: hidden;
          }
        }
      }
    }
  }
}

/deep/ .high-light-row {
  background: yellow;
  td {
    color: red;
  }
}
</style>
<style>
  .ant-modal-content{
    margin-top:100px;
  }
</style>