<template>
  <div class="searchPatent">
    <div style="display: flex;align-items: center;">
      <el-cascader :options="options" @change="cascaderChange" v-model="value" :show-all-levels="false" size="small"
        style="width: 150px;"></el-cascader>

      <div style="margin: 0px 10px 0px 10px;">
        <el-input v-if="!isControl.select" v-model="inputValue" size="small"
          :placeholder="isControl.placeholder"></el-input>
        <el-select v-else v-model="inputValue" multiple collapse-tags placeholder="请选择" size="small">
          <el-option v-for="item in typeStatus[isControl.selectCheck]" :key="item.value" :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <el-button @click="search" type="primary" size="small">检索</el-button>

      <el-popover placement="bottom" v-if="searchStorageText.length > 0" width="260" trigger="click">
        <div style="height: 200px;overflow-x: auto;">
          <div v-for="(item, index) in searchStorageText" :key="index">
            <div style="margin-bottom:10px;background:#F0F9EB;padding: 10px 5px;">
              <span>{{ item.field.show }}</span>
              <span> = </span>
              <template>
                <span>(</span>
                <span v-for="(result, i) in item.value" :key="i" @click="resultBtn(item, index, i,1)"  style="cursor: pointer;">
                  {{ result.show }}
                  <i v-if="item.value.length > 1" class="el-icon-close"></i>
                  <b v-if="item.value.length - 1 > i"> OR </b>
                </span>
                <span>)</span>
                <span @click="resultBtn(item, index, 0,2)" style="cursor: pointer;"><i class="el-icon-close"></i></span>
              </template>
            </div>
          </div>
        </div>

        <el-button slot="reference" type="primary" size="small" class="margin-left_10">检索式</el-button>
      </el-popover>

    </div>


  </div>
</template>

