<template>
  <div>
    <div class="select-box">
        <Icon type="ios-close-circle"
            :class="{'clear-tree-icon': true, 'hidden-icon': disabled || readonly || !selectValue }"
            @click="clearList" />
        <Input ref="searchInput"
                v-model="selectValue"
                :disabled="disabled"
                :readonly="readonly || multiple"
                :class="{'multiple-input': multiple && !readonly}"
                placeholder=""
                @on-change="handleChange"
                @on-focus="handleFocus"
                @on-blur="handleBlur"
                @keydown.down.native="handleSelectNext"
                @keydown.up.native="handleSelectPrev"
                @keydown.enter.native="handleSelected">
                <Icon type="ios-more"
                      class="more-select"
                      slot="suffix"
                      @click="handleInputSelect" />
        </Input>
    </div>

    <ul ref="searchList"
        class="main-search-list acct-search-list"
        :class="{
          'is-focus': hasFocus,
          'position-left-bottom': !positionTop && positionLeft,
          'position-left-top': positionTop && positionLeft,
          'position-right-bottom': !positionTop && !positionLeft,
          'position-right-top': positionTop && !positionLeft }"
        v-show="dataListShow"
        @mouseleave="onResultList = false"
        @mouseenter="onResultList = true">
      <li :class="['acct-search-item',selectIndex === index ? 'selected' : '',{active: activeName == item.name}]"
          v-for="(item,index) in baseDataList"
          :key="item.code"
          :value="item.code"
          @click="handleMainSearchSelectClick(item)">
        <span class="acct-search-label">{{ item.name }}</span>
      </li>
      <li v-if="baseDataList.length === 0">
        <span class="list-empty">无匹配数据</span>
      </li>
    </ul>


    <!-- 弹框 -->
    <EditModal
      v-if="showModal"
      v-model="showModal"
      :title="title"
      :selection="selection"
      :table-name="tableName"
      :multiple="multiple"
      :tableKey="tableKey"
      :treeKey="treeKey"
      :tableColumns="tableColumns"
      :searchPlaceholder="searchPlaceholder"
      :authType="authType"
      :versionDate="versionDate"
      :modalWidth="modalWidth"
      :isLeaf="isLeaf"
      :hideSelected="hideSelected"
      :structtype="structtype"
      :groupTableName="groupTableName"
      :treeTableName="treeTableName"
      :filterFormular="filterFormular"
      :filterFormularSP="filterFormularSP"
      :billdefineName="billdefineName"
      :billId="billId"
      :bill="bill"
      :isFilter="isFilter"
      :rowIndex="rowIndex"
      @on-ok="onSelectOk"
    />
  </div>
