<template>
    <!-- 列表 -->
      <div
        class="table__box height100"
      >
          <!-- 树网格 -->
          <vxe-table
            ref="tstable"
            :row-id="rowId"
            height="100%"
            border
            resizable
            :tree-config="treeConfig"
            :loading="loading"
            :show-footer="showFooter"
            :data="data"
            :key="sources.id"
            :id="sources.id"
          >
              <vxe-table-column v-for="(config, index) in colModel" :key="index"
                v-bind="config"
              ></vxe-table-column>
          </vxe-table>
      </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'TsTableTree',
  components: {},
  props: {
  
    initData: {
      type: [Object, Array],
      default: function() {
        return []
      }
    },
 
    isNoHint: {
      type: [Boolean, String],
      default: false
    },
    source: {
      type: Object,
      default: () => {
        return {
          offPage: false,
          dataType: 'local',
          colModel: [],
          showOverflow: true,
          postData: {},
          totalSet: [],
          totalSetCfg: {}
        }
      }
    },
    width: [String, Number, Boolean],
    height: [String, Number, Boolean],
    rowId: String,
    border: String,
  
  },
  components: {
  },
  data() {
    return {
      tableData:[],
      radiolist: {},
      iconAsc: '',
      scrollY: { gt: 200 },
      iconFilter: 'null',
      columnList: [],
      refreshTime: '', // 后台传出的数据更新时间
      opearList: [
        // {visible:true,title:'显示隐藏子列',type:'column'},
        {
          visible: false,
          title: '过滤',
          type: 'filter'
        },
        {
          visible: true,
          title: '排序',
          type: 'sort'
        }
      ],
      showSet: true,
      tableExport: {
        // 默认选中类型
        type: 'xlsx',
        // 自定义类型
        types: ['csv', 'html', 'xml', 'txt']
      },
      merge_Cells: [],
      sources: this.source,
      childConfig: this.childTabl,
      childSlotConfig: this.childSlot,
      widths: this.width || '100%', //  宽
      heights: this.height || '100%', // 表格高度
      formatArr: [], // 需按配置格式化数据参数
      loading: false, // 加载层
      colModel: [], // 表格基本属性
      rows: 1, // 表头行数
      data: [], // 表格数据
      showFooter: false, // 是否显示合计
      selectionMode: 'single', // 行选择样式
      pageSize: 0, // 当页条数
      nowPage: '1', // 当前分页
      pageNo: 1, // 当前分页
      totalCount: 0, // 总条数
      pageCount: 1, // 总页数
      treeConfig: false, // 树子集配置
      m_h: 30,
      isfilter: false, // 是否显示筛选区域
      btnAlone: false, // 筛选触发按钮是否单独放置
      filterObj: {}, // 筛选对象
      buttons: this.source.buttons, // 按钮对象
      offPage: false,
      isLoad: true,
      totalSet: this.source.totalSet,
      cshow: true,
      emptyText: '--暂无数据--', // 暂无数据
      showTable: true,
      href: '',
      isRshow: true,
      totalSetCfg: this.source.totalSetCfg || {} // 合计标题
    }
  },
  created() {
    const _this = this
    // 判断是否为树表格
      this.treeConfig = {
        lazy: true, 
        children: 'children',
        hasChild: 'hasChild',
        loadMethod: this.loadChildrenMethod, 
        iconOpen: 'table-tree__closeicon',
        iconClose: 'table-tree__openicon'
      }
    this.colModelFn(this.sources.colModel) // 格式化列表配置
    // 初始化数据
    if (this.sources.dataType === 'local') {
      this.localData()
    } else {
      this.apiData() // 列表数据拉取
    }
  },
  mounted() {
 
  },
  methods: {
    loadChildrenMethod(row){
         return new Promise(resolve => {
           let  data = [{
             name:'科室',
             value:'1111',
             num:'',
             id:'222'
           }] 
           resolve(data)
          // let data = this.source.lazyUrl
          // if(this.source.)
        // this.$api({
        //     url: '',
        //     data:'',
        //   }).then(res => {
        //   if (res.success) {
        //     resolve(res.data)
        //   } else {

        //   }
        // })
      })
    },


    rowStyle({ row, rowIndex }) {
      if (this.styleData.stripe == 'false' || this.styleData.stripe == false) {
        return {
          backgroundColor: this.styleData.backgroundColor
        }
      } else {
        if (rowIndex % 2 == '0') {
          return {
            backgroundColor: this.styleData.backgroundColor
          }
        } else {
          return {
            backgroundColor: this.styleData.anotherBackgroundColor
          }
        }
      }
    },
    cellStyle({ row, rowIndex, column, columnIndex }) {
      if (this.styleData) {
        if (row.KSMC && row.KSMC == '合计') {
          //合计特需处理 自定义报表返回的结果
          return {
            fontWeight: 600,
            fontSize: '13px',
            color: '#333'
          }
        }
        let col = this.styleData.cols[columnIndex]
        if (col) {
          return {
            backgroundColor: col.backgroundColor,
            color: col.fontColor,
            fontSize: col.fontSize + 'px'
          }
        }
        // for (let i = 1; i < this.styleData.cols.length - 1; i++) {
        //   if (columnIndex == i) {
        //
        //     }
        //   }
        // }
      } else {
        return {
          fontSize: '12px',
          color: '#333'
        }
      }
    },
    // 阻止默认事件
    hinder() {
      this.$nextTick(() => {
        if (!this.isNoHint) {
        }
      })
    },
 
 


    // 列表配置格式化
    colModelFn(arr) {
      const _this = this
      const _arr = []
      this.sources.dataType = this.source.dataType || 'json'
      if (arr && arr.length > 0) {
        arr.forEach((v, i) => {
          // if (v.type != 'seq') {
          //   // v.filterRender = { name: 'FilterContent' }
          //   v.sortable = v.sortable !== false
          // }
          _arr.push(v)
        })
  
        this.colModel = _arr
      }
    },
    // 表头行计算
    rowsCount() {
      const _this = this
      const arr = this.colModel
      const rows = this.colModel.length
      arr.forEach((vo, l) => {
        vo.forEach((v, i) => {
          if (v.colspan > 1) {
            v.rowspan = 1
          } else {
            v.rowspan = rows - l
          }
        })
      })
    },
    localData() {
      let data = this.sources.data || []
      if (data.length === 0) {
        data = this.initData
      }
      data.forEach(res=>{
        res.hasChild = true
      })
      this.data = data
      this.hinder()
    },
    // 数据
    apiData(type) {
      const _this = this
      const d = this.sources
      if (this.isLoad === true) {
        this.isLoad = false
        if (this.source.noloading != true) {
          this.loading = true
        }
        try {
          this.emptyText = '数据加载中...'
          this.$api({
            url: d.url,
            method: d.method || 'post',
            data: this.reqData(),
            responseType: d.responseType || 'json',
            loading: false,
            headers: {
              'Content-Type': d.contentType || 'application/json; charset=utf-8'
            }
          })
            .then(function(response) {
              _this.loading = false
              // 请求成功
              _this.isLoad = true
              // _this.$mModal.loading.close()
              if (d.isHasResObj) {
                // 含object的解析
                response = {
                  ...response.object
                }
              }
              // 只包含object的情况
              if (response.object && !response.rows) {
                response.rows = [...response.object]
              }
              if (response.rows || response.rows == null) {
                _this.data = []
                _this.$nextTick(() => {
                  if (typeof d.prmNames === 'object') {
                    _this.nowPage = response[d.prmNames.page]?response[d.prmNames.page].toString():'1'
                    _this.pageCount = response[d.prmNames.pageCount]
                    _this.totalCount = response[d.prmNames.totalCount]
                  } else {
                    _this.nowPage = response.pageNo
                      ? response.pageNo.toString()
                      : '1'
                    _this.pageCount = response.pageCount
                    _this.totalCount = response.totalCount
                  }
                  _this.refreshTime = response.refreshTime || ''
                  _this.data = response.rows
                  if(response.rows&&response.rows.length>0&&response.rows[0].queryJson){
                       _this.data.forEach(query=>{
                       let fieldJson =  JSON.parse(query.queryJson)
                      Object.assign(query,fieldJson)
                      })
                  }
               
                  if (Object.keys(_this.radioConfig).length > 0) {
                    _this.data.forEach(radio => {
                      if (radio[_this.radioConfig.mainId] == true) {
                        _this.radiolist[radio[_this.radioConfig.groupId]] =
                          radio.id
                      }
                      if (!_this.radiolist[radio[_this.radioConfig.groupId]]) {
                        _this.radiolist[radio[_this.radioConfig.groupId]] = ''
                      }
                    })
                  }
                })
              }
              _this.loading = false
              _this.hinder()
              // 列表数据加载成功后回调
              _this.$nextTick(() => {
                _this.$emit('loadSuccess', _this.data)
                _this.emptyText = '--暂无数据--'
              })
            })
            .catch(function(error) {
              // 请求失败
              // _this.$mModal.loading.close()
              _this.data = []
              _this.loading = false
              _this.isLoad = true
              _this.emptyText = '--暂无数据--'
            })
        } catch (err) {
          this.data = []
          this.loading = false
          this.isLoad = true
        }
      }
    },
    // 请求参数
    reqData() {
      const d = this.sources
      const _page = this.pageSize || 100
      let data = {
        sord: d.sord || 'desc',
        pageSize: _page,
        pageNo: this.pageNo
      }
      d.postData = d.postData || {}
       Object.assign(data, d.postData)
      return data
    },
    // 合计



    // 选中行触发
    onSelectRow({ row }) {
      this.$emit('onSelectRow', row)
    },
    // 单元格被点击时会触发该事件
    cellClickEvent({ row, column, $event }) {
      $event.stopPropagation()
      this.$emit('cellClick', row, column, $event)
    },

    clearCheckboxReserve() {
      return this.$refs.tstable.clearCheckboxReserve()
    },
    // 阻止冒泡
    forbidBubbling(e, event) {
      e.stopPropagation()
      // e.preventDefault()
      if (typeof event === 'function') {
        event()
      }
    },
    // 导出
    openExport(obj) {
      this.$refs.tstable.openExport(obj)
      this.$refs.tstable.exportData({
        filename: obj.filename,
        type: obj.type,
        isHeader: true,
        isFooter: true
      })
    },
    // 导出excel
    exportDataEvent() {
      this.$refs.tstable.exportData({
        filename: '导出',
        sheetName: 'Sheet1',
        type: 'xlsx'
      })
    }
  },
  watch: {
    'source.data': {
      handler(o, a) {
        this.sources.data = o
        this.refresh()
      },
      deep: true
    },

    'source.postData': {
      handler(o, a) {
        this.sources.postData = o
      },
      deep: true
    },

    'source.totalSetCfg': {
      handler(o, a) {
        this.totalSetCfg = o
      },
      deep: true
    },



  }
}
</script>

