<template>
  <!-- 远程搜索 -->
  <div id="Remote_search" class="Remote_search">
    <div class="search">
      <div v-if="showType==='list'" class="search_input">
        <el-autocomplete
          ref="autocomleteInput"
          v-model="search"
          v-bind="$attrs"
          :disabled="disabled"
          :fetch-suggestions="querySearch"
          :value-key="markProp.name"
          clearable
          :placeholder="placeholder"
          :popper-class="showClassName?'equipmentStyle':'resume_autocomplete_input'"
          suffix-icon="el-icon-caret-bottom"
          @focus="handleFocus"
          @blur="handlBlur"
          @clear="clearSelect"
          @select="handleSelect"
        >
          <template #default="{ item }">
            <slot :item="item"></slot>
          </template>
        </el-autocomplete>
        <slot name="searchBtn"></slot>
      </div>
      <div v-else class="search_tree">
        <el-cascader
          v-model="search"
          v-bind="$attrs"
          ref="cascaderMenu"
          :class="{'hasDefaultValue':search&&search.length>0}"
          :collapse-tags="collapseTags"
          :disabled="disabled"
          :options="treeData"
          :props="cascaderProps"
          :show-all-levels="false"
          clearable
          filterable
          size="mini"
          style="font-size:14px!important"
          @change="checkTreeNode"
          @visible-change="getTreeData"
        >
          <slot slot-scope="{ node, data }" :data="data" :node="node"></slot>
        </el-cascader>
        <div v-if="create" class="createIconBox">
           <i class="el-icon-edit-outline createIcon" :size="20" @click="createShowFlag = true"></i>
        </div>
      </div>
    </div>
    <div class="resume_searchmore">
      <enoDialog :show.sync="dialogFlag" :title="title" :width="width" append-to-body top="5vh">
        <div v-if="searchForm">
          <enoSearchForm :key="searchFormKey" :onQuery="formSearch" labelWidth="80px" :itemList="itemList" multiSearch></enoSearchForm>
        </div>
        <div class="resume_searchmore_input" v-else>
          <el-input v-model="searchValue" @change="searchChange" :placeholder="tablePlaceholder?tablePlaceholder:'请输入'">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="searchChange"></i>
          </el-input>
        </div>
        <div class="table_wrapper" style="height: 470px;">
          <enoTable :table-data="tableData.records" height="451px" @row-click="tableRowSelect" :loading="loading">
            <el-table-column v-for="(item,index) in  tableColumnList" :key="index" :column-key="item.prop" :label="item.label" :prop="item.prop" :width="item.width" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-switch v-if="item.showType==='switch'" v-bind="item.otherAttr" :value="scope.row[item.prop]"></el-switch>
                <span v-else-if="item.showType==='object'">{{ scope.row[item.prop] ? scope.row[item.prop][item.otherAttr.prop] : '' }}</span>
                <span v-else-if="item.showType==='translate'">
                  <span
                    v-for="(itemKid,indexKid) in String(scope.row[item.prop]).split(',')"
                    :key="indexKid"
                  >{{ item.otherAttr[itemKid] }}{{ indexKid === String(scope.row[item.prop]).split(',').length - 1 ? '' : '，' }}</span>
                </span>
                <span v-else-if="item.showType==='html'" v-html="item.otherAttr[scope.row[item.prop]]"></span>
                <span v-else-if="item.showType==='connect'">{{item.otherAttr['connect']+scope.row[item.prop]}}</span>
                <span v-else>
                  <template v-if="!item.slotName">{{ scope.row[item.prop]}}</template>
                  <template v-else-if="item.slotName==='default'">
                    <slot :item="scope.row"></slot>
                  </template>
                  <template v-else>
                    <slot name="uscc" :item="scope.row"></slot>
                  </template>
                </span>
              </template>
            </el-table-column>
          </enoTable>
        </div>
        <enoPaging slot="append" :pager.sync="pager" :onQuery="searchTable" :total="tableData.total" position="left"></enoPaging>
      </enoDialog>
    </div>
    <div v-if="create">
       <enoDialog class="createDialog" append-to-body :modal="createModal" :title="createTitle" ref="createSlot" :key="createKey" @close-click="createClose" @confirm-click="createConfirm" :show.sync="createShowFlag">
           <slot name="create"></slot>
       </enoDialog>
    </div>
  </div>
