<template>
    <div class="paraTable" style="position: relative" ref="paraTable">
        <Table
                :dataSource="dataSource"
                :bordered="bordered"
                :childrenColumnName="childrenColumnName"
                :columns="columns"
                :components="components"
                :defaultExpandAllRows="defaultExpandAllRows"
                :defaultExpandedRowKeys="defaultExpandedRowKeys"
                :expandedRowKeys="expandedRowKeys"
                :expandedRowRender="expandedRowRender"
                :expandIcon="expandIcon"
                :expandRowByClick="expandRowByClick"
                :title="title"
                :footer="footer"
                :indentSize="indentSize"
                :loading="loading"
                :locale="locale"
                :pagination="pagination?defPagination:false"
                :rowClassName="rowClassName"
                :rowKey="rowKey"
                :rowSelection="rowSelection"
                :scroll="scroll"
                :showHeader="showHeader"
                :size="size"
                :customHeaderRow="customHeaderRow"
                :customRow="customRow"
                @expandedRowsChange="expandedRowsChange"
                @change="change"
                @expand="expand"
        >

            <!--批量处理表单-->
            <template v-if="batch">
                <TableColumn width="20px">
                    <!--不生效-->
                    <!-- <template #title>
                         <a-icon type="plus-circle"  />
                     </template>-->
                    <!--生效-->
                    <span slot="title">
                       <Icon type="plus-circle" @click="addDataSource"/>
                    </span>

                    <template #default="record">
                        <span>
                           <Icon type="minus-circle" @click="deleteDataSource(record)"/>
                        </span>
                    </template>
                </TableColumn>
            </template>

            <!--拖拽列显示-->
            <template v-if="dragColumn">
                <TableColumn width="36px">
                    <!--不生效-->
                    <!-- <template #title>
                         <a-icon type="plus-circle"  />
                     </template>-->
                    <!--生效-->
                    <span slot="title">
                        &nbsp;
                    </span>

                    <template #customRender="text, record, index">
                         <span class="dragIcon">
                            <Icon type="caret-up" @click="moveClick('up',record,index)"/>
                            <Icon type="caret-down" @click="moveClick('down',record,index)"/>
                             <!--<Icon type="minus-circle" @click="deleteDataSource(record)"/>-->
                        </span>
                    </template>

                    <!--<template #default="record">
                        <span style="display: table;width: 100%">
                            <Icon type="caret-up" @click="moveClick('up',record)" style="display: table-cell;color: rgba(0, 0, 0, 0.65)"/>
                            <Icon type="caret-down" @click="moveClick('down',record)" style="display: table-cell;color: rgba(0, 0, 0, 0.65)"/>
                           &lt;!&ndash;<Icon type="minus-circle" @click="deleteDataSource(record)"/>&ndash;&gt;
                        </span>
                    </template>-->
                </TableColumn>
            </template>

            <template #expandedRowRender="record" v-if="openExpandedRow">
                <slot name="expands" :record="record"></slot>
            </template>

            <!--选择列-->
            <template>
                <TableColumn
                        v-for="(item) in choseColums"
                        :title="item.title"
                        :width="item.width"
                        :sorter="item.sorter"
                        :dataIndex="item.dataIndex"
                        :key="item.dataIndex"
                        :align="item.align"
                        :colSpan="item.colSpan"
                        :filterDropdown="item.filterDropdown"
                        :filtered="item.filtered"
                        :filteredValue="item.filteredValue"
                        :filterIcon="item.filterIcon"
                        :filterMultiple="item.filterMultiple"
                        :filters="item.filters"
                        :fixed="item.fixed"
                        :customRender="item.customRender"
                        :customCell="item.customCell"
                        :customHeaderCell="item.customHeaderCell"
                        :onFilter="item.onFilter"
                        :onFilterDropdownVisibleChange="item.onFilterDropdownVisibleChange"
                        :slots="item.slots"
                        :scopedSlots="item.scopedSlots"
                >
                    <template #default="text, record">
                        <span>{{text}}</span>
                    </template>
                </TableColumn>
            </template>

            <!--template风格列-->
            <slot name="default"></slot>

            <!--表格头部和尾部-->
            <template #title="currentPageData" v-if="showTitle && !optionBottom">
                <div class="table-options">
                    <Tooltip placement="top" v-show="showRefresh">
                        <template slot="title">
                            <!--刷新-->
                            <span>{{optionsLables.refresh[language]}}</span>
                        </template>
                        <Icon type="reload" @click="currentRefresh"/>
                    </Tooltip>

                    <Tooltip placement="top" v-show="selectRow">
                        <template slot="title">
                            <!--选择行-->
                            <span>{{optionsLables.srow[language]}}</span>
                        </template>
                        <Icon type="bars" @click="selectRows"/>
                    </Tooltip>
                    <Tooltip placement="top" v-show="drag || dragRequest">
                        <template slot="title">
                            <!--拖拽行-->
                            <span>{{optionsLables.drag[language]}}</span>
                        </template>
                        <!--设置dragColumn 显示-->
                        <Icon type="drag" @click="dragClick"/>
                    </Tooltip>

                    <Tooltip placement="top" v-show="column.length">
                        <template slot="title">
                            <!--选择列-->
                            <span>{{optionsLables.scloumn[language]}}</span>
                        </template>
                        <Icon type="form" @click="modalVisible=!modalVisible"/>
                    </Tooltip>
                    <slot name="titleOptions"></slot>
                </div>
            </template>
            <template #footer="currentPageData" v-if="selectRow">
                <!--<slot name="footer" :currentPageData="currentPageData"></slot>-->
                <div class="option-btn">
                    <!--重置选项-->
                    <Button size="small" v-show="value?value.length:selectedRowKeys.length"
                            @click="restSelectedRowKeys">{{t('paraTable.reset')}}
                    </Button>
                    <slot name="footerOptions"></slot>
                </div>
            </template>

        </Table>
        <template v-if="showTitle && optionBottom && showOption">
            <div class="table-options" style="position: absolute;bottom: 24px;margin-left:10px;">
                <Tooltip placement="top" v-show="showRefresh">
                    <template slot="title">
                        <!--刷新-->
                        <span>{{optionsLables.refresh[language]}}</span>
                    </template>
                    <Icon type="reload" @click="currentRefresh"/>
                </Tooltip>
                <Tooltip placement="top" v-show="selectRow">
                    <template slot="title">
                        <!--选择行-->
                        <span>{{optionsLables.srow[language]}}</span>
                    </template>
                    <Icon type="bars" @click="selectRows"/>
                </Tooltip>
                <Tooltip placement="top" v-show="drag || dragRequest">
                    <template slot="title">
                        <!--拖拽行-->
                        <span>{{optionsLables.drag[language]}}</span>
                    </template>
                    <!--设置dragColumn 显示-->
                    <Icon type="drag" @click="dragClick"/>
                </Tooltip>
                <Tooltip placement="top" v-show="column.length">
                    <template slot="title">
                        <!--选择列-->
                        <span>{{optionsLables.scloumn[language]}}</span>
                    </template>
                    <Icon type="form" @click="modalVisible=!modalVisible"/>
                </Tooltip>
                <slot name="titleOptions"></slot>
            </div>
        </template>
        <!--选择列弹窗-->
        <Modal
                :title="t('paraTable.scloumn')"
                :footer="null"
                :maskClosable="false"
                v-model="modalVisible">
            <para-transfer
                    label-key="title"
                    value-key="dataIndex"
                    :data="column" v-model="transferRightData">
            </para-transfer>
        </Modal>
    </div>
