<template>
  <div class="newQuery">
    <div class="newQuery-contents">
      <div class="newQuery-head flex">
        <div class="newQuery-head-left flex-wrap">
          <div class="title">高级查询</div>
          <div class="btns">
            <el-scrollbar ref="scrollContainer" :vertical="false">
              <el-button v-for="(item,index) in queryItems" :key="index" @click="handleClick(item)" size="mini" plain type="primary">
                <span class="btnName">{{ item.name }}</span>
                <span @click.stop="handleRemove(item)" class="btnIcon"><i class="el-icon-close"></i></span>
              </el-button>
            </el-scrollbar>
          </div>
        </div>
        <div class="newQuery-head-right flex-wrap">
          <template v-if="flag">
            <!-- <el-button @click="handleAdd" size="mini" plain type="primary">新增</el-button> -->
            <el-button @click="saveItem" size="mini" plain type="primary">保存条件</el-button>
          </template>
          <el-button @click="handleSearch" size="mini" class="r10" plain type="primary">查询</el-button>
          <img @click="handleDown" class="btn-square btn-shadow" src="@/assets/baggage/ic_export.png" title="导出">
        </div>
      </div>
      <div class="newQuery-tab">
        <div @click="flag = !flag " class="msg">
          <span v-if="flag" class="el-icon-caret-top"></span>
          <span v-else class="el-icon-caret-bottom"></span>
        </div>
      </div>
      <div v-if="flag" class="newQuery-search">
        <Search :dataQuery="dataQuery" @getColData="getColData" ref="searchTable" />
      </div>
      <div :style="{height:tableHeight}" class="newQuery-table">
        <Table :pageSize="999" style="height:100%" ref="queryTable" :tableTag="tableTag" />
      </div>
    </div>
    <Dialog width="520px" :flag="diaFlag">
      <div class="dialog-content">
        <div class="title">查询条件保存</div>
        <div class="contents">
          <el-form ref="form" :model="formObj" label-width="80px">
            <el-form-item label="条件名称">
              <el-input clearable v-model="formObj.name" placeholder="请输入条件名称"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="foot right">
          <el-button size="medium" @click="handleOk" class="r24" type="primary">确定</el-button>
          <el-button @click="diaFlag = false" size="medium">取消</el-button>
        </div>
      </div>
    </Dialog>
    <!--删除-->
    <Dialog :flag="rmFlag">
      <div class="airportInfoDialog">
        <div class="title del-title">删除</div>
        <div class="content del-content">
          <span class="el-icon-error error r10"></span>您是否确认删除<span class="error l10">{{ rmTitle }}</span>
          ？
        </div>
        <div class="foot right Delfoot">
          <el-button size="medium" class="r24" @click="tableRemove" type="danger">删除</el-button>
          <el-button size="medium" @click="rmFlag = false">取消</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import Search from './components/search.vue'
