<template>
  <a-layout style="padding: 4px; height: 100%">
    <a-layout-sider
      width="500px"
      style="margin-right: 4px; background-color: transparent; height: 100%; border-bottom: 2px solid #0073bc"
    >
      <a-card
        title="关注井列表"
        size="small"
        style="height: 100%"
        :bodyStyle="{ overflowY: 'auto', height: 'calc(100% - 40px)' }"
      >
        <template slot="extra">
          <a-popover title="查询" trigger="click" style="display: none">
            <a-button type="primary" size="small" style="wdith: 65px"> 查询</a-button>
            <template slot="content">
              <a-form-item label="井号" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" style="width: 320px">
                <a-input-search
                  placeholder="请输入..."
                  style="width: 170px"
                  size="small"
                  v-model="queryParams.jh"
                  @change="_debounceRefreshTable"
                />
              </a-form-item>
              <a-form-item label="范围" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" style="width: 320px">
                <a-radio-group
                  v-model="queryParams.fw"
                  size="small"
                  button-style="solid"
                  style="margin-left: 8px"
                  @change="fwChanged"
                >
                  <a-radio-button value="dept"> 单位</a-radio-button>
                  <a-radio-button value="person"> 个人</a-radio-button>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="二级单位" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" style="width: 320px">
                <a-select
                  :disabled="queryParams.fw === 'person'"
                  size="small"
                  v-model="queryParams.dw"
                  :options="ejdwList"
                  style="width: 170px"
                  @change="_debounceRefreshTable"
                >
                </a-select>
              </a-form-item>
            </template>
          </a-popover>
          <a-button size="small" @click="addFoucsWell" style="margin-left: 8px; width: 90px"> 添加关注井</a-button>
        </template>
        <div style="margin-left: 5px">
          井号：
          <a-input-search
            placeholder="模糊检索井... ..."
            style="width: 380px"
            size="small"
            v-model="queryParams.jh"
            @change="_debounceRefreshTable"
          />
        </div>
        <br />
        <div style="margin-left: 5px; margin-top: -10px; margin-bottom: 10px">
          <span>范围：</span>
          <a-radio-group
            v-model="queryParams.fw"
            size="small"
            button-style="solid"
            style="margin-left: 0px"
            @change="fwChanged"
          >
            <a-radio-button value="dept"> 单位</a-radio-button>
            <a-radio-button value="person"> 个人</a-radio-button>
          </a-radio-group>
          <span style="margin-left: 22px">二级单位：</span>
          <a-select
            :disabled="queryParams.fw === 'person'"
            size="small"
            v-model="queryParams.dw"
            :options="ejdwList"
            style="width: 200px"
            @change="_debounceRefreshTable"
          ></a-select>
        </div>
        <!--          :scroll="{ y: 'calc(100% - 46px)' }"-->
        <a-table
          ref="leftTable"
          :showHeader="true"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :columns="columns"
          :data-source="dataSource"
          :pagination="ipagination"
          class="left-table"
          @onSelectAll="onSelectAllJh"
          @change="handleTableChange"
          size="small"
          :loading="tableLoading"
          :scroll="{ y: '94%' }"
        >
          <template slot="action" slot-scope="text, record">
            <a @click="handleSelect(record)">{{ text }}</a>
          </template>
          <template slot="dt" slot-scope="text">
            <a-tag color="geekblue">{{ text }}</a-tag>
          </template>
          <template slot="settings" slot-scope="text, record">
            <!-- <a-tag @click="openSettings(record)">设置</a-tag> -->
            <a-switch
              checked-children="开"
              un-checked-children="关"
              :defaultChecked="record.isWarn == '0'"
              :disabled="queryParams.fw == 'dept'"
              @change="warnSwitch(record)"
            />
          </template>
        </a-table>
      </a-card>
    </a-layout-sider>
    <a-layout-content style="height: 100%; border-bottom: 2px solid #0073bc">
      <a-card
        :title="`关注井报警信息${titleSupplement ? '(' + titleSupplement + ')' : ''}`"
        size="small"
        style="height: 100%"
        :bodyStyle="{ overflowY: 'auto', height: 'calc(100% - 40px)' }"
      >
        <template slot="extra">
          <a-checkbox size="small" v-if="false"> 全部井</a-checkbox>
          <a-divider type="vertical" v-if="false"></a-divider>
          时间：
          <a-date-picker
            v-model="rightQueryParams.warnTimeRange[0]"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            size="small"
            style="width: 118px"
            :allowClear="false"
          />
          -
          <a-date-picker
            v-model="rightQueryParams.warnTimeRange[1]"
            format="YYYY-MM-DD"
            :allowClear="false"
            valueFormat="YYYY-MM-DD"
            size="small"
            style="width: 118px"
          />
          报警类别：
          <a-select
            style="width: 120px"
            size="small"
            v-model="rightQueryParams.source"
            @change="changWarnType"
            placeholder="请选择报警类别"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="工程预警">工程预警</a-select-option>
            <!--                <a-select-option value="邻井复杂">邻井复杂</a-select-option>-->
            <a-select-option value="钻井液">钻井液</a-select-option>
            <a-select-option value="新参数预警">新参数预警</a-select-option>
            <a-select-option value="工况智能识别参数预警">工况智能识别参数预警</a-select-option>
          </a-select>
          <a-button-group size="small" style="margin-left: 16px">
            <a-button type="primary" @click="queryWarn" icon="search">查询</a-button>
            <a-button @click="searchReset" icon="reload" style="">重置</a-button>
            <a-button type="danger" @click="jumpTo">切换</a-button>
          </a-button-group>
          <a-dropdown-button size="small" style="margin-left: 10px">
            设置
            <a-menu slot="overlay" @click="handleMenuClick">
              <a-menu-item v-for="item in handleMenuOptions" :key="item.key">
                <a-icon :type="item.icon" />
                {{ item.value }}
              </a-menu-item>
              <!-- <a-menu-item key="2">
                <a-icon type="share-alt" />
                部门管理
              </a-menu-item>
              <a-menu-item key="3">
                <a-icon type="user" />
                员工管理
              </a-menu-item>
              <a-menu-item key="4">
                <a-icon type="share-alt" />
                定时任务
              </a-menu-item>
              <a-menu-item key="7">
                <a-icon type="share-alt" />
                新工况参数
              </a-menu-item>
              <a-menu-item key="8">
                <a-icon type="share-alt" />
                采集井状态
              </a-menu-item>
              <a-menu-item key="9">
                <a-icon type="share-alt" />
                预警参数
              </a-menu-item> -->
              <!-- <a-menu-item key="8">
                <a-icon type="share-alt" />
                测试用接口
              </a-menu-item> -->
            </a-menu>
            <a-icon slot="icon" type="team" />
          </a-dropdown-button>
        </template>
        <focus-list-right-page
          v-if="rightQueryType != '工况智能识别参数预警'"
          ref="warnList"
          v-model="jhList"
          :queryParam="rightQueryParams"
          @ok="closeModel"
          style="margin-top: 0px"
          @refreshMsgChanged="(s) => (titleSupplement = s)"
        />
        <warn-table v-else ref="warnTableRef" :queryParam="rightQueryParams" />
        <realTimeLog ref="realTimeLogRef" />
      </a-card>
    </a-layout-content>
    <a-modal
      v-model="showDialog"
      destroyOnClose
      width="1000px"
      class="modal-reset"
      title="配置2"
      :footer="null"
      :okButtonProps="{ style: { display: 'none' } }"
    >
      <a-tabs default-active-key="1" @change="callback">
        <a-tab-pane key="1" tab="曲线配置">
          <chart-options />
        </a-tab-pane>
        <a-tab-pane key="2" tab="预警模型配置">
          <warning style="overflow: scroll; height: 600px" :new-j-h="selectedJH" />
        </a-tab-pane>
        <a-tab-pane key="3" tab="工况参数配置">
          <mode />
        </a-tab-pane>
      </a-tabs>
    </a-modal>
    <a-modal
      title="井号表变更"
      :width="800"
      :visible="visible1"
      @cancel="handleCancel1"
      :okButtonProps="{ style: { display: 'none' } }"
      cancelText="关闭"
    >
      <div>
        <div style="float: left; margin-bottom: 10px">
          <span style="float: left; margin-left: 5px">井号：</span>
          <el-input v-model="JH" placeholder="" size="mini" style="float: left; width: 150px"></el-input>
          <span style="float: left; margin-left: 10px">井表：</span>
          <el-input v-model="JH_TABLE_NAME" placeholder="" size="mini" style="float: left; width: 150px"></el-input>
          <el-button type="primary" plain size="mini" style="float: left; margin-left: 10px" @click="lr"
            >录入</el-button
          >
          <el-button type="info" plain size="mini" style="float: left" @click="cz">重置</el-button>
        </div>
        <el-table
          class="tableClass"
          stripe
          :border="false"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="overflow-y: auto"
          height="501"
          max-height="501"
          size="small"
          :header-cell-style="{ background: 'cornflowerblue', color: 'white' }"
        >
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <el-table-column label="井号" prop="jh" align="center"></el-table-column>
          <el-table-column label="井表" prop="jhTableName" align="center"></el-table-column>
          <el-table-column label="操作" prop="tag" align="center">
            <template slot-scope="scope">
              <el-button type="danger" plain size="mini" @click="sc(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </a-modal>
  </a-layout>
