<template>
  <div class="ta-search-panel">
    <ta-popover v-model="searchVisible" :width="width" :placement="placement" trigger="manual" popper-class="ta-search-panel-popper" manual @hide="tabActiveKey = '1'">
      <template slot="reference">
        <span @click="targetClick">
          <slot name="target" />
        </span>
        <a v-if="showClear" @click="clearSearch"><ta-icon type="delete" class="icon-delete" />清除搜索</a>
      </template>
      <ta-tabs v-if="searchVisible" :active-key="tabActiveKey" class="tabs-content" @change="tabChange">
        <ta-icon slot="tabBarExtraContent" type="close" class="tabs-close" @click="searchVisible = false" />
        <ta-tab-pane key="1" tab="高级查询">
          <div :id="'formPanelContent_'+id" class="form-content" :style="{'height': height-50+'px'}" :class="'formPanelContent_'+id">
            <slot name="formPanel" />
          </div>
          <div class="btn-content">
            <ta-button style="margin-right: 8px;" @click="form.resetFields()">
              重置
            </ta-button>
            <ta-dropdown-button @click="searchMenuClick">
              搜索
              <ta-menu slot="overlay" @click="searchMenuClick">
                <ta-menu-item key="1">
                  <ta-icon type="search" />搜索并保存
                </ta-menu-item>
                <ta-menu-item key="2">
                  <ta-icon type="save" />保存搜索条件
                </ta-menu-item>
              </ta-menu>
            </ta-dropdown-button>
            <span class="tips">（当前搜索过滤以高级搜索为准）</span>
          </div>
        </ta-tab-pane>
        <ta-tab-pane key="2" tab="我的搜索">
          <div class="right-box" :style="{'height': height+'px'}">
            <div v-if="showSearch.length == 0" class="no-data" :style="{'padding-top': height/2 - 40 +'px'}">
              <ta-icon type="file-text" class="no-data-icon" />暂时没有搜索条件哟~
            </div>
            <ta-collapse v-else v-model="collapseActiveKey" accordion>
              <ta-collapse-panel v-for="(item,index) in showSearch" :key="index.toString()" :header="item[2].timeShow + ' 的搜索'">
                <p v-for="(info, index1) in item[1]" :key="index1" class="show-info">
                  {{ info.label }}： {{ info.value }}
                </p>
                <div style="text-align: right;">
                  <ta-button @click="searchInfo(item[0])">
                    <ta-icon type="search" /> 搜索
                  </ta-button>
                  <ta-button @click="showConfirm(item[2].timeSave)">
                    <ta-icon type="delete" /> 删除
                  </ta-button>
                </div>
              </ta-collapse-panel>
            </ta-collapse>
          </div>
        </ta-tab-pane>
      </ta-tabs>
    </ta-popover>
  </div>