import Table from './components/table.vue'
import Dialog from '@/layout/components/Dialog/index.vue'
import { getToken } from '@/utils/auth'
import pf from '@/layout/mixin/publicFunc'
export default {
  name: 'NewQuery',
  components: { Search, Table, Dialog },
  mixins: [pf],
  data () {
    return {
      queryBtns: [],
      flag: false,
      queryType: '',
      diaFlag: false,
      rmFlag: false,
      formObj: {
        name: ''
      },
      queryArrs: [],
      nameArrs: [],
      rmObj: {},
      rmTitle: '',
      tbObj: {},
      dataQuery: [],
      tableTag: {},
      clkItem: {},
      clkArrs: [],
      queryItems: JSON.parse(localStorage.getItem('localItems')) ?? []
    }
  },
  computed: {
    tableHeight () {
      if (this.flag) {
        return 'calc(100% - 300px)';
      } else {
        return 'calc(100% - 80px)';
      }
    }
  },
  mounted () {
    const { query } = this.$route
    if (query && Object.keys(query).length) {
      const queryData = query
      const datas = []
      for (const key in queryData) {
        if (Object.hasOwnProperty.call(queryData, key)) {
          const val = queryData[key]
          const comparator = key == 'startDate' ? '>=' : key == 'endDate' ? '<=' : '='
          const column = key == 'startDate' ? 'carrierFlightsDate' : key == 'endDate' ? 'carrierFlightsDate' : key
          const r = {
            // left: '(',
            column: column,
            comparator,
            value: val,
            // right: ')',
            connector: 'and'
          }
          datas.push(r)
        }
      }
      this.flag = true
      setTimeout(() => {
        this.dataQuery = datas
        this.tableTag = {
          filter: datas
        }
      }, 50);
    }
  },
  methods: {
    //删除查询条件
    handleRemove (item) {
      this.rmFlag = true
      this.rmObj = item
      this.rmTitle = item.name
    },
    //新增查询
    handleAdd () {
      this.$refs.searchTable.addParamsHandler()
    },
    //历史查询条件点击
    handleClick (item) {
      this.flag = true
      const { name, value } = item
      this.formObj.name = name
      this.clkItem = item
      setTimeout(() => {
        this.dataQuery = value
        this.tableTag = {
          filter: value
        }
      }, 50);
    },
    //table导出
    handleDown () {
      this.$refs.queryTable.exportHandler()
    },
    // 保存条件
    saveItem () {
      this.diaFlag = true
      this.queryType = 'save'
      this.$refs.searchTable.advancedQueryHandler()
    },
    //获取缓存数据
    getLocalData () {
      const datas = localStorage.getItem('localItems')
      if (datas) {
        const newDatas = JSON.parse(datas)
        return newDatas
      } else {
        return []
      }
    },
    //查询数据
    getColData (arrs) {
      if (this.queryType == 'save') {
        if (Object.keys(this.clkItem).length) {
          this.clkArrs = arrs
        } else {
          this.queryArrs.push(arrs)
        }
      } else {
        this.tableTag = {
          filter: arrs
        }
      }
    },
    //查询
    handleSearch () {
      this.queryType = 'query'
      this.$refs.searchTable?.advancedQueryHandler()
    },
    //确定-保存条件
    handleOk () {
      const localDatas = this.getLocalData()
      if (Object.keys(this.clkItem).length) {
        this.$refs.searchTable.advancedQueryHandler()
        const { name } = this.clkItem
        const forName = this.formObj.name
        const newDatas = {}
        localDatas.filter((item, index) => {
          if (item.name === name) {
            newDatas.index = index
            newDatas.values = this.clkArrs.length ? this.clkArrs : item
          }
        })
        if (Array.isArray(newDatas.values)) {
          localDatas[newDatas.index].name = forName
          localDatas[newDatas.index].value = newDatas.values
        } else {
          newDatas['values'].name = forName
          localDatas[newDatas.index] = newDatas.values
        }
        this.queryItems = localDatas
      } else {
        let datas = []
        const name = this.formObj.name
        this.nameArrs.push(name)
        const nameIndex = this.nameArrs.slice(-5)
        const arrs = _.cloneDeep(this.queryArrs).slice(-5)
        arrs.forEach((item, index) => {
          const obj = {
            name: nameIndex[index],
            value: item,
            // userid: getToken('userid')
          }
          datas.push(obj)
        })
        if (localDatas && localDatas.length) {
          datas = [...localDatas, ...datas]
        }
        const caps = _.uniqBy(datas, 'name')
        this.queryItems = caps.slice(-5)
        this.formObj.name = ''
      }
      localStorage.setItem('localItems', JSON.stringify(this.queryItems))
      this.diaFlag = false
    },
    //确定-删除
    tableRemove () {
      const item = this.rmObj
      const datas = JSON.parse(localStorage.getItem('localItems'))
      if (datas && datas.length) {
        datas.forEach((nitem, index) => {
          if (item.name == nitem.name) {
            datas.splice(index, 1)
          }
        })
      }
      this.queryItems = datas
      localStorage.setItem('localItems', JSON.stringify(datas))
      this.clkItem = {}
      this.dataQuery = []
      this.formObj.name = ''
      this.rmFlag = false
    }
  }
}
</script>

<style lang="scss" scoped>
.newQuery {
  padding: 24px;
  height: calc(100vh - 80px);
  &-contents {
    height: 100%;
    border-radius: 4px;
    position: relative;
  }
  .r10 {
    margin-right: 10px;
  }
  &-tab {
    position: absolute;
    left: 0;
    top: 78px;
    width: 100%;
    height: 5px;
    background-color: #b2cbde;
    z-index: 100;
    text-align: center;
    .msg {
      display: inline-block;
      width: 100px;
      height: 12px;
      background-color: #b2cbde;
      border-radius: 0px 0px 4px 4px;
      cursor: pointer;
      color: #fff;
    }
  }
  &-head {
    padding: 24px;
    background-color: #fff;
    border-radius: 4px 4px 0px 0px;
    .title {
      font-size: 26px;
      font-weight: 500;
      margin-right: 50px;
    }
    .btns {
      max-width: 750px;
      white-space: nowrap;
      .btnIcon {
        margin-left: 15px;
      }
    }
  }
  &-table {
    padding: 0 24px;
    background-color: #fff;
    border-radius: 0px 0px 4px 4px;
  }
}
</style>