</template>
<script>
import newWarnApi from '@/api/newWarnApi'
import { getAction } from '@/api/manage'
import wellInfo from '@/api/wellInfo'
import FocusListRightPage from './sub/FocusListRightPage'
import warnApi from '@/api/warnApi'
import events from '@/views/top/events'
import moment from 'moment'
import vue from 'vue'
import { TOP_WELL_CHOOSEN } from '@/store/mutation-types'
import ChartOptions from '@views/form/chartOptions'
import Warning from '@views/form/warning'
import mode from '@/views/form/mode'
import FocusSelectWell from './sub/FocusSelectWell'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import _ from 'lodash'
import { randomUUID, calculateTimeIntervalPoints } from '@/utils/util'
import warnTable from './parameterWarning/warnTable.vue'
import realTimeLog from './sub/realTimeLog.vue'
const lsJhKey = 'TOPLEFT_JH_SELECTED'
export default {
  name: 'FocusWarning',
  components: { Warning, ChartOptions, FocusListRightPage, mode, warnTable, realTimeLog },
  data() {
    return {
      JH: '',
      JH_TABLE_NAME: '',
      tableData: [],
      visible1: false,
      dataSource: [],
      leftTableContentHeight: 500,
      tableLoading: false,
      tableQueryIndex: 0,
      ipagination: {
        current: 1,
        pageSize: 999,
        // pageSizeOptions: ['10', '20', '30'],
        total: 0,
        hideOnSinglePage: true
      },
      handleMenuOptions: [
        {
          key: '1',
          value: '错表对照',
          icon: 'edit'
        }, {
          key: '2',
          value: '部门管理',
          icon: 'share-alt'
        }, {
          key: '3',
          value: '员工管理',
          icon: 'user'
        }, {
          key: '4',
          value: '定时任务',
          icon: 'share-alt'
        }, {
          key: '7',
          value: '新工况参数',
          icon: 'share-alt'
        }, {
          key: '8',
          value: '采集井状态',
          icon: 'share-alt'
        }, {
          key: '9',
          value: '预警参数',
          icon: 'share-alt'
        }, {
          key: '10',
          value: '综合复杂',
          icon: 'share-alt'
        }
      ],
      columns: [
        {
          title: '井号',
          dataIndex: 'jh',
          align: 'center',
          width: 90,
          scopedSlots: { customRender: 'action' }
        },
        {
          title: '实际井深/设计井深',
          dataIndex: 'gzjs',
          align: 'center',
          width: 140
        },
        {
          title: '动态',
          dataIndex: 'dt',
          align: 'center',
          width: 80,
          scopedSlots: { customRender: 'dt' }
        }
        , {
          title: '配置',
          align: "right",
          dataIndex: 'dt',
          width: 80,
          scopedSlots: { customRender: 'settings' }
        }
      ],
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      jhList: '',
      showDialog: false,
      selectedJH: '',

      focusRule: 'dept',
      rightQueryType: '工况智能识别参数预警',
      rightQueryParams: {
        warnTimeRange: [
          moment()
            .add(-2, 'days')
            .format('YYYY-MM-DD'),
          moment().format('YYYY-MM-DD')
        ],
        source: '工况智能识别参数预警',
        jh: ''
      },
      titleSupplement: '',
      ejdwList: [],
      queryParams: {
        dw: undefined,
        jh: undefined,
        fw: 'person'
      },
      tempjhList: [],
      multipleSelection: [],

    }
  },
  created() {

    this.loadLeftData(),
      (this._debounceRefreshTable = _.debounce(() => {
        this.ipagination.current = 1
        this.loadLeftData()
      }, 500))
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0
    }
  },
  methods: {
    cz() {
      this.JH = ''
      this.JH_TABLE_NAME = ''
    },
    sc(item) {
      newWarnApi.delWarningJh({ id: item.id }).then(res => {
        this.$message.success('删除成功')
        this.initTable()
      })
    },
    lr() {
      newWarnApi.saveWarningJh({ id: randomUUID(), jh: this.JH, jhTableName: this.JH_TABLE_NAME }).then(res => {
        this.$message.success('录入成功')
        this.initTable()
      })
    },
    handleCancel1() {
      this.visible1 = false
    },
    initTable() {
      newWarnApi.getWarningJhAll({}).then(res => {
        this.tableData = res.result
      })
    },
    warnSwitch(record) {
      console.log('warnSwitch:record')
      console.log(record)
      var is_warn = record.isWarn;
      if (is_warn == '0') {
        is_warn = '1'
      } else {
        is_warn = '0'
      }
      this.updateJhIsWarn(record.id, is_warn)
    },
    updateJhIsWarn(id, is_warn) {
      var param = {
        id: id,
        isWarn: is_warn
      }
      wellInfo.updateAFocushJhIsWarn(param).then(res => {
        console.log('更新数据状态', res)
        this.loadLeftData()
      })
    },
    handleMenuClick(e) {
      console.log('key', e.key)
      if (e.key == '1') {
        this.cz()
        this.visible1 = true
        this.initTable()
      } else if (e.key == '2') {
        this.$router.push({ name: '/DepartList' })
      } else if (e.key == '3') {
        console.log(e.key)
        this.$router.push({ name: '/UserList' })
      } else if (e.key == '4') {
        this.$router.push({ name: '/QuartzJobList' })
      } else if (e.key == '5') {
        this.$router.push({ name: '/dayWorkConditionsPage' })
      } else if (e.key == '6') {
        this.$router.push({ name: '/workConditionsPage' })
      } else if (e.key == '7') {
        this.$router.push({ name: '/newWorkConditionParamPage' })
      } else if (e.key == '8') {
        //this.pageByUserDw()
        //this.$refs.warnTableRef.speak()
        this.$refs.realTimeLogRef.open()
      } else if (e.key == '9') {
        console.log('跳转预警参数页面')
        this.$router.push({ name: '/warnTab' })
        //this.pageByUserDw()
        //this.$refs.warnTableRef.speak()
        // this.$refs.realTimeLogRef.open()
      }else if (e.key == '10') {
        this.$router.push({ name: '/drillingRisk' })
      }
    },

    pageByUserDw() {
      console.log('调用接口')
      var params = {
        jhs: "达4,利页6HF,埕中斜10,征深102,沙深1,董斜20,垦东47-3",
        endDate: "2024/10/30",
        strDate: "2024/10/28"
      }
      wellInfo.getMaxTimeWarnDataByJh(params).then(res => {
        console.log('res', res)
      })
      //   wellInfo.pageByUserDw().then(res => {
      //     console.log(res)
      //   })
      // },
      // changWarnType(value) {
      //   this.rightQueryType = value
      //   console.log('rightQueryType', this.rightQueryType)
      //   if (this.rightQueryType != '工况智能识别参数预警') {
      //     this.queryWarn()
      //   }
    },
    loadLeftData() {
      console.log(this.ipagination)
      console.log('created=======')
      this.tableLoading = true
      const queryIndex = ++this.tableQueryIndex
      var params = {
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize
      } //查询条件
      if (this.queryParams.dw && this.queryParams.fw != 'person') {
        params['dw'] = this.queryParams.dw
      }
      if (this.queryParams.jh) {
        params['jh'] = this.queryParams.jh
      }

      this.loading = true
      getAction('/focusJh/getJh', params)
        .then(res => {
          if (queryIndex !== this.tableQueryIndex) {
            throw exception
          }
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
            this.tempjhList = []
            res.result.records.forEach(item => {
              this.tempjhList.push(item.jh)
            })
            console.log('tempjhList', this.tempjhList.join())
            this.jhList = this.tempjhList.join()
            if (this.dataSource.length === 0) {
              this.$message.warning('当前关注井列表为空，您可以点击添加按钮进行添加')
              return
            }
            console.log('this.jhList ', this.jhList)
            this.$refs.warnTableRef.loadData(this.jhList, this.dataSource, this.queryParams.fw)
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
        .finally(() => {
          this.tableLoading = false
        })
    },
    start() {
      setTimeout(() => {
        this.loading = false
        this.selectedRowKeys = []
      }, 1000)
    },
    onSelectChange(selectedRowKeys) {
      console.log('aa', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
      console.log('bb', this.tempjhList.join())
      if (selectedRowKeys.length == 0) {
        this.jhList = this.tempjhList.join()
      } else {
        this.jhList = this.selectedRowKeys
          .map(item => {
            return this.dataSource[item].jh
          })
          .join()
      }

      console.log('a', this.jhList)
    },
    onSelectAllJh(selected, selectedRows, changeRows) {
      console.log('全选或取消全选', selected, selectedRows, changeRows)
    },
    handleSelect(record) {
      console.log(record)
      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: 1,
        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() })
      this.$emit('ok')
      this.$router.push({ name: 'topCompare', query: { jh: parmams.JH, ltd: 1 } })
    },
    closeModel() {
      this.$emit('ok')
    },
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination
      console.log(this.ipagination)
      this.loadLeftData()
    },
    delFocus(record) {
      var that = this
      const parmams = { jh: record.jh }
      warnApi.deleteFocusJh(parmams).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadLeftData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    openSettings(record) {
      // console.log(record)
      this.selectedJH = record.jh
      this.showDialog = true
    },
    queryWarn() {
      this.$refs.warnList.searchQuery()
    },
    addFoucsWell() {
      const that = this
      this.$dialog(
        FocusSelectWell,
        {
          on: {
            close() {
              that.loadLeftData()
            }
          }
        },
        {
          title: '我的关注井',
          width: document.body.offsetWidth * 0.85,
          height: document.body.offsetHeight * 0.85,
          centered: true,
          maskClosable: true,
          okButtonProps: { style: { display: 'none' } },
          cancelText: '关闭'
        }
      )
    },
    fwChanged() {
      if (this.queryParams.fw === 'dept') {
        this.queryParams.dw = this.ejdwList[0].key
      } else {
        this.queryParams.dw = undefined
      }
      this._debounceRefreshTable()
    },
    jumpTo() {
      this.$router.push({ name: '/WarningPage' })
    }
  },
  mounted() {
    // warnApi
    //   .getEjdwList({})
    //   .then(res => {
    //     const ejdw = Vue.ls.get(USER_INFO).ejdw
    //     if (ejdw) {
    //       this.ejdwList = [{ key: ejdw, title: ejdw }]
    //     } else {
    //       this.ejdwList = res.result.data.map(k => {
    //         return { key: k.G_CNAME, title: k.G_CNAME }
    //       })
    //     }
    //   })
    //   .catch(e => {
    //   })

    warnApi
      .getRbEjdwList({})
      .then(res => {
        this.ejdwList = res.result.data.map(k => {
          return { key: k.EJDW, title: k.EJDW }
        })
      })
      .catch(e => {
      })


  }
}
</script>