</template>

<script>
export default {
  name: 'enoRemoteSearch',
  props: {
    title: String,
    width: {
      type: String,
      default: '1160px',
    },
    url: {},
    disabled: Boolean,
    tableColumnList: {
      type: Array,
      default: () => {
        return []
      },
    },
    markProp: {
      type: Object,
      default: () => {
        return {
          name: 'name',
          key: 'id',
          initKey:'id'
        }
      },
    },
    value: {},
    createModal:{
      type: Boolean,
      default: true,
    },
    create:Boolean,
    createTitle:{
      type: String,
      default: '新建',
    },
    params: Object,
    getParams: String,
    initValue: [String, Number],
    initName: {},
    showType: {
      type: String,
      default: 'list',
    },
    treeSelectType: {
      type: String,
      default: 'radio',
    },
    selfTempalteAttr: {
      type: Object,
      default: () => {
        return {
          name: 'name',
          number: 'number',
        }
      },
    },
    multipleTree: {
      type: Boolean,
      default: false,
    },
    tablePlaceholder: String,
    exclude: [String, Number], //排除选项
    collapseTags: {
      type: Boolean,
      default: false,
    },
    //是否初始化下拉框.配合树下拉框回显
    initselect: {
      type: Boolean,
      default: false,
    },
    checkStrictly: {
      type: Boolean,
      default: true,
    },
		emitPath: {
		  type: Boolean,
		  default: false,
		},

    //搜索框属性
    searchProp: {
      type: String,
      default: 'condition',
    },
    mismatchClear: {
      type: Boolean,
      default: true,
    },
    // el-autocomplete下拉框增加popper-class属性值(改变弹框宽度)
    showClassName:{
      type: Boolean,
      default: false,
    },
    searchForm:Boolean,
    itemList:{
      type: Array,
      default: ()=>{
        return []
      },
    }
  },
  data() {
    return {
      search: this.initName,
      searchValue: '',
      dialogFlag: false,
      treeData: [],
      tableData: {},
      searchParams: this.params || {},
      placeholder: '请选择',
      pager: {
        size: 10,
        current: 1,
      },
      isEmptyInitName: true,
      dataArr: [],
      createShowFlag:false,
      createKey:1,
      loading:true,
      formSearchParams:{},
      searchFormKey:'searchFormKey'
    }
  },
  watch: {
    initName(newVal) {
      this.search = newVal
    },

    search(val) {
      if (!val && this.isEmptyInitName) {
        if (typeof this.value === 'number') {
          this.$emit('input', 0)
        } else {
          this.$emit('input', '')
        }
      }
      this.$emit('update:initName', val)
    },

    value(newVal) {
      if (!newVal) {
        this.search = ''
      }
    },
    params(newVal) {
      this.searchParams = newVal
    },

    dialogFlag(val) {
      if (!val) {
        this.pager.current = 1
        this.searchParams[this.searchProp] = ''
        this.searchValue = ''
        this.formSearchParams = {}
        this.searchFormKey += 1
        this.$refs.enoPaging.current = 1; // 强制修改页码
			  this.$store.commit('updatePageIndex', 1)
      }
    },
  },
  created() {
    if (this.initselect) {
      this.searchParams.status = 'enable'
      this.getTreeData(true)
    }
  },
  computed: {
    cascaderProps() {
      return {
        multiple: this.multipleTree,
        checkStrictly: this.checkStrictly,
        value: this.markProp.key,
        label: this.markProp.name,
        children: this.markProp.children,
        emitPath: this.emitPath,
        expandTrigger: 'hover',
      }
    },
  },
  methods: {
    createConfirm(){
        this.$refs.createSlot.$slots.default[0].child.save().then((data)=>{
            if(data){
              this.$emit('input', data.value)
              this.$emit('change', data)
              if(this.showType == 'tree'){
                this.search = data.value;
                this.getTreeData(true);
                this.$emit('update:init-name', data.value)
              }
              else{
                this.$emit('update:init-name', data.name)
              }
              this.createShowFlag = false
            }
        })
    },
    createClose(){
      //重置dialog
      this.createKey += 1
    },
    searchChange() {
      this.pager.current = 1
      this.searchTable()
    },
    changePageSize() {
      this.searchTable()
    },
    //页码
    pageChange() {
      this.searchTable()
    },
    // 远程搜索
    querySearch(data, cb) {
      data = this.search
      this.listSearch().then(() => {
        this.filterDataArr(data, cb)
      })
    },

    /* 获取列表数据 */
    async listSearch() {
      return this.dealWidthSearchUrl().then((response) => {
        if (response.code === '200') {
          this.dataArr = response.data.records || response.data
          return response.data.records || response.data
        } else {
          this.$message({
            type: 'error',
            message: response.data || '获取失败',
          })
        }
      })
    },

    /* 过滤数据 */
    filterDataArr(data, cb) {
      if (this.exclude) {
        let excludeValue = this.exclude
        if (this.exclude === 'company') {
          excludeValue = localStorage.getItem('companyId')
        }
        if (this.exclude === 'user') {
          excludeValue = this.$store.state.userInfo.id
        }
        this.dataArr = this.dataArr.filter((value) => {
          return value[this.markProp.key] !== excludeValue
        })
      }

      //去除前端过滤逻辑
      let results = this.dataArr
      // results = data
      //   ? this.dataArr.filter((value) => {
      //       return (
      //         value[this.markProp.name] &&
      //         value[this.markProp.name].includes(data)
      //       )
      //     })
      //   : this.dataArr

      /* 无匹配数据时 */
      this.popperClass = ['resume_autocomplete_input'] //还原下拉弹窗初始类名
      if (!results.length) {
        results.push('')
        this.$refs.autocomleteInput.$refs.suggestions.referenceList.classList.add(
          'hidden'
        )
        this.removeSelfAddNode()
        this.addNoContentNode()
      } else {
        this.$refs.autocomleteInput.$refs.suggestions.referenceList.classList.remove(
          'hidden'
        )
        this.removeSelfAddNode()
      }

      /* 使用表格弹窗 */
      if (this.tableColumnList.length > 0 && results.length > 9) {
        this.addSearchMoreNode()
      }
      if(this.create){
        this.addCreateNode()
      }

      cb(results)
    },

    //搜索接口地址处理
    dealWidthSearchUrl: function () {
      this.loading = true;
      let promiseObj
      let params = {}

      if (this.getParams) {
        params = this.getParams
      } else {
        params = {
          condition:this.search,
          ...this.searchParams,
          current: this.pager.current,
          size: this.tableColumnList.length > 0 ? this.pager.size : 2000,
          ...this.formSearchParams
        }
      }
      if(!this.dialogFlag && typeof params!== 'string'){
        params.condition = this.search
      }

      if (typeof this.url === 'string') {
        let url = this.url.split('.')
        promiseObj = new Promise((resolve, reject) => {
          this.$http[url[0]]
            [url[1]](params)
            .then((response) => {
              resolve(response)
              this.loading = false;
            })
            .catch((err) => {
              reject(err)
              this.loading = false;
            })
        })
      } else if (typeof this.url === 'function') {
        promiseObj = new Promise((resolve, reject) => {
          this.url(params)
            .then((response) => {
              resolve(response)
              this.loading = false;
            })
            .catch((err) => {
              reject(err)
              this.loading = false;
            })
        })
      }
      return promiseObj
    },

    /* 添加暂无数据节点 */
    addNoContentNode() {
      let $refernceList =
        this.$refs.autocomleteInput.$refs.suggestions.referenceList
      if (
        $refernceList.parentNode.childNodes &&
        $refernceList.parentNode.childNodes.length > 1
      )
        return
      let div = document.createElement('div')
      div.innerText = '暂无匹配数据'
      div.style.cssText = `color:#828282;text-align:center;padding:5px 20px;linr-height:34px;`
      $refernceList.parentNode.appendChild(div)
    },

    /* 添加表格搜索按钮 */
    addSearchMoreNode() {
      let $refernceList =
        this.$refs.autocomleteInput.$refs.suggestions.referenceList
      if (
        $refernceList.parentNode.childNodes &&
        $refernceList.parentNode.childNodes.length > 1
      )
        return
      let div = document.createElement('div')
      div.innerText = '搜索更多'
      div.addEventListener('click', () => {
        this.dialogFlag = true
        this.tableSearch()
        this.$refs.autocomleteInput.$refs.suggestions.showPopper = false
      })
      div.style.cssText = `color:#4880ff;padding:5px 20px;linr-height:34px;cursor:pointer;`
      $refernceList.parentNode.appendChild(div)
    },
    addCreateNode(){
      let $refernceList =
        this.$refs.autocomleteInput.$refs.suggestions.referenceList
      let div = document.createElement('div')
      div.innerText = '创建并编辑'
      div.addEventListener('click', () => {
        this.$refs.autocomleteInput.$refs.suggestions.showPopper = false;
        this.createShowFlag = true;
      })
      div.style.cssText = `color:#4880ff;padding:5px 20px;linr-height:34px;cursor:pointer;`
      $refernceList.parentNode.appendChild(div)
    },
    addCreateTreeNode(){
      let $refernceList =
        this.$refs.autocomleteInput.$refs.suggestions.referenceList
      let div = document.createElement('div')
      div.innerText = '创建并编辑'
      div.addEventListener('click', () => {
        this.$refs.autocomleteInput.$refs.suggestions.showPopper = false;
        this.createShowFlag = true;
      })
      div.style.cssText = `color:#4880ff;padding:5px 20px;linr-height:34px;cursor:pointer;`
      $refernceList.parentNode.appendChild(div)
    },

    /* 删除按钮 */
    removeSelfAddNode() {
      let $refernceListParent =
        this.$refs.autocomleteInput.$refs.suggestions.referenceList.parentNode

      if (!$refernceListParent) return
      if (
        $refernceListParent.childNodes &&
        $refernceListParent.childNodes.length > 1
      ) {
        $refernceListParent.removeChild(
          $refernceListParent.childNodes[
            $refernceListParent.childNodes.length - 1
          ]
        )
      }
    },

    /*表格搜索*/
    tableSearch: function () {
      this.dealWidthSearchUrl().then((response) => {
        if (response.code === '200') {
          if (this.exclude) {
            let excludeValue = this.exclude
            if (this.exclude === 'company') {
              excludeValue = localStorage.getItem('companyId')
            }
            if (this.exclude === 'user') {
              excludeValue = this.$store.state.userInfo.id
            }
            response.data.records = response.data.records.filter((value) => {
              return value.id !== excludeValue
            })
          }
          this.tableData = response.data
        } else {
          this.$message({
            type: 'error',
            message: response.data || '获取失败',
          })
        }
      })
    },

    /*表格选择*/
    tableRowSelect: function (row) {
      // this.search=row[this.markProp.name];
      this.$emit('input', row[this.markProp.key])
      this.$emit('update:init-name', row[this.markProp.name])
      this.$emit('change', row)
      this.dialogFlag = false
    },

    // 选择下拉框
    handleSelect(item) {
      this.$emit('input', item[this.markProp.key])
      this.$emit('update:init-name', item[this.markProp.name])
      this.$emit('change', item, this.markProp)
    },

    //清空選擇
    clearSelect() {
			  this.search = '';
        if (typeof this.value === 'number') {
          this.$emit('input', 0)
        } else {
          this.$emit('input', '')
        }
        this.$emit('update:init-name', '')
        this.$emit('clear')
        this.placeholder = '请选择'
    },

    // 表格搜索
    searchTable() {
      this.searchParams[this.searchProp] = this.searchValue
      this.tableSearch()
    },
    formSearch(params={}){
      delete params.size
      delete params.current
      this.formSearchParams = {...this.searchParams, ...params}
      this.tableSearch()
    },

    //获取树结构数据
    getTreeData: function (val) {
      //val为true是展开时
      if (val) {
        this.dealWidthSearchUrl().then((response) => {
          if (response.code === '200') {
            this.dealWidthTreeData(response.data.records || response.data)
            if (
              typeof this.url === 'string' &&
              this.url.split('.')[0] === 'fault'
            ) {
              this.treeData = response.data[0][this.markProp.children]
            } else {
              this.treeData = response.data
            }
          } else {
            this.$message({
              type: 'error',
              message: response.data || '获取失败',
            })
          }
        })
      }
    },

    /*处理级联数据*/
    dealWidthTreeData: function (data) {
      data.forEach((value) => {
        if (value[this.markProp.initKey] == this.initValue) {
          this.search = value[this.markProp.key]
        }
        if (
          !value[this.markProp.children] ||
          value[this.markProp.children].length === 0
        ) {
          value[this.markProp.children] = null
        } else {
          this.dealWidthTreeData(value[this.markProp.children])
        }
      })
    },

    //树节点选择
    checkTreeNode: function (data, checked) {
      this.$refs.cascaderMenu.dropDownVisible = false
      this.$emit('input', data)
    },

    //获取焦点
    handleFocus() {
      if (this.search) {
        this.isEmptyInitName = false //是否更新组件的value值
        this.placeholder = this.search || '请选择'
        this.search = ''
      }
    },

    //失去焦点
    handlBlur() {
      if (this.placeholder !== '请选择') {
        this.search = this.placeholder
        this.placeholder = '请选择'
        this.isEmptyInitName = true
      }
    },
  },
}
</script>