</template>
<script>
import TaPopover from '../../popover-ex'
export default {
  name: 'TaSearchPanel',
  components: { TaPopover },
  props: {
    width: {
      type: Number,
      default: 400,
    },
    height: {
      type: Number,
      default: 300,
    },
    id: {
      type: [String, Number],
      required: true,
    },
    form: {
      required: true,
    },
    placement: {
      type: String,
      default: 'bottom-end',
    },
  },
  data () {
    return {
      searchVisible: false,
      tabActiveKey: '1',
      collapseActiveKey: '0',
      showSearch: [],
      url: window.location.href,
      showClear: false,
    }
  },
  computed: {
    showSearchLabels () {
      let parentObj = document.getElementById('formPanelContent_' + this.id)
      let labels = parentObj.getElementsByTagName('label')
      let len = labels.length
      let _showLabels = {}
      for (let i = 0; i < len; i++) {
        if (labels[i].attributes.for) {
          _showLabels[labels[i].attributes.for.value] = labels[i].attributes.title.value
        }
      }
      return _showLabels
    },
  },
  created () {
    this.searchStorage = this.Base.webStorage.init('search_storage', { isLocal: true })
  },
  methods: {
    /* 搜索 */
    searchMenuClick (e) {
      let formData = this.form.getFieldsValue(), keys = Object.keys(formData), tempForm = {}, dateForm = {}, hasData = false
      keys.forEach((key) => {
        if (formData[key] != undefined) {
          if (formData[key]._isAMomentObject || ( formData[key][0] && formData[key][0]._isAMomentObject)){
            dateForm[key] = formData[key]
          } else if (formData[key].length) {
            tempForm[key] = formData[key]
          }
        }
      })
      hasData = !!(Object.keys(tempForm).length || Object.keys(dateForm).length)
      if (Object.keys(dateForm).length) {
        let dateKeyValue = this.getFormValueLabel(dateForm)
        if (dateKeyValue.length) {
          dateKeyValue.forEach(({key, value}) => {
            if (value.indexOf(',') != -1) {
              tempForm[key] = value.split(', ')
            } else {
              tempForm[key] = value
            }
          })
        }
      }

      if (e.key) {
        if (hasData) {
          this.saveForm(tempForm)
        } else {
          this.$message.info('没有需要保存的查询条件')
        }
      }

      if (e.key == undefined || e.key === '1') {
        this.$emit('search', {...tempForm})
        if (hasData) {
          this.showClear = true
        }
        this.searchVisible = false
      }
    },
    /* tab 切换 */
    tabChange (tab) {
      this.tabActiveKey = tab
      if (tab === '2') {
        this.showSearch = [...this.getShowSearch()]
      }
    },
    /* 获取以search_ 开头的localStorage，并按时间排序 */
    getShowSearch () {
      let list = this.searchStorage.getAll(), result = []
      Object.keys(list).forEach((item) => {
        if (item.indexOf('search_' + this.url + '_' + this.id) != -1) {
          result.push(JSON.parse(list[item]))
        }
      })
      let compare = function (time1, time2) {
        let val1 = time1[2].timeSave
        let val2 = time2[2].timeSave
        if (val1 < val2) { return 1 } else if (val1 > val2) { return -1 } else { return 0 }
      }
      return result.sort(compare)
    },
    /* 返回当前时间 */
    getCurrentTime () {
      let result = {}
      let d = new Date()
      result.save = d.getFullYear() + '' + ((d.getMonth() + 1) >= 10 ? +(d.getMonth() + 1) : '0' + (d.getMonth() + 1)) + '' + ((d.getDate()) >= 10 ? d.getDate() : '0' + d.getDate()) + '' + ((d.getHours()) >= 10 ? d.getHours() : '0' + d.getHours()) + '' + ((d.getMinutes()) >= 10 ? d.getMinutes() : '0' + d.getMinutes()) + '' + ((d.getSeconds()) >= 10 ? d.getSeconds() : '0' + d.getSeconds())
      result.show = d.getFullYear() + '-' + ((d.getMonth() + 1) >= 10 ? +(d.getMonth() + 1) : '0' + (d.getMonth() + 1)) + '-' + ((d.getDate()) >= 10 ? d.getDate() : '0' + d.getDate()) + ' ' + ((d.getHours()) >= 10 ? d.getHours() : '0' + d.getHours()) + ':' + ((d.getMinutes()) >= 10 ? d.getMinutes() : '0' + d.getMinutes()) + ':' + ((d.getSeconds()) >= 10 ? d.getSeconds() : '0' + d.getSeconds())
      return result
    },
    /* 保存表单数据 */
    saveForm (formData) {
      let currentTime = this.getCurrentTime()
      let formValueLabel = this.getFormValueLabel(formData)
      let setData = [formData, formValueLabel, {'timeShow': currentTime.show, 'timeSave': currentTime.save}]
      this.searchStorage.set('search_' + this.url + '_' + this.id + '_' + currentTime.save, setData)
      this.$message.success('保存成功')
    },
    /* 获取表单的value,label,key */
    getFormValueLabel (formData) {
      let formKey = Object.keys(formData), saveValueLabel = []
      formKey.forEach((key) => {
        let obj = document.querySelectorAll('.formPanelContent_' + this.id + ' #' + key)[0]
        if (obj.className.indexOf('ant-cascader-input') != -1) {
          if (obj.parentNode.innerText.length) {
            let temp = { label: this.showSearchLabels[key], value: obj.parentNode.innerText, key: key }
            saveValueLabel.push(temp)
          }
        } else if (obj.className.indexOf('ant-select') != -1 && obj.className.indexOf('ant-select-auto-complete') == -1) {
          if (obj.value.length) {
            let objLi = obj.getElementsByTagName('li'), temp = {}
            if (objLi.length) {
              let checked = []
              for (let i = 0; i < objLi.length; i++) {
                if (objLi[i].className.indexOf('choice') != -1) {
                  checked.push(objLi[i].innerText)
                }
              }
              if (checked.length) {
                temp = { label: this.showSearchLabels[key], value: checked.join(', '), key: key }
              }
            } else {
              temp = { label: this.showSearchLabels[key], value: obj.innerText, key: key }
            }
            saveValueLabel.push(temp)
          }
        } else if (obj.className.indexOf('ant-calendar-picker') != -1) {
          if (obj.childNodes[0].childNodes[0].value.length) {
            let start = obj.childNodes[0].childNodes[0].value, end = obj.childNodes[0].childNodes[2].value ? ', ' + obj.childNodes[0].childNodes[2].value : ''
            let temp = { label: this.showSearchLabels[key], value: start + end, key: key }
            saveValueLabel.push(temp)
          }
        } else if (obj.className.indexOf('ant-time-picker') != -1) {
          if (obj.childNodes[0].value.length) {
            let temp = { label: this.showSearchLabels[key], value: obj.childNodes[0].value, key: key }
            saveValueLabel.push(temp)
          }
        } else if (obj.className.indexOf('ant-radio-group') != -1) {
          for (let i = 0; i < obj.children.length; i++) {
            if (obj.children[i].className.indexOf('checked') != -1) {
              let temp = { label: this.showSearchLabels[key], value: obj.children[i].innerText, key: key }
              saveValueLabel.push(temp)
              break
            }
          }
        } else if (obj.className.indexOf('ant-checkbox-group') != -1) {
          let checked = []
          for (let i = 0; i < obj.children.length; i++) {
            if (obj.children[i].children[0].className.indexOf('checked') != -1) {
              checked.push(obj.children[i].innerText)
            }
          }
          if (checked.length) {
            let temp = { label: this.showSearchLabels[key], value: checked.join(', '), key: key}
            saveValueLabel.push(temp)
          }
        } else if (obj.className.indexOf('ta-user-input') != -1 && obj.value) {
          let temp = { label: this.showSearchLabels[key], value: obj.innerText, key: key }
          saveValueLabel.push(temp)
        } else {
          if (obj.value.length) {
            let temp = { label: this.showSearchLabels[key], value: obj.value, key: key }
            saveValueLabel.push(temp)
          }
        }
      })
      return saveValueLabel
    },
    /* 搜索表单 */
    searchInfo (form) {
      this.$emit('search', {...form})
      this.showClear = true
      this.searchVisible = false
    },
    /* 删除表单数据 */
    showConfirm (time) {
      this.$confirm({
        title: '确定要删除这条搜索吗？',
        cancelText: '取消',
        okText: '确定',
        onOk: () => {
          this.searchStorage.remove('search_' + this.url + '_' + this.id + '_' + time)
          this.showSearch = [...this.getShowSearch()]
          this.$message.success('删除成功')
        },
      })
    },
    targetClick () {
      this.searchVisible = !this.searchVisible
      this.tabActiveKey = '1'
      this.collapseActiveKey = '0'
    },
    clearSearch () {
      const {resetFields, getFieldsValue} = this.form
      resetFields()
      this.$emit('search', {...getFieldsValue()})
      this.showClear = false
    },
  },
}
</script>