<script>
export default {
  props: {
    // 所有的检索字段（包含自定义字段）
    searchFiled: {
      type: Array,
      default: () => {
        return []
      }
    },
    searchPatentCheck: {
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      // 级联面板数据源
      options: [],
      value:['text', 'AB'],
      // 存储条件
      searchStorage: [],
      searchStorageText: [],
      // 专利检索式
      searchStr: '',
      // 自定义栏位检索式
      searchCustomStr: '',
      // 专利IPC/CPC/UPC/LOC的选项
      special: {
        MC: [
          { value: 'ipcLevel1', label: 'IPC部' },
          { value: 'ipcLevel2', label: 'IPC大类' },
          { value: 'ipcLevel3', label: 'IPC小类' },
          { value: 'ipcLevel4', label: 'IPC大组' },
          { value: 'ipcLevel5', label: 'IPC小组' },
        ],
        CPC: [
          { value: 'cpcLevel1', label: 'CPC部' },
          { value: 'cpcLevel2', label: 'CPC大类' },
          { value: 'cpcLevel3', label: 'CPC小类' },
          { value: 'cpcLevel4', label: 'CPC大组' },
          { value: 'cpcLevel5', label: 'CPC小组' },
        ],
        UPC: [
          // { value: '0', label: '分类号' },//老系统有
          { value: 'upcLevel1', label: 'UPC大类' },
          { value: 'upcLevel2', label: 'UPC小类' },
        ],
        LOC: [
          // { value: '0', label: '分类号' },//老系统有
          { value: 'locLevel1', label: 'LOC大类' },
          { value: 'locLevel2', label: 'LOC小类' },
        ],
      },
      // 类型及状态
      typeStatus: {
        //法律状态暂定
        LG: [
          { value: '1', label: '有效' },
          { value: '2', label: '无效' },
          { value: '3', label: '审中' },
        ],
        //专利类型
        PT: [
          { value: '1 OR 8', label: '发明' },
          { value: '2 OR 9', label: '实用新型' },
          { value: '3', label: '外观' },
        ],
        //专利状态
        SS: [
          { value: '1', label: '有效' },
          { value: '2', label: '无效' },
          { value: '3', label: '审中' },
        ],
      },
      // 控制检索式弹窗显示
      dialogVisible: false,
      // 选择的cascader
      casString: null,
      // 输入框的值
      inputValue: '',
      // 控制显示提示及select
      isControl: {
        placeholder: '请输入检索内容'
      },
    }
  },
  watch: {
    searchFiled: {
      deep: true,
      handler() {
        this.getGroup()
      },
    },
  },
  mounted() {
    this.getGroup()
  },
  methods: {
    // 点击检索式中的检索条件
    resultBtn(item, index, i,type) {
      if(type ==2){
        this.searchStorageText.splice(index,1)
      }else if(type == 1){
        var obj = this.searchStorageText[index]
        obj.value.splice(i,1)
        if(obj.value.length == 0){
          this.searchStorageText.splice(index,1)
        }
      }
      this.search2(1)
    },
    // cascader变化事件
    cascaderChange(val) {
      this.inputValue = ''
      // let a = this.options.find(item => {
      //   return item.value == val[0]
      // })
      // this.isControl = a.children.find(item => {
      //   return item.value == val[1]
      // })
      var a = JSON.parse(JSON.stringify(this.options))
      val.forEach((item1,index) => {
        if (index == val.length - 1) {
          this.isControl = a.children.find(item => {
            return item.value == item1
          })
        } else {
          if (index == 0) {
            a = a.find(item => {
              return item.value == item1
            })
          } else {
            a = a.children.find(item => {
              return item.value == item1
            })
          }
          
        }
      })
      this.isControl.placeholder = '请输入检索内容'
      if (this.isControl.type == '2') {
        this.isControl.placeholder = '请输入日期(格式2020 ~ 2023)'
      }
      if (val[0] == 'typeStatus') {
        this.$set(this.isControl, 'select', true)
        this.$set(this.isControl, 'selectCheck', val[val.length - 1])
      }
    },
    // 存储条件
    storage() {
      this.isControl.inputValue = this.inputValue
      var obj = {
        field:{
          search:this.isControl.value,
          show:this.isControl.label,
          group:this.isControl.group
        },
        value:[],
        op:'='
      }
      if(typeof this.isControl.inputValue == 'object'){
        var arr = this.isControl.inputValue
        arr.forEach(item=>{
          var show = item
          if(this.typeStatus[this.isControl.selectCheck]){
            var obj2 = this.typeStatus[this.isControl.selectCheck].find(item2=>{
              return item2.value == item
            })
            if(obj2){
              show = obj2.label
            }
          }
          obj.value.push(
            {
              search:item,
              show:show
            }
          )
        })
      }else{
        obj.value.push(
          {
            search:this.isControl.inputValue,
            show:this.isControl.inputValue
          }
        )
      }
      this.searchStorageText.push(obj)

    },
    getSearchOptionData() {
      if(this.searchPatentCheck && this.searchPatentCheck.length>0){
        for(var i = 0;i<this.searchPatentCheck.length;i++){
          this.searchStorageText.push(this.searchPatentCheck[i])
        }
        // this.searchPatentCheck.length = 0
      }
    },
    // 页面检索按钮
    search() {
      if (!this.isControl.value) {
        this.$message.error('检索项不能为空')
        return
      }
      if (!this.inputValue) {
        this.$message.error('检索内容不能为空')
        return
      }
      this.storage()
      this.search2(1)
    },
    search2(type) {
      if(!type){
        this.getSearchOptionData()
      }
      
      this.getSearchStorage()
    },
    // 处理检索条件
    getSearchStorage() {
      this.searchStr = ''
      let customFields = []
      let count = 0
      this.searchStorageText.forEach(item=>{
        if(item.field.group == 'nos' || item.field.filedKind == -1){
          var front = ''
          if(count!=0){
            front = ' AND '
          }else{
            count ++ 
          }
          var value = ''
          if(item.op == '≡'){
            value = item.value.map(value=>`IET@ "${value.search}"`).join(" OR ")
          }else if(item.op == '='){
            value = item.value.map(value=>value.search).join(" OR ")
          }
            // this.searchStr += `${front}${item.field.search} ${item.op} (${value})`
            this.searchStr += `${front}${item.field.search} = (${value})`
          
        }else{
          let a = {
            fieldId: item.field.search,
            fieldValue: item.value.map(value=>value.search),
            ifHaveChild:item.ifHaveChild
          }
          customFields.push(a)
        }
      })
      this.$emit('searchValue', { searchStr: this.searchStr, customFields: customFields, })

      return
     
    },


    getGroup() {
      if(!this.searchFiled||this.searchFiled.length == 0){
        return ;
      }
      let obj = {
        text: '文本',
        number: '号码',
        typeStatus: '类型及状态',
        classify: '分类',
        dateType: '日期',
        company: '公司/人',
        typeStatus: '类型及状态',
        address: '地址',
        nation: '国家/地区',
        amount: '引用',
        customField: '自定义字段',
      }
      let filedObj = {}
      let data = this.searchFiled
      for (let i = 0; i < data.length; i++) {
        if (data[i].group == 'nos') {//专利本身
          if (filedObj[data[i].groupBy]) {
            filedObj[data[i].groupBy].children.push(data[i])
          } else {
            filedObj[data[i].groupBy] = {
              value: data[i].groupBy,
              label: obj[data[i].groupBy],
              children: [
                data[i]
              ],
            }
          }
          // 给ipc、cpc、upc、loc添加大小类等
          // if (['MC', 'CPC', 'UPC', 'LOC'].includes(data[i].value)) {
          //   for (let j = 0; j < filedObj[data[i].groupBy].children.length; j++) {
          //     if (!filedObj[data[i].groupBy].children[j].children) {
          //       filedObj[data[i].groupBy].children[j].children = this.special[filedObj[data[i].groupBy].children[j].value]
          //     }
          //   }
          // }
        } else {//自定义字段
          if (filedObj[data[i].group]) {
            filedObj[data[i].group].children.push(data[i])
          } else {
            filedObj[data[i].group] = {
              value: data[i].group,
              label: obj[data[i].group],
              children: [data[i]]
            }
          }
        }
      }
      this.options = Object.values(filedObj)
      if(this.options.length>0){
        this.cascaderChange(this.value)
      }
      
    },
  },
}
</script>

<style lang="scss" scoped>
.searchPatent {
  // width: 550px;
}
</style>