<template>
  <div>
    <p-query-form ref="form"
                  v-if="queryItems && queryItems.length>0"
                  :items="queryItems"
                  :colNum="colNum"
                  :colSpan="colSpan"
                  @submit="handleQueryEvent" />

    <div v-if="queryItems && queryItems.length>0"
         style="height: 20px"></div>

    <p-table ref="table"
             :bordered="true"
             :filterDropdownColum="false"
             :colorTransformRow="false"
             :dragle="true"
             :autoWidth="true"
             :rowSelectFixed="true"
             :hasRowSelectCheck="true"
             :columns="tableColumns"
             :rowKey="uniqueKey"
             :autoLoad="false"
             :scroll="scroll"
             :dataSource.sync="tableData"
             :rowSelectType="selectType"
             :remoteUrl="remote"
             :remoteData="remoteData"
             :remoteParams="remoteParams"
             @selectChange="onSelectedChange">

      <!-- custom -->
      <template v-for="item of customCols"
                v-slot:[item.dataIndex]="text, record">
        <span class="link" v-if="item.type=='click'"
              @click.stop="item.onClick(text, record)"
              :key="item.dataIndex">{{ text }}</span>
        <span v-if="item.type=='mapper'"
              :key="item.dataIndex">{{mapper(item, text)}}</span>
        <p-switch v-if="item.type=='switch'"
                  :key="item.dataIndex"
                  :checked="text"
                  @click="(checked, event)=>handleClick(event,checked,item.dataIndex,record)" />
      </template>

      <!-- operators -->
      <template v-if="operators && operators.length > 0"
                v-slot:operator="text, record">
        <template v-for="item of operators">
          <span v-if="typeof item.onShow === 'function' ? item.onShow(record) : true"
                :key="item.key"
                class="table-operator-item"
                @click="item.onClick(record)">
            {{ item.label }}
          </span>
        </template>
      </template>

    </p-table>
  </div>
</template>

<script>
import PQueryForm from '../../query-form/src/index.vue'

export default {
  name: 'PQueryTable',
  components: { PQueryForm },
  props: {
    queryItems: { // 查询表单配置
      type: Array,
      default: null,
    },
    colNum: {
      type: Number,
      default: 3,
    },
    colSpan: {
      type: Object,
      default() {
        return { label: 10, wrapper: 12 }
      },
    },
    columns: { // 表格列配置
      type: Array,
      default() { return [] },
    },
    uniqueKey: { // 唯一键
      type: String,
      default: '',
    },
    remoteMethod: {
      type: String,
      default: null,
    },
    remoteUrl: {
      type: String,
      default: null,
    },
    autoLoad: { // 初始自动加载数据
      type: Boolean,
      default: false,
    },
    selectType: { // 表格勾选类型
      type: Number,
      default: 2,
    },
    fixedOperators: {
      type: Boolean,
      default: false,
    },
    operators: {
      type: Array,
      default() { return [] },
    },
    scrollX: {
      type: Number,
      default: null,
    },
    scrollY: {
      type: Number,
      default: null,
    },
    remotep: {
      type: Object,
      default() {
        return {}
      }
    }
  },

  data() {
    return {
      tableColumns: [],
      remoteParams: {},
      remoteData: {},
      tableData: null,
      selectedRows: [],
      selectedRowKeys: [],
      scroll: { x: true },
      customCols: [],
    }
  },

  watch: {
    columns: {
      immediate: true,
      handler(columns) {
        let tableColumns = [...columns];
        this.initDynamicCols(tableColumns)
        if (this.operators.length > 0) {
          tableColumns.push(this.initOperator());
        }
        this.tableColumns = tableColumns;
        this.initScroll();
      },
    },
    remoteMethod: {
      immediate: true,
      handler() {
        if (this.remoteMethod && this.remoteUrl) {
          this.remote = {
            method: this.remoteMethod,
            url: this.remoteUrl,
          };
          this.$nextTick(() => {
            this.reload();
          })
        } else {
          this.remote = null;
        }
      },
    },
  },

  methods: {

    /* 对外方法 */
    reload() {
      if (this.$refs.form) {
        this.$refs.form.handleQuery();
      } else {
        this.handleQueryEvent({});
      }
    },

    getDateList(isSelected = false) {
      if (isSelected) {
        return this.selectedRows;
      } else {
        return this.tableData;
      }
    },

    /* 事件方法 */
    onSelectedChange(keys, rows) {
      this.selectedRows = rows;
      this.selectedRowKeys = keys;
      this.$emit('onSelectedChange', { keys: keys, rows: rows });
    },

    /* 内部方法 */
    initOperator() {
      let col = {
        title: '操作',
        dataIndex: 'operator',
        key: 'operator',
        scopedSlots: { customRender: 'operator' },
      }
      if (this.fixedOperators) {
        col.fixed = 'right';
      }
      let width = 0;
      this.operators.forEach(tt => {
        width += tt.label.length * 20;
      });
      if (width) col.width = width + 20;
      return col;
    },
    mapper(data, text) {
      if(data.mapper) return
      let row  = data.mapper.find(item => {
        return item.value == text
      })
      return row ? row.label : ''
    },

    initScroll() {
      let scroll = {};
      if (this.scrollX) scroll.x = this.scrollX;
      else scroll.x = true;
      if (this.scrollY) scroll.y = this.scrollY;
      this.scroll = scroll;
    },

    initDynamicCols(columns) {
      columns.forEach(tt => {
        if (!tt.customCol) { return; }
        // 'switch'
        // 'click'
        // 'mapper'
        this.customCols.push({
          type: tt.customCol,
          dataIndex: tt.dataIndex,
          mapper: tt.customCol== 'mapper'? tt.mapper : '',
          onClick: tt.customCol == 'click' ? tt.onClick : ''
        });
        Reflect.deleteProperty(tt, 'customCol')
        tt.scopedSlots = { customRender: tt.dataIndex };
      });
    },

    handleQueryEvent(params) {
      this.$emit('handleQueryEvent')
      if (this.remoteMethod === "post") {
        this.remoteData = {...params,...this.remotep};
      } else {
        this.remoteParams = {...params,...this.remotep};
      }
    },

    handleClick(event, checked, key, record) {
      event.stopPropagation();
      let col = this.tableColumns.find(t => t.dataIndex == key)
      console.log('handleClick', checked, key, record, col)
      col.onClick(checked, record);
    },

    // handleChange(checked) {
    //   console.log('handleChange', checked)
    // },



  },
}
</script>

<style>
.table-operator-item {
  margin-left: 10px;
  color: #2b80ff;
  cursor: pointer;
}
.table-operator-item:first-child {
  margin-left: 5px;
}
.table-operator-item:hover {
  text-decoration: underline;
}
.link {
  color: #2b80ff;
  cursor:pointer;
}
.link:hover {
  text-decoration: underline;
}
</style>