</template>
<script>
import EditModal from './edit-modal.vue'
import baseDataMixin from '../util/baseDataMixin'
import indexMixin from '../util/indexMixin'
export default {
  mixins: [indexMixin, baseDataMixin],
  components: {
    EditModal,
  },
  model: {
    prop: 'value',
    event: 'data-change',
  },
  data() {
    return {
      hasFocus: false,
      positionTop: false,
      positionLeft: true,
      dataListShow: false,
      // 下拉列表
      baseDataList: [],
      selectValue: null,
      selectIndex: -1, // 当前选中的索引
      selectedItem: {}, // 选中的对象
      onResultList: false, // 判断鼠标是否停留在列表结果上
      activeName: null,

      filterFormular: true,
      selection: [],
      showModal: false,
      tableColumns: [
        {
          type: 'selection',
          key: 'select',
          width: 60,
          align: 'center',
        },
        {
          title: '代码',
          key: 'code',
          ellipsis: true,
        },
        {
          title: '名称',
          key: 'name',
          ellipsis: true,
        },
      ],
      // 基础数据查询搜索
      pageTotal: 0,
      pageSize: 20,
      pageNo: 1,
      total: 0
    }
  },

  watch: {
    value: {
      handler: function (newVal) {
        if (newVal) {
          this.init(newVal)
        } else {
          this.selectValue = newVal
        }
      },
      deep: true,
      immediate: true
    },
    filterFormular: {
      handler: function () {
        this.getBaseDataList()
      },
    }
  },
  methods: {
    init(value) {
      if (this.isCode) {
        if (Object.prototype.toString.call(value) === '[object Object]') {
          this.selectValue = value.name
          this.activeName = value.name
        } else {
          this.selectValue = value
        }
      } else {
        if (this.multiple) {
          this.selectValue = value.map(item => item.code)
        } else {
          if(Object.prototype.toString.call(value) === '[object Object]'){
            this.selectValue = value.name
            this.activeName = value.name
          }else{
            this.selectValue = value
          }
        }
      }
      this.selectValue = String(this.selectValue);
      this.findIndex()
    },
    // 弹框
    handleInputSelect () {
      if (!this.disabled) {
          if (this.value === null) {
              this.showModal = true
          } else {
              this.selection[0] = this.value
              this.showModal = true
          }
      }
    },
    // 下拉列表
    handleFocus () {
        // if (this.value) {
        //     // this.hasFocus = true
        //     // this.dataListShow = true
        //     // this.handleChange()
        // } else {
        //     this.hasFocus = true
        //     this.dataListShow = true
        //     this.getBaseDataList()
        // }
        this.selectIndex = -1
        this.hasFocus = true
        this.dataListShow = true
        this.getBaseDataList()
    },
    handleBlur () {
        if (!this.onResultList) {
          this.hasFocus = false
          this.dataListShow = false
        }

        this.selectValue = String(this.selectValue)
        if (this.value === null) {
          this.selectValue = ''
          this.selectIndex = -1
          this.selectedItem = {}
        } else{
            this.selectValue = this.value.name
            this.selectedItem = this.value
            this.findIndex()
        }

        // if (this.selectValue === '' || this.selectValue === null) {
        //     this.selectIndex = -1
        //     this.selectedItem = {}
        //     this.activeName = null
        //     this.value = null
        // } else {
        //     this.selectValue = this.value.name
        //     this.selectedItem = this.value
        //     this.findIndex()
        // }

        this.$emit('data-change', this.value)
    },
    // 输入查询时
    handleChange () {
        if (this.selectValue === '' || this.selectValue === null) {
            this.selectIndex = -1
            this.selectedItem = {}
            this.activeName = null
            // this.value = null
            // this.$emit('data-change', this.value)
        }
        let treeNode = this.getBaseDataListRefresh()
        this.refreshWhenAll(treeNode)
    },
    // 树节点
    async getBaseDataListRefresh () {
        if (this.isOrg) {
          let param = {
            pagination: false,
            parentcode: '-',
            queryDataStructure: 'ALL',
          }
          let result = await this.getOrg(param)
          this.treeData = this.formateTree(result)
        } else {
          // 修改list接口为tree接口
          const getTreeDataMap = (nodes) => {
            nodes.forEach(node => {
              this.treeDataMap[node.id] = node.children? node.children: []
              if (node.children) {
                getTreeDataMap(node.children)
              }
            })
          }
          
          const postData = {
            tableName: this.tableName,
            queryDataStructure: 'ALL',
            authType: this.authType,
            versionDate: this.versionDate,
            expression: this.filterFormular,
            'BI-SYNTAX': null
          }
          if (this.structtype === 1) {
            if (this.groupTableName.define.showFields) {
              const relevance = this.groupTableName.define.showFields.find(item => item.columnName === this.groupTableName.groupFieldName)
              let relevanceField = ''
              if (relevance) {
                relevanceField = relevance.mapping? relevance.mapping.split('.')[0]: ''
                postData.tableName = relevanceField
              }
            }
          }
          const { data } = await this.getBaseData(postData, '/baseData/data/tree')
          const formateRootNode = (nodes) => {
            let node = nodes[0]
            node.expand = true
            node.title = node.name || node.text
            node.loading = false
            node.code = node.code || node.id
            if (node.children) {
              let nodeChildren = []
              if (this.isFilterTree) {
                nodeChildren = node.children.filter(item => sonCodes.indexOf(item.id) !== -1)
              } else {
                nodeChildren = node.children
              }
              node.children = nodeChildren.map(item => {
                if (item.hasChildren) {
                  item.children = []
                  item.loading = false
                }
                item.title = item.name || item.text
                item.code = item.code || item.id
                return item
              })
            }
            return [node]
          }
          this.treeData = formateRootNode(data.rows)
        }

        let data = this.treeData
        return data[0]
    },
    // 列表
    async refreshWhenAll(treeNode) {
        if (this.isOrg) {
          let param = {
            pagination: true,
            parentcode: treeNode.code,
            searchKey: this.selectValue,
            queryDataStructure: 'ALL',
            limit: this.pageSize,
            offset: (this.pageNo - 1) * this.pageSize,
          }
          GMS.$http
            .post('/org/data/list', param)
            .then((res) => {
              const { rows, rs, total } = res.data
              this.baseDataList = rows
              this.pageTotal = total
              // this.refreshRowsCheckStatus(this.selection, rows)
            })
            .catch((err) => {
              console.error('获取组织机构失败：' + JSON.stringify(err))
              console.log('error', err)
            })
        } else {
          let postData = {}
          if (this.structtype === 1) {
            const treeData = JSON.parse(JSON.stringify(this.treeNode))
            treeData.children = this.treeDataMap[this.treeNode.code]
            let objectCodes = []
            const getGroupNames = (nodes) => {
              nodes.forEach(item => {
                if (item && item.attributes && item.attributes.objectcode) {
                  objectCodes.push(item.attributes.objectcode)
                }
                if (item.children && item.children.length > 0) {
                  getGroupNames(item.children)
                }
              })
            }
            getGroupNames([treeData])
            postData = {
              groupFieldName: this.groupFieldName,
              groupname: this.treeNode.attributes.objectcode,
              groupNames: objectCodes,
              tableName: this.tableName,
              pagination: true,
              offset: (this.pageNo - 1) * this.pageSize,
              limit: this.pageSize,
              searchKey: this.selectValue,
              stopflag: -1,
              queryDataStructure: "ALL",
              authType: this.authType,
              versionDate: this.versionDate,
              expression: this.filterFormular,
              'BI-SYNTAX': null 
            }
          } else {
            postData = {
              pagination: true,
              limit: this.pageSize,
              offset: (this.pageNo - 1) * this.pageSize,
              tableName: this.tableName,
              searchKey: this.selectValue,
              queryDataStructure: 'ALL',
              queryChildrenType: 'ALL_CHILDREN_WITH_SELF',
              lazyload: false,
              code: treeNode.code === '-'? '': treeNode.code,
              authType: this.authType,
              versionDate: this.versionDate,
              expression: this.filterFormular,
              'BI-SYNTAX': null 
            }
          }
          this.getBaseData(postData)
            .then((response) => {
              if (!(response || response.data)) {
                this.tableDatas = []
                return
              }
              const { rows, rs, total } = response.data
              this.baseDataList = rows

              this.pageTotal = total
            })
            .catch((err) => {
              console.error('获取表格信息失败：' + JSON.stringify(XMLHttpRequest))
              console.log('error', err)
            })
        }
    },
    // 获取下拉列表数据
    getBaseDataList() {
      let postData = {
        pagination: false,
        tableName: this.tableName,
        searchKey: '',
        queryDataStructure: 'ALL',
        authType: this.authType,
        versionDate: this.versionDate,
        expression: this.filterFormular,
        'BI-SYNTAX': null        
      }
      this.getBaseData(postData)
        .then((response) => {
          const { rows } = response.data
          this.baseDataList = rows
        })
        .catch((error) => {   
          console.log('获取基础数据失败', error)
        })
    },
    // 点击下拉菜单的条目
    handleMainSearchSelectClick(item) {
        this.selectValue = item.code
        this.hasFocus = false
        this.dataListShow = false
        this.value = item
        this.selectedItem = item
        this.$emit('data-change', this.value)
    },
    // 列表上、下、回车
    handleSelectPrev() {
        if (this.value && this.baseDataList && this.selectIndex === -1) this.findIndex()
        if (this.selectIndex > 0) {
            this.selectIndex--
            this.selectedItem = this.baseDataList[this.selectIndex]
        }
    },
    handleSelectNext() {
        if (this.value && this.baseDataList && this.selectIndex === -1) this.findIndex()
        if (this.selectIndex < this.baseDataList.length - 1) {
            this.selectIndex++
            this.selectedItem = this.baseDataList[this.selectIndex]
        }
    },
    handleSelected() {
        for (var i = 0; i < this.baseDataList.length; i++) {
          if (this.selectIndex === i) {
              this.selectValue = this.baseDataList[i].code
              this.value = this.baseDataList[i]
              this.selectedItem = this.baseDataList[i]
          }
        }
        this.hasFocus = false
        this.dataListShow = false
        this.$emit('data-change', this.value)
        this.selectIndex = -1
        this.$refs.searchInput.blur()
    },
    // 查找索引位置
    findIndex() {
        var index = -1
        for (var i = 0; i < this.baseDataList.length; i++) {
            if (this.baseDataList[i].code === this.value.code) {
              index = i
            }
        }
        this.selectIndex = index
    },
    clearList() {
      this.selectValue = ''
      this.selectIndex = -1
      this.selectedItem = {}
      this.activeName = null
      this.value = null
      this.$emit('data-change', this.value)
    },
    onSelectOk(value) {
      this.selection = value
      let result = this.getReturnInfo()
      this.sendEvent(result)
    }
  },
}
</script>
<style>
  .select-box {
    position: relative;
  }

  .select-box .clear-tree-icon {
    position: absolute;
    color: #808695;
    font-size: 16px;
    width: 14px;
    height: 14px;
    top: 0;
    bottom: 0;
    right: 26px;
    margin: auto 0;
    z-index: 3;
    display: none;
    background-color: #fff;
  }

  .select-box:hover .clear-tree-icon {
    display: inline-block;
  }

  .select-box:hover .hidden-icon,
  .select-box .hidden-icon {
    display: none;
  }
  
  .main-search-list {
    position: relative;
    z-index: 999;
    min-height: 42px;
    max-height: 252px;
    min-width: 100%;
    overflow: auto;
    padding: 5px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
    display: none;
  }
  .main-search-list.is-focus {
    display: block;
  }

  /* .main-search-list.position-left-bottom {
    left: 0;
    bottom: calc(100% + 2px);
  } */

  .main-search-list.position-left-top {
    left: 0;
    top: calc(100% + 2px);
  }

  .main-search-list.position-right-bottom {
    right: 0;
    bottom: calc(100% + 2px);
  }

  .main-search-list.position-right-top {
    right: 0;
    top: calc(100% + 2px);
  }

  .acct-search-list {
    position: absolute;
    z-index: 999;
    margin: 0;
    padding: 6px 0;
    box-sizing: border-box;
    background-color: #fff;
    list-style: none;
  }

  .acct-search-list .acct-search-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 7px 16px;
    font-size: 14px!important;
    box-sizing: border-box;
    line-height: 16px;
  }

  .acct-search-list .acct-search-item.selected {
    background-color: #f4f9ff;
  }

  .acct-search-list .acct-search-item .acct-search-label {
    margin-right: 20px;
    white-space: nowrap;
    font-size: 12px;
  }

  .acct-search-list .acct-search-item .acct-search-path {
    white-space: nowrap;
    color: #aaa;
  }

  .acct-search-list .acct-search-item:hover {
    background-color: #f4f9ff;
    cursor: pointer;
  }

  .acct-search-list .acct-search-item.selected .acct-search-label {
    color: black;
  }

  .acct-search-list .acct-search-item:hover .acct-search-label {
    color: black;
  }

  .list-empty {
    margin-left: 100px;
    font-size: 14px;
    color: #aaa;
  }

  li.active {
    color: #005791;
   }
</style>