<style lang="scss" scoped>
.table_icon {
  position: absolute;
  top: 3px;
  left: 2px;
  height: 30px;
  width: 30px;
  cursor: pointer;
  z-index: 99;
}

.table_icon:hover .table_set {
  display: block;
}

.table_set {
  display: none;
  position: absolute;
  top: 5px;
  left: 10px;
  background: #fff;
  height: 60px;
  width: 100px;
  z-index: 99;
  padding: 10px 0 10px 10px;
  border: 1px solid var(--border_color);
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

.column_Hover:hover .table_column {
  display: block;
}

/deep/.fixed-left--wrapper {
  overflow: hidden;
}
.check_name {
  font-size: 12px;
  margin-left: -4px;
}

.check_name:hover {
  color: var(--base-acv);
}

.table_column {
  display: none;
  position: absolute;
  top: 10px;
  left: 110px;
  background: #fff;
  min-width: 100px;
  width: auto;
  z-index: 99;
  padding: 10px;
  border: 1px solid var(--border_color);
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

/deep/.vxe-button.type--text {
  padding: 0;
}

/deep/.vxe-table--footer-wrapper.body--wrapper {
  overflow-x: hidden;
  margin-top: 0px;
}

/deep/.el-checkbox__label {
  padding-left: 6px;
}

/deep/.vxe-table--filter-wrapper {
  .vxe-table--filter-footer {
    display: none;
  }
}

/deep/.ts-slider-horizontal {
  display: flex;
  align-items: center;

  .slider-text {
    width: 50%;
    text-align: right;
  }
}

/deep/.el-slider__runway {
  .el-slider__bar {
    background-color: #6395f9;
    height: 100%;
  }

  margin: 0 0 0 5px;
  width: 40%;
  height: 10px;
}

/deep/.vxe-header--row th:first-child .vxe-cell--title {
  padding-left: 16px;
}
/deep/.vxe-editable .vxe-header--row th:first-child .vxe-cell--title {
  padding-left: 0px !important;
}
/deep/.vxe-loading {
  display: none;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 99;
  user-select: none;
  background-color: rgba(250, 250, 250, 0.1);
  &.is--visible {
    display: block;
  }
  .vxe-loading--spinner {
    width: 56px;
    height: 56px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    &:before,
    &:after {
      content: '';
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: red;
      background: url('../../../../assets/images/main/tableloading2.gif') no-repeat;
      background-size: 100% 100%;
      opacity: 0.6;
      position: absolute;
      top: 0;
      left: 0;
      animation: none;
      // animation: bounce 2.0s infinite ease-in-out;
    }
    &:after {
      animation-delay: 0s;
    }
  }
  @keyframes bounce {
    0%,
    100% {
      transform: scale(1);
    }
    50% {
      transform: scale(1);
    }
  }
}

.size--mini {
  .vxe-loading {
    .vxe-loading--spinner {
      width: 38px;
      height: 38px;
    }
  }
}
.size--small {
  .vxe-loading {
    .vxe-loading--spinner {
      width: 44px;
      height: 44px;
    }
  }
}
.size--medium {
  .vxe-loading {
    .vxe-loading--spinner {
      width: 50px;
      height: 50px;
    }
  }
}
</style>