<style lang='less' scoped>
@import '~@assets/less/common.less';

@tableHeight: calc(100% - 35px);

.options-list-l {
  height: 100%;
  border: 2px solid #e8e8e8;
  position: relative;
  padding: 10px 5px 0px 5px;
  margin-bottom: 10px;
}

.options-list-r {
  height: 100%;
  border: 2px solid #e8e8e8;
  position: relative;
  padding: 10px 5px;
}

.options-list-l /deep/ .ant-table-body {
  min-height: 82vh;
}

.options-list-r /deep/ .ant-table-body {
  min-height: 50vh;
}

h4 {
  position: absolute;
  top: -14px;
  padding: 1px 8px;
  margin-left: 16px;
  border-radius: 2px 2px 0 0;
  background: #fff;
  font-size: 14px;
  width: auto;
}

.left-table {
  margin-top: 0px;
  /*height: 100%;*/
  height: calc(100vh - 145px);

  /deep/ .ant-spin-nested-loading {
    height: @tableHeight;

    .ant-spin-container {
      height: 100%;

      .ant-table {
        height: 100%;

        .ant-table-content {
          height: 100%;

          .ant-table-scroll {
            height: 100%;
            overflow: hidden;
          }
        }
      }
    }
  }
}

.page-container {
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 10px;
  height: 90%;
}

/deep/ .ant-table-pagination.ant-pagination {
  margin: 0;
}

/deep/ .ant-modal-body {
  padding: 10px;
}
</style>