<style lang="less">
  #Remote_search {
    .search {
      .search_tree{
        display: flex;

        .createIconBox{
          display: flex;
          align-items: center;
          margin-left: 5px;

          .createIcon{
            cursor: pointer;
            font-size: 20px;
          }
        }


      }
      .el-autocomplete {
        width: 100%;

        .el-input__suffix {
          .el-input__suffix-inner {
            .el-icon-caret-bottom {
              color: #979797;
            }
          }
        }

        &[aria-expanded] {
          .el-input__suffix {
            .el-input__suffix-inner {
              .el-icon-caret-bottom {
                transform: rotate(180deg);
              }
            }
          }
        }

        .el-autocomplete-suggestion__wrap {
          .el-autocomplete-suggestion__list {
            li {
              &:hover {
                background-color: @bgColor;
                color: @mainColor;
              }
            }
          }
        }
      }

      .el-cascader {
        vertical-align: bottom;

        &.hasDefaultValue {
          .el-input {
            .el-input__inner {
              &::-webkit-input-placeholder {
                color: #333;
              }
            }
          }

          .el-cascader__tags {
            .el-cascader__search-input {
              &::-webkit-input-placeholder {
                font-size: 14px;
                color: #333;
              }
            }
          }
        }

        .el-input__suffix {
          color: #979797;

          .el-input__suffix-inner {
            .el-icon-arrow-down {
              color: #979797;
              margin-right: 0;

              &::before {
                content: '\e790';
                color: #979797;
              }

              &::after {
                content: '' !important;
              }
            }
          }
        }

        .el-cascader__tags {
          .el-cascader__search-input {
            margin-left: 12px;
          }
        }
      }
    }
  }

  .el-cascader__dropdown {
    .el-cascader-panel {
      .el-cascader-menu {
        .el-cascader-menu__wrap {
          .el-scrollbar__view {
            .el-cascader-node {
              max-width: 300px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
        }
      }
    }
  }
  .equipmentStyle{
    width: 400px!important;
    .hidden {
      display: none;
    }
  }
  .resume_autocomplete_input {
    .hidden {
      display: none;
    }
  }

  .resume_searchmore_input {
    float: right;
    height: 32px;
    width: 320px;
    line-height: 32px;
    margin-bottom: 10px;

    .el-input {
      .el-input__suffix {
        .el-input__validateIcon {
          display: none;
        }
      }
    }
  }
  .el-pagination__sizes {
    .el-select {
      .el-input {
        .el-input__suffix {
          .el-input__validateIcon {
            display: none;
          }
        }
      }
    }
  }

  .createDialog {
    .el-dialog{
      .el-dialog__body{
        .customFilter{
          .el-row{
            max-width: none !important;
          }
        }
      }
    }

  }
</style>