</template>

<script>
  import {Table, Modal, Icon, Tooltip, Button} from 'ant-design-vue';
  import paraTransfer from '../para-transfer/para-transfer.vue';
  import {
    $Local as Local,
    $http as http,
    $paraReqCancel
    // $axios
  } from '@chenxihub/sweet';
  import Event from './Event';

  const optionsLables = {
    scloumn: {
      zh_CN: '选择列',
      en_GB: 'Select Column',
    },
    refresh: {
      zh_CN: '刷新',
      en_GB: 'Refresh',
    },
    srow: {
      zh_CN: '选择行',
      en_GB: 'Select Row',
    },
    drag: {
      zh_CN: '拖拽行',
      en_GB: 'Drag Row',
    }
    //选择行
    // 拖拽行

  };

  const orderbyMap = {
    'ascend': 'ASC',
    'descend': 'DESC'
  };
  export default {
    name: 'paraTable',
    components: {
      paraTransfer,
      Table,
      TableColumn: Table.Column,
      Modal,
      Icon,
      Tooltip,
      Button
    },
    mixins: [Local],
    props: {
      isPageNumber: {
        type: Boolean,
        default: false
      },
      column: {
        type: Array,
        default: () => ([])
      },
      drag: {
        type: Boolean,
        default: false
      },
      dragKey: {
        type: String,
        default: 'key'
      },
      batch: {
        type: Boolean,
        default: false
      },
      project: {
        type: String,
        default: null
      },
      dragRequest: {
        type: [Object, String],
        default: ''
      },
      request: {
        type: [Object, String],
        default: ''
      },
      value: {
        type: Array
      },
      requestCallback: {
        type: Function
      },
      search: {
        type: [Object, String],
        default: () => ({})
      },
      data: {
        // 数据数组
        type: [Object, Array]
        /* default: () => ({
          page: null,
          list: []
        }) */
      },
      bordered: {
        // 是否展示外边框和列边框
        type: Boolean,
        default: false
      },
      childrenColumnName: {
        // 指定树形结构的列名
        type: [Array, String],
        default: () => 'children'
      },
      columns: {
        // 表格列的配置描述
        type: [Array],
        default: () => undefined
      },
      components: {
        // 覆盖默认的 table 元素
        type: [Object]
      },
      defaultExpandAllRows: {
        // 初始时，是否展开所有行
        type: Boolean,
        default: false
      },
      defaultExpandedRowKeys: {
        // 默认展开的行
        type: Array
      },
      expandedRowKeys: {
        // 展开的行，控制属性
        type: [Array]
      },
      openExpandedRow: {
        type: Boolean,
        default: false
      },
      expandedRowRender: {
        // 额外的展开行
        type: [Function, Object]
      },
      expandIcon: {
        // 自定义展开图标
        type: [Function, Object]
      },
      expandRowByClick: {
        // 通过点击行来展开子行
        type: Boolean,
        default: false
      },
      footer: {
        // 表格尾部
        type: [Function, Object]
      },
      indentSize: {
        // 展示树形数据时，每层缩进的宽度，以 px 为单位
        type: Number,
        default: 15
      },
      /* loading: {
          // 页面是否加载中
          type: [Boolean, Object],
          default: false
      }, */
      locale: {
        // 默认文案设置，目前包括排序、过滤、空数据文案
        type: Object
      },
      pagination: {
        // 分页器，参考配置项或 pagination，设为 false 时不展示和进行分页
        type: [Object, Boolean],
        default: () => false
      },
      rowClassName: {
        // 表格行的类名
        type: [Function, String]
      },
      rowKey: {
        // 表格行 key 的取值，可以是字符串或一个函数
        type: [String, Function],
        default: 'key'
      },
      /* rowSelection: {
          // 列表项是否可选择，配置项
          type: Object,
          default: () => null
      }, */
      scroll: {
        // 设置横向或纵向滚动，也可用于指定滚动区域的宽和高，
        // 建议为 x 设置一个数字，如果要设置为 true，需要配合样式 .ant-table td { white-space: nowrap; }
        type: Object
      },
      showHeader: {
        // 是否显示表头
        type: Boolean,
        default: true
      },
      showTitle: {
        type: Boolean,
        default: true
      },
      size: {
        // 正常或迷你类型，default or small
        type: String,
        default: 'default'
      },
      title: {
        // 表格标题
        type: [Function, Object]
      },
      customHeaderRow: {
        // 设置头部行属性
        type: [Function]
      },
      customRow: {
        // 设置行属性
        type: [Function]
      },
      selectRow: {
        type: Boolean,
        default: false
      },
      showRefresh: {
        type: Boolean,
        default: true
      },
      radio: {
        type: Boolean,
        default: false
      },
      getCheckboxProps: {
        type: Function,
        default: () => ({
          props: {}
        })
      },
      trHeight: {
        type: Number,
        default: 48
      },
      optionBottom: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        dataSource: [],
        defPagination: {
          position: 'bottom',
          showQuickJumper: true,
          showSizeChanger: true,
          simple: false,
          size: 'small',
          type: null,
          pageSizeOptions: ['10', '20', '30', '40'],
          pageSize: 20,
          current: 1,
          total: 0
        },
        isRowSelect: false,
        selectedRowKeys: [],
        loading: false,
        sorter: {
          column: '',
          columnKey: '',
          field: '',
          order: ''
        },
        filters: {},
        transferRightData: [],
        // 拖拽线条颜色
        dragColor: 'red',
        modalVisible: false,
        dragSourceEventList: ['dragstart', 'drag', 'dragleave', 'dragend'],
        dragAimEventList: ['dragenter', 'dragover', 'drop', 'dragleave'],
        Event: '',
        dragDiabled: true,
        position: '',
        GRdata: null,
        hasRender: false,
        showTotalLabel: {
          zh_CN: '总条数',
          en_GB: 'total'
        },
        showOption: false,
        // CancelToken: $axios.CancelToken,
        source: null,
        axiosUUID: '',
        dragColumn: false,
        errorTime: null,
        optionsLables
      };
    },
    computed: {
      searchFiled() {
        if (typeof this.search === 'string') {
          const tempobj = {};
          this.search.split('&').forEach((data) => {
            const result = data.split('=');
            tempobj[result[0]] = result[1];
          });
          return tempobj;
        }
        if (typeof this.search === 'object') {
          return this.search;
        }
        return {};
      },
      Gdata: {
        set() {
        },
        get() {
          if (this.data instanceof Array) {
            return {list: this.data};
          }
          return Object.assign({}, this.data);
        }
      },
      dictData: {
        get() {
          if (this.column.length) {
            const result = {};
            this.column.forEach((item) => {
              result[item.dataIndex] = item;
            });
            return result;
          }
          return {};
        },
        set() {
        }
      },
      choseColums: {
        get() {
          const columnResult = [];
          if (this.transferRightData.length) {
            this.transferRightData.forEach((item) => {
              if (this.dictData[item]) {
                columnResult.push(this.dictData[item]);
              }
            });
            return columnResult;
          }
          return columnResult;
        },
        set() {
        }
      },
      rowSelection: {
        get() {
          return this.isRowSelect ? {
            selectedRowKeys: this.value ? this.value : this.selectedRowKeys,
            onChange: this.onSelectChange,
            hideDefaultSelections: false,
            selections: true,
            type: this.radio ? 'radio' : 'checkbox',
            //   columnTitle: this.$createElement('span', {on: {click: this.checkAll}}, this.radio ? '单选' : )
            // columnTitle: this.radio ? this.$createElement('span', {}, '&nbsp;&nbsp;') : undefined,
            getCheckboxProps: this.getCheckboxProps
          } : null;
        },
        set() {

        }
      },
      language() {
        return JSON.parse(window.localStorage[window.$project]).setting.language || 'zh_CN';
      }
    },
    watch: {
      searchFiled: {
        // eslint-disable-next-line
        handler: function () {
          this.restPagination();
          this.GRdata = null;
          this.chooseDataSource();
        },
        deep: true
      },
      data: {
        // eslint-disable-next-line
        handler: function () {
          this.currentRefresh();
        },
        deep: true
      },
      drag() {
        this.dragOperation();
      }
    },
    beforeCreate() {
    },
    created() {
      // this.source = this.CancelToken.source();
      this.Event = new Event();
      this.init();
    },
    mounted() {},
    methods: {
      init() {
        // 合并 pagination
        this.megePagination();
        // 判断 search
        // 初始化table 是url 还是 data 优先 data
        this.chooseDataSource();

        // 是否有选择项table
        if (this.selectRow) {
          this.isRowSelect = true;
          this.defaultSelcet = true;
        }
        // 判断是否有拖拽功能
        if (this.drag || this.dragRequest) {
          this.defaultDragColumn = this.dragColumn;
        }
      },
      restSelectedRowKeys() {
        this.$emit('input', []);
        this.$emit('checkdata', []);
        this.selectedRowKeys = [];
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.$emit('input', selectedRowKeys);
        this.$emit('checkdata', selectedRows);
        this.selectedRowKeys = selectedRowKeys;
      },
      megePagination() {
        // 初始化合并父组件传递的 pagination
        const elHeight = document.createElement.clientHeight || document.body.clientHeight;
        // const tableHeight = elHeight;
        // eslint-disable-next-line radix
        // 获取最相近的pageSize
        let recentPagsize = parseInt(elHeight / this.trHeight);
        let arr = this.defPagination.pageSizeOptions.slice().map(item => Math.abs(item - recentPagsize));
        this.defPagination.pageSize = this.defPagination.pageSizeOptions[arr.indexOf(Math.min.apply(null, arr))];
        this.defPagination.pageSize = Number(this.defPagination.pageSize);
        this.defPagination.showTotal = this.showTotal;
        if (typeof this.pagination === 'object') {
          // eslint-disable-next-line no-prototype-builtins
          if (this.pagination.hasOwnProperty('page')) {
            this.defPagination.current = this.pagination.page ? this.pagination.page : this.defPagination.current;
          }
          // eslint-disable-next-line no-prototype-builtins
          if (this.pagination.hasOwnProperty('size')) {
            // eslint-disable-next-line radix
            this.defPagination.pageSize = this.pagination.size ? this.pagination.size : this.defPagination.pageSize;
          }
          // eslint-disable-next-line no-prototype-builtins
          if (this.pagination.hasOwnProperty('sizes')) {
            this.defPagination.pageSizeOptions = this.pagination.sizes.length ? this.pagination.sizes : this.defPagination.pageSizeOptions;
          }
          // eslint-disable-next-line no-prototype-builtins
          if (this.pagination.hasOwnProperty('type')) {
            this.defPagination.type = this.pagination.type ? this.pagination.type : true;
          }
          // eslint-disable-next-line no-prototype-builtins
          if (this.pagination.hasOwnProperty('showTotal')) {
            this.defPagination.showTotal = this.pagination.showTotal ? this.pagination.showTotal : this.defPagination.showTotal;
          }
          // 合并分页
          this.defPagination = Object.assign(this.defPagination, this.pagination);
        }
      },
      chooseDataSource() {
        if (this.data) {
          // 如果data有值渲染 data
          this.Gdata.type = 'Gdata';
          // this.Gdata.list.length
          this.renderTable(this.Gdata);
        } else if (this.request || this.request.url) {
          // requset 有渲染
          if (this.GRdata) {
            this.GRdata.type = 'GRdata';
            this.renderTable(this.GRdata);
          } else {
            this.renderServerTable(this.request);
          }
        } else {
          console.warn('request和data参数必须传递一项');
        }
      },
      getsearchResult(data) {
        try {
          const temp = [];
          const filterSearchFiled = Object.assign({}, this.searchFiled, this.filters);
          Object.keys(filterSearchFiled).forEach((searchitem) => {
            if (searchitem.indexOf(';') < 0) {
              if (filterSearchFiled[searchitem] instanceof Array) {
                const tempFilter = [];
                filterSearchFiled[searchitem].forEach((item, index) => {
                  tempFilter.push(`item['${searchitem}'].toString().indexOf('${filterSearchFiled[searchitem][index]}')>-1`);
                });
                if (tempFilter.length > 0) {
                  temp.push(`(${tempFilter.join('||')})`);
                } else {
                  temp.push(`(${true})`);
                }
              } else {
                temp.push(`item['${searchitem}'].toString().indexOf('${filterSearchFiled[searchitem]}')>-1`);
              }
            } else {
              return true;
            }
          });


          /*var eval2 = eval;
          (function () {
            eval2(temp.join('&&'));
          })();*/
          // eslint-disable-next-line no-unused-vars,array-callback-return
          return data.list.filter((item) => (function (item) {
            return eval(temp.join('&&'));
          })(item));
        } catch (e) {
          return [];
        }
      },
      localSearch(data) {
        let results = {};
        if (Object.keys(this.searchFiled).length || Object.keys(this.filters).length) {
          // console.log(this.getsearchResult(data))
          results = Object.assign({}, {list: this.getsearchResult(data)});
        } else {
          results = data;
        }
        return results;
      },
      execRequestCallback(data) {
        const finnal = Object.assign({}, {list: [], page: null}, data);
        // requestCallback
        this.requestCallback({
          data: finnal.list,
          type: Object.keys(this.searchFiled).length ? 'search' : ''
        }, (e, first = false) => {
          if (e) {
            if (first) {
              this.hasRender = true;
            }
            if (e instanceof Array) {
              const datasource = Object.assign({}, finnal, {list: e});
              this.setPagination(datasource);
              this.dataSource = datasource.list;
              this.loading = false;
            } else {
              const datasource = Object.assign({}, finnal, e);
              this.setPagination(datasource);
              this.dataSource = datasource.list;
              this.loading = false;
            }
          } else {
            this.setPagination(finnal);
            this.dataSource = finnal.list;
            this.loading = false;
          }
        });
      },
      renderTable(data) {
        this.loading = true;
        this.showOption = true;
        const resSearData = this.localSearch(data);
        if (typeof this.requestCallback === 'function' && !this.hasRender) {
          this.execRequestCallback(resSearData);
        } else {
          this.setPagination(resSearData);
          this.dataSource = resSearData.list;
          this.loading = false;
        }
        this.$nextTick(() => {
          /* 数据渲染结束 开始绑定拖拽事件 */
          this.dragOperation();
        });
      },
      renderServerTable(request) {
        this.loading = true;
        let pageParams = Object.assign({}, {
          page: this.defPagination.current,
          size: this.defPagination.pageSize
        }, this.filters, this.searchFiled);
        if (this.sorter.order) pageParams = Object.assign(pageParams, {orderBy: `${this.sorter.field} ${orderbyMap[this.sorter.order]}`});
        if (typeof request === 'string') {
          this.fetch('GET', {url: request, project: this.project, data: pageParams});
        } else if (request.method) {
          // 设置请求分页方式
          this.fetch(request.method.toLocaleUpperCase(), Object.assign({}, {
            project: request.project ? request.project : this.project,
            data: pageParams
          }, this.request));
        } else {
          // 默认请求分页方式 get
          this.fetch('GET', Object.assign({}, {
            project: request.project ? request.project : this.project,
            data: pageParams
          }, this.request));
        }
      },
      setPagination(data) {
        // 开启分页
        if (this.pagination !== false || this.pagination.type === 'server' || this.pagination.type === 'local') {
          // 兼容模式
          if (this.isPageNumber) {
            if (data && data.page) {
              // 服务器分页
              this.defPagination.current = data.page;
              this.defPagination.pageSize = data.size;
              this.defPagination.total = data.total;
            } else if (data) {
              // 本地分页
              this.defPagination.total = data.list.length;
            }
          } else {
            // 自动分页
            if (data && data.page) {
              // 服务器分页
              this.defPagination.current = data.page.pageNum;
              this.defPagination.pageSize = data.page.pageSize;
              this.defPagination.total = data.page.total;
            } else if (data) {
              // 本地分页
              this.defPagination.total = data.list.length;
            }
          }
        }
      },
      restPagination() {
        this.defPagination.current = 1;
      },
      async fetch(method, config) {
        method = method.toLocaleUpperCase();
        if (method === 'GET') {
          config.params = config.data;
        }
        let data = [];
        try {
          // data = await this.getTableData(method, config);
          this.loading = true;
          const {data: dataSource, err} = await this.getTableData(method, config);
          // const dataSource = await this.getTableData(method, config);
          this.loading = false;
          this.showOption = true;
          if (err || !dataSource) return;
          data = dataSource;
          if (dataSource && dataSource.data && dataSource.data.list) {
            data = dataSource.data;
          }
          if (!data.list) {
            data = {list: data.data || data};
            this.GRdata = data;
          }
          if (typeof this.requestCallback === 'function' && !this.hasRender) {
            this.execRequestCallback(data);
          } else {
            this.setPagination(data);
            this.dataSource = data.list;
            // this.loading = false;
          }
          this.$nextTick(() => {
            /* 数据渲染结束 开始绑定拖拽事件 */
            this.dragOperation();
          });
        } catch (e) {
          if (e && e.err === 'cancel') {
            this.loading = true;
            /*this.errorTime = setTimeout(() => {
              this.loading = false;
            },5000);*/
          } else {
            this.loading = false;
          }
          this.showOption = true;
          //  console.error(e);
        }
      },
      getTableData(method, config) {
        /* if (this.source) {
          this.source.cancel({err:'cancel'});
        }
        this.source = this.CancelToken.source();
        const url = `${window.$paraContext[config.project]}/${config.url}?fiql=${config.params.fiql}`;
        // return $axios[method.toLowerCase()](url,Object.assign(config, {cancelToken: this.source.token}))
        let configs = Object.assign(config, {cancelToken: this.source.token});
        return $axios(Object.assign(configs,{url})) */
        this.cancelRequest();
        return new Promise((resolve) => {
          const uuid = http[`$para${method}`](config, resolve);
          // const uuid = http[`$para${method}`]('http://127.0.0.1:3000/gateway/service/test', resolve);
          this.axiosUUID = uuid;
        });
        //return http[`$para${method}`](Object.assign(config, {cancelToken: this.source.token}));
      },
      refresh() {

        // 重置page为0刷新表格
        this.restPagination();
        this.GRdata = null;
        this.chooseDataSource();
      },
      // 清除当前加载中的pending数据
      cancelRequest() {
        if (this.axiosUUID) {
          $paraReqCancel(this.axiosUUID);
        }
      },
      currentRefresh() {
        // 当前page刷新表格
        this.loading = true;
        this.GRdata = null;
        this.chooseDataSource();
      },
      checkAll() {
        // console.log('checkAll');
      },
      expandedRowsChange(expandedRows) {
        // 展开的行变化时触发
        this.$emit('expandedRowsChange', expandedRows);
      },
      change(pagination, filters, sorter) {
        // this.loading = true;
        // 分页、排序、筛选变化时触发
        this.defPagination = Object.assign({}, this.defPagination, pagination);
        this.sorter = sorter;
        this.filters = filters;
        // console.log('pagination===', pagination, 'filters====', filters, 'sorter====', sorter);
        /*if(!this.search.useCache){

        }*/
        if(this.search.hasOwnProperty('useCache')){
          delete this.search.useCache;
        }
        // console.log(" this.search", this.search);
        this.chooseDataSource();
        /* this.$nextTick(() => {
          this.dragOperation();
        }); */
      },
      expand(expanded, record) {
        // 点击展开图标时触发
        this.$emit('expand', expanded, record);
      },
      addDataSource() {
        this.$emit('addrow');
      },
      deleteDataSource(record) {
        this.$emit('deleterow', record);
      },
      // 表格总条数中英文
      showTotal(total) {
        return `${this.showTotalLabel[this.language]} ${total}`;
      },


      /* 获取slots列dataIndex */
      getSlotsCloumsKey() {
        let slotsKey = [];
        let sourceTarg = this.$slots.default;
        if (sourceTarg.length) {
          for (let v of sourceTarg) {
            if (v.componentOptions && v.componentOptions.propsData.dataIndex) {
              slotsKey.push(v.componentOptions.propsData.dataIndex);
            }
          }
        }
        return slotsKey;
      },

      /* 拖拽操作 */

      selectRows() {
        this.isRowSelect = !this.isRowSelect;
        // 选择行显示的时候 拖拽不显示
        if (this.isRowSelect) {
          this.dragColumn = false;
        } else {
          // 选择行不显示的时候 判断拖拽上一次的状态来显示还是不显示
          if (this.defaultDragColumn) {
            this.dragColumn = true;
          } else {
            this.dragColumn = false;
          }
        }
        this.defaultSelcet = this.isRowSelect;
      },
      // 拖拽图标点击
      dragClick() {
        this.dragColumn = !this.dragColumn;
        // 拖拽显示的时候  选择行不显示
        if (this.dragColumn) {
          this.isRowSelect = false;
        } else {
          // 拖拽不显示的时候 判断选择行上一次的状态来显示还是不显示
          if (this.defaultSelcet) {
            this.isRowSelect = true;
          } else {
            this.isRowSelect = false;
          }
        }
        this.defaultDragColumn = this.dragColumn;
      },
      dragOperation() {
        if (!this.drag && !this.dragRequest) return false;
        if (!this.dragKey) {
          // 拖拽唯一标识 key 默认是key
          console.error('请传入正确的dragKey');
          return false;
        }
        const TRLIST = this.$refs.paraTable.querySelectorAll('.ant-table-row');
        /* 绑定事件 */
        for (const TRitem of TRLIST) {
          // 每项tr 绑定 mousedown和mouseup 事件
          this.Event.addEvents(TRitem, 'mousedown', this.dragMouse);
          this.Event.addEvents(TRitem, 'mouseup', this.dragMouse);
        }
      },
      /* 绑定拖拽元素事件 */
      bindSourceDrag(tritem) {
        for (const event of this.dragSourceEventList) {
          this.Event.addEvents(tritem, event, this.dragSourceEvent);
        }
      },
      /* 绑定拖拽目标元素事件 */
      bindAimDrag(tritems) {
        for (const tritem of tritems) {
          for (const event of this.dragAimEventList) {
            this.Event.addEvents(tritem, event, this.dragAimEvent);
          }
        }
      },
      /* 解绑拖拽元素事件 */
      unbindSourceDrag(tritem) {
        for (const event of this.dragSourceEventList) {
          this.Event.removeEvents(tritem, event, this.dragSourceEvent);
        }
      },
      /* 解绑拖拽目标元素事件 */
      unbindAimDrag(tritems) {
        for (const tritem of tritems) {
          for (const event of this.dragAimEventList) {
            this.Event.removeEvents(tritem, event, this.dragAimEvent);
          }
        }
      },
      /* 设置点击的元素tr可拖拽 */
      setDraggable(e, enable = true) {
        if (enable) {
          e.target.closest('tr.ant-table-row').setAttribute('draggable', true);
        } else {
          e.target.closest('tr.ant-table-row').setAttribute('draggable', false);
        }
      },
      /* 拖拽当前应用元素的事件操作 */
      dragSourceEvent(e) {
        if (this.dragDiabled) return false;
        if (e.target.tagName !== 'TR') {
          e.preventDefault();
        }
        if (e.type === 'dragstart' && e.target.tagName === 'TR') {
          e.target.closest('tr.ant-table-row').style.opacity = 0.5;
          e.dataTransfer.setData('key', e.target.closest('tr.ant-table-row').getAttribute('data-row-key'));
          this.$emit('dragstart');
        } else if (e.type === 'drag') {
          // this.$emit('drag');
        } else if (e.type === 'dragleave') {
          //  this.$emit('souredragleave');
        } else if (e.type === 'dragend') {
          e.target.closest('tr.ant-table-row').style.display = 'table-row';
          e.target.closest('tr.ant-table-row').style.opacity = 1;
          this.unbindSourceDrag(e.target.closest('tr.ant-table-row'));
          this.unbindAimDrag(this.Event.sibling(e.target.closest('tr.ant-table-row')));
          this.setDraggable(e, false);
          this.$emit('dragend');
        } else {
          return false;
        }
      },
      /* 目标元素的事件操作 */
      dragAimEvent(e) {
        if (this.dragDiabled) return false;
        if (e.target.tagName !== 'TR') {
          e.preventDefault();
        }
        if (e.type === 'dragenter') {
          this.$emit('dragenter');
        } else if (e.type === 'dragover') {
          const offsetY = e.offsetY;
          const percent = e.target.offsetHeight / 2;
          if (offsetY > percent) {
            this.dragLine(e.target.closest('tr.ant-table-row'), 'bottom');
          } else {
            this.dragLine(e.target.closest('tr.ant-table-row'), 'top');
          }
        } else if (e.type === 'drop') {
          this.dragLine(e.target.closest('tr.ant-table-row'));
          this.transferData(e.dataTransfer.getData('key'), e.target.closest('tr.ant-table-row').getAttribute('data-row-key'));
          this.$emit('drop');
        } else if (e.type === 'dragleave') {
          this.dragLine(e.target.closest('tr.ant-table-row'));
        } else {
          return false;
        }
      },
      /* 拖拽线条 */
      dragLine(el, position) {
        if (position === 'bottom') {
          this.position = 'bottom';
          if (el.style.borderBottom) {
            return false;
          }
          if (el.style.borderTop) {
            el.style.borderTop = '';
          }
          el.style.borderBottom = `3px solid ${this.dragRequest ? this.dragRequest.dragColor || this.dragColor : this.dragColor}`;
        } else if (position === 'top') {
          this.position = 'top';
          if (el.style.borderTop) {
            return false;
          }
          if (el.style.borderBottom) {
            el.style.borderBottom = '';
          }
          el.style.borderTop = `3px solid ${this.dragRequest ? this.dragRequest.dragColor || this.dragColor : this.dragColor}`;
        } else {
          // 全部清空
          // eslint-disable-next-line no-lonely-if
          if (el.style.borderBottom || el.style.borderTop) {
            el.style.borderTop = '';
            el.style.borderBottom = '';
          }
        }
      },
      /* 拖拽行的事件 */
      dragMouse(e) {
        e.cancelBubble = true;
        e.stopPropagation();
        if (e.type === 'mousedown') {
          this.$emit('bindEvent');
          this.dragDiabled = false;
          if (!this.dragColumn) return;
          this.setDraggable(e);
          // 绑定目标元素事件
          this.bindAimDrag(this.Event.sibling(e.target.closest('tr.ant-table-row')));
          // 绑定应用元素事件
          this.bindSourceDrag(e.target.closest('tr.ant-table-row'));
        } else if (e.type === 'mouseup') {
          if (!this.dragColumn) return;
          this.setDraggable(e, false);
          this.unbindSourceDrag(e.target.closest('tr.ant-table-row'));
          this.dragDiabled = true;
        }
      },
      /*点击排序行*/
      moveClick(type, record, index) {
        let skey = record[this.dragKey];
        let akey = null;
        // let skeyIndex = this.dataSource.findIndex((item) => item[this.dragKey] == skey);
        switch (type) {
          case 'up':
            if (index <= 0) return;
            this.position = 'top';
            akey = this.dataSource[index - 1][this.dragKey];
            break;
          case 'down':
            if (index >= this.dataSource.length - 1) return;
            this.position = 'bottom';
            akey = this.dataSource[index + 1][this.dragKey];
            break;
          default:
            break;
        }
        this.transferData(skey, akey);
      },
      /* 拖拽完成数据的转换 */
      transferData(skey, akey) {
        this.filterData(skey, akey);
      },
      /* 拖拽数据的过滤 */
      async filterData(skey, akey) {
        // eslint-disable-next-line eqeqeq 拖拽元素
        const skeyIndex = this.dataSource.findIndex((item) => item[this.dragKey] == skey);
        // eslint-disable-next-line eqeqeq 目标元素
        const akeyIndex = this.dataSource.findIndex((item) => item[this.dragKey] == akey);
        // const {err} = await this.execServerDrag(this.dataSource[akeyIndex]);
        // if(err) return;
        if (this.position === 'top') {
          // console.log('top', akeyIndex, skeyIndex, this.dataSource[akeyIndex], this.dataSource[skeyIndex]);
          if (akeyIndex - skeyIndex === 1) {
            return false;
            // 相邻的行拖拽
            // console.log('top', '相邻的行拖拽');
            // this.swapArr(this.dataSource, skeyIndex, akeyIndex - 1);
          } else {
            let upVal = {
              key: this.dataSource[skeyIndex].key,
              serial: this.dataSource[akeyIndex].serial + 1
            };
            if (this.dragRequest.key) {
              upVal[this.dragRequest.key] = this.dataSource[skeyIndex][this.dragRequest.key];
            }
            if (this.dragRequest.type) {
              upVal['type'] = this.dragRequest.type;
            }
            const {err} = await this.execServerDrag(upVal);
            this.loading = false;
            if (err) return;
            if (akeyIndex > skeyIndex) {
              // console.log('top1111');
              this.swapArr(this.dataSource, skeyIndex, akeyIndex - 1);
            } else {
              // console.log('88888');
              this.swapArr(this.dataSource, skeyIndex, akeyIndex);
            }
          }
        } else {
          // console.log('bottom', akeyIndex, skeyIndex, this.dataSource[akeyIndex], this.dataSource[skeyIndex]);
          // eslint-disable-next-line no-lonely-if
          if (skeyIndex - akeyIndex === 1) {
            return false;
            // 相邻的行拖拽
            // console.log('bottom', '相邻的行拖拽');
            // this.swapArr(this.dataSource, skeyIndex, akeyIndex + 1);
          } else {
            let upVal = {
              key: this.dataSource[skeyIndex].key,
              serial: this.dataSource[akeyIndex].serial - 1
            };
            if (this.dragRequest.key) {
              upVal[this.dragRequest.key] = this.dataSource[skeyIndex][this.dragRequest.key];
            }
            if (this.dragRequest.type) {
              upVal['type'] = this.dragRequest.type;
            }
            const {err} = await this.execServerDrag(upVal);
            this.loading = false;
            if (err) return;
            if (akeyIndex > skeyIndex) {
              this.swapArr(this.dataSource, skeyIndex, akeyIndex);
            } else {
              this.swapArr(this.dataSource, skeyIndex, akeyIndex + 1);
            }
          }
        }
      },
      swapArr(arr, skeyIndex, akeyIndex) {
        arr.splice(akeyIndex, 0, arr.splice(skeyIndex, 1)[0]);
        return arr;
      },
      async execServerDrag(item) {
        this.loading = true;
        let config = {method: 'put'};
        if (this.dragRequest) {
          if (typeof this.dragRequest === 'string') {
            config = Object.assign({
              url: this.dragRequest,
              project: this.project,
              data: item
            }, config);
          } else {
            config = Object.assign({
              url: this.dragRequest.url,
              project: this.dragRequest.project ? this.dragRequest.project : this.project,
              data: item
            }, config, this.dragRequest);
          }
        } else if (this.drag) {
          if (typeof this.request === 'string') {
            config = Object.assign({url: this.request, project: this.project, data: item}, config);
          } else {
            config = Object.assign({
              url: this.request.url,
              project: this.request.project ? this.request.project : this.project,
              data: item
            }, config, this.request);
          }
        }
        return this.getTableData(config.method.toLocaleUpperCase(), config);
      }
    },
    destroyed() {
      this.cancelRequest();
    }
  };
</script>
