import T from "ant-design-vue/es/table/Table";
import get from "lodash.get"
export default {
  data() {
    return {
      needTotalList: [],
      selectedRows: [],
      selectedRowKeys: [],
      localLoading: false,
      localDataSource: [],
      localPagination: Object.assign({}, T.props.pagination),
      isSearch:false,  //是否查询
      url:this.$route.path
    };
  },
  props: Object.assign({}, T.props, {
    scroll:{
      type:Object,
      default:function () {
        return {y: 500, x: 4400}
      }
    },
    columns:{},
    rowKey: {
      type: [String, Function],
      default: 'id'
    },
    data: {
      type: Function,
      required: true
    },
    pageNum: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    },
    showSizeChanger: {
      type: Boolean,
      default: true
    },
    showAlertInfo: {
      type: Boolean,
      default: false
    },
    showPagination: {
      default: 'auto'
    }
  }),
  updated(){

  },
  computed: {
    pages() {
      return this.$store.state.app.pageHeight;
    }
  },
  watch: {
    columns(){
      //监听改变srcoll.x,解决表格混乱
      this.setTableWidth();
    },
    pages(){
      this.setHeight()
    },
    'localPagination.current'(val) {
      this.$router.push({
        name: this.$route.name,
        params: Object.assign({}, this.$route.params, {
          pageNo: val
        }),
      });
    },
    pageNum(val) {
      Object.assign(this.localPagination, {
        current: val
      });
    },
    pageSize(val) {

      Object.assign(this.localPagination, {
        pageSize: val
      });
    },
    showSizeChanger(val) {

      Object.assign(this.localPagination, {
        showSizeChanger: val
      });
    }
  },
  created() {
    this.localPagination = ['auto', true].includes(this.showPagination) && Object.assign({}, this.localPagination, {
      current: this.pageNum,
      pageSize: this.pageSize,
      showSizeChanger: this.showSizeChanger,
      showTotal: (total, range) => {
        return " 共" + total + "条"
      }
    });
    this.needTotalList = this.initTotalList(this.columns)
    this.loadData();
  },
  methods: {
    setNum(text){
      if(text&&typeof(text)=='string'){
        if(!isNaN(Number(text))){
          return Number(text)
        }
      }
      return text;
    },
    setHeight(){

      if(this.isNoheigh){
        return
      }
      if(this.url !== this.$route.path){
        return;
      }
      let theadH = 0;
      if(document.querySelector(".ant-table-fixed")){
        var ls=document.querySelectorAll(".ant-table-header  .ant-table-fixed");
        for (var i =0;i<ls.length;i++){
          if(ls[i].style.display !='none'){
            theadH =ls[i].offsetHeight;
          }
        }
      }

      let paginationH = 0;
      if(document.querySelector(".ant-table-pagination")){
        paginationH = document.querySelector(".ant-table-pagination").offsetHeight;
      }
      let sl =
          this.$el.offsetHeight -
          theadH -
          paginationH - 30
      if(sl < 200){ //最小值200
        sl = 200
      }
      this.scroll.y = sl;
    },
    setTableWidth(){ //为解决宽度变化太大导致
      let minWidth = 0;
      if(this.rowSelection){
        minWidth = 62.4;
      }
      let boxwidth = this.getTableWidth(this.columns) + minWidth;
      if(this.$el.offsetWidth>boxwidth){
        this.scroll.x = boxwidth;
        this.columns.forEach(item =>{
          item.fixed = false;
        })
      }else{
        this.scroll.x = boxwidth;
      }
    },
    setWidth(data){
        data.forEach(item =>{
          if(item.children){
            this.setWidth(item.children)
          }else{
            if(!item.width){
              item.width = 200
            }
          }
        })
    },
    refresh(option) {
      if(option){
        if(option.search){
          this.isSearch = option.search;
        }
      }
      this.loadData();
    },
    loadData(pagination, filters, sorter) {
      this.setWidth(this.columns);
      this.localLoading = true
      //作查询的特殊处理 @liweiwen
      let pageNo = (pagination && pagination.current) ||
      this.localPagination.current || 1;
      if(this.isSearch){
        pageNo = 1; //查询时重置分页
      }
      this.isSearch = false;
      var result = this.data(
        Object.assign({
            pageNo: pageNo, //新增了判断条件 @liweiwen
            pageSize: (pagination && pagination.pageSize) ||
              this.localPagination.pageSize || this.pageSize //新增了判断条件 @liweiwen
          },
          (sorter && sorter.field && {
            sortField: sorter.field
          }) || {},
          (sorter && sorter.order && {
            sortOrder: sorter.order
          }) || {}, {
            ...filters
          }
        )
      );

      if (result instanceof Promise) {
        result.then(r => {
          this.localPagination = Object.assign({}, this.localPagination, {
            current: r.pageNo,  // 返回结果中的当前分页数
            total: r.totalCount?this.setNum(r.totalCount):r.totalCount, // 返回结果中的总记录数
            showSizeChanger: this.showSizeChanger,
            pageSize: (pagination && pagination.pageSize) ||
              this.localPagination.pageSize || this.pageSize //新增了判断条件 @liweiwen
          });
          !r.totalCount && ['auto', false].includes(this.showPagination) && (this.localPagination = false)

          this.localDataSource = r.data; // 返回结果中的数组数据
          this.localLoading = false

          //回调高度
          this.$nextTick(() =>{
            if(!this.isNoheigh){
              setTimeout(()=>{ //为防止表头高度变化，延迟300s
                this.setHeight()
              },300)

            }

            let minWidth = 0;
            if(this.rowSelection){
              minWidth = 62.4;
            }

            let boxwidth = this.getTableWidth(this.columns) + minWidth;
            if(this.$el.offsetWidth>boxwidth){
              this.scroll.x = boxwidth;
              this.columns.forEach(item =>{
                item.fixed = false;
              })
            }else{
              this.scroll.x = boxwidth;
            }
          })

        });
      }
    },
    initTotalList(columns) {
      const totalList = []
      columns && columns instanceof Array && columns.forEach(column => {
        if (column.needTotal) {
          totalList.push({ ...column,
            total: 0
          })
        }
      })
      return totalList
    },
    updateSelect(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      let list = this.needTotalList
      this.needTotalList = list.map(item => {
        return {
          ...item,
          total: selectedRows.reduce((sum, val) => {
            let total = sum + get(val, item.dataIndex)
            return isNaN(total) ? 0 : total
          }, 0)
        }
      })
      // this.$emit('change', selectedRowKeys, selectedRows)
    },
    updateEdit() {
      this.selectedRows = []
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.updateSelect([], [])
    },
    //获取表格宽度
    getTableWidth(data, lens) {
      let len = 0;
      if (lens) {
        len = lens;
      }
      data.forEach((item) => {
        len = len + (item.width ? item.width : 0);
        if (item.children) {
          len = this.getTableWidth(item.children, len)
        }else{
          if(!item.width){
            len = len + 200
          }
        }
      })
      return len;
    },
    renderMsg(h) {
      const _vm = this
      let d = []
      // 构建 已选择
      d.push(
        h('span', {
          style: {
            marginRight: '12px'
          }
        }, ['已选择 ', h('a', {
          style: {
            fontWeight: 600
          }
        }, this.selectedRows.length)])
      );

      // 构建 列统计
      this.needTotalList.map(item => {
        d.push(h('span', {
            style: {
              marginRight: '12px'
            }
          },
          [
            `${ item.title }总计 `,
            h('a', {
              style: {
                fontWeight: 600
              }
            }, `${ !item.customRender ? item.total : item.customRender(item.total) }`)
          ]))
      });

      // 构建 清空选择
      d.push(h('a', {
        style: {
          marginLeft: '24px'
        },
        on: {
          click: _vm.onClearSelected
        }
      }, '清空'))

      return d
    },
    renderAlert(h) {
      return h('span', {
        slot: 'message'
      }, this.renderMsg(h))
    },
  },
  render(h) {
    const _vm = this

    let props = {},
      localKeys = Object.keys(this.$data);

    Object.keys(T.props).forEach(k => {
      let localKey = `local${k.substring(0,1).toUpperCase()}${k.substring(1)}`;
      if (localKeys.includes(localKey)) {
        return props[k] = _vm[localKey];
      }
      return props[k] = _vm[k];
    })


    // 显示信息提示
    if (this.showAlertInfo) {

      props.rowSelection = {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          _vm.updateSelect(selectedRowKeys, selectedRows)
          _vm.$emit('onSelect', { selectedRowKeys: selectedRowKeys, selectedRows: selectedRows })
        }
      };

      return h('div', {}, [
        h("a-alert", {
          style: {
            marginBottom: '16px'
          },
          props: {
            type: 'info',
            showIcon: true
          }
        }, [_vm.renderAlert(h)]),
        h("a-table", {
          tag: "component",
          attrs: props,
          on: {
            change: _vm.loadData
          },
          scopedSlots: this.$scopedSlots
        }, this.$slots.default)
      ]);

    }

    return h("a-table", {
      tag: "component",
      attrs: props,
      on: {
        change: _vm.loadData
      },
      scopedSlots: this.$scopedSlots
    }, this.$slots.default);

  }
};
