<template>
  <div class="CmsEditTable">
    <vxe-grid
      perfect
      row-id="id"
      ref="tableRef"
      v-bind="$attrs"
      v-on="listeners"
      :round="true"
      :auto-resize="true"
      :show-overflow="true"
      :keep-source="true"
      :toolbar-config="toolsBar ? toolsBarConfig : false"
      :column-key="true"
      :seq-config="{ seqMethod: seqMethod }"
      :highlight-hover-row="true"
      :columns="columns"
      :edit-config="tableEditConfig"
      :export-config="{
        filename: new Date().getTime(),
      }"
    >
      <template slot="form">
        <slot name="form" v-if="formItemConfig.length === 0"></slot>
        <el-card class="box-card" v-else>
          <div slot="header"><i class="el-icon-info"></i> 搜索条件</div>
          <div class="cms-search-container">
            <cms-query-form
              :label-width="labelWidth"
              :form-model="queryParams"
              ref="queryForm"
              label-align="right"
              class="cms-search-form"
            >
              <el-row>
                <cms-query-item
                  v-for="(item, index) in formItemConfig"
                  :prop="item.prop"
                  :column="item.column"
                  :key="index"
                  :collapse.sync="collapse"
                  :folding="index > 2"
                  :collapse-node="index > 2"
                  :label="item.label"
                >
                  <slot :name="item.prop"></slot>
                </cms-query-item>
              </el-row>
            </cms-query-form>
            <div class="cms-search-tools">
              <cms-button-group>
                <cms-button
                  :disabled="disabled"
                  @click="searchTable"
                  type="primary"
                  icon="search"
                >
                  {{ this.$t("common.button.search") }}
                </cms-button>
                <cms-button :disabled="disabled" @click="resetClick" type="success">
                  <cms-svg-icon
                    icon-class="reset"
                    style="width: 0.91em; height: 0.91em"
                  />
                  <span style="padding-left: 5px">{{ $t("common.button.reset") }}</span>
                </cms-button>
                <cms-button
                  :disabled="disabled"
                  v-if="formItemConfig.length > 3"
                  type="warning"
                  @click.native="getFolding"
                >
                  <i
                    style="font-weight: bold"
                    :class="collapse ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
                  ></i>
                  {{ collapse ? "收起" : "展开" }}
                </cms-button>
              </cms-button-group>
            </div>
          </div>
        </el-card>
      </template>
      <template slot="buttons">
        <div class="toolbar-tools-left">
          <slot name="left-button">
            <cms-button-group v-if="toolsBar">
              <cms-button
                :disabled="disabled"
                v-for="item in toolsBar"
                :key="item.title"
                :type="item.status"
                :icon="item.icon"
                v-permission="[item.access]"
                @click="item.onClick"
              >
                {{ item.title }}
              </cms-button>
              <slot name="buttons"></slot>
            </cms-button-group>
          </slot>
        </div>
      </template>
      <template slot="pager" v-if="pagination">
        <vxe-pager
          @page-change="pageChange"
          :auto-hidden="false"
          :current-page.sync="tablePage.currentPage"
          :perfect="true"
          :page-size.sync="tablePage.limit"
          :total="tablePage.total"
          :layouts="[
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'Sizes',
            'FullJump',
            'Total',
          ]"
        >
        </vxe-pager>
      </template>
      <template slot="top">
        <slot name="top"></slot>
      </template>
      <template slot="bottom">
        <slot name="bottom"></slot>
      </template>
    </vxe-grid>
  </div>
</template>

<script>
import { mixTableConstants } from "../mixin/common-mixins";
import "./_CmsEditTable.less";

export default {
  mixins: [ mixTableConstants ],
  props: {
    columns: Array,
    parentHeight: {
      type: Number,
      default: () => {
        return 0;
      },
    },
    customForm: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    labelWidth: {
      type: String,
      default: () => {
        return "100px";
      },
    },
    emptyText: {
      type: String,
      default: () => {
        return "";
      },
    },
    formRule: {
      type: Object,
      default: () => {
        return {};
      },
    },
    showRight: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    formItemConfig: {
      type: Array,
      default: () => {
        return [];
      },
    },
    callback: Function,
  },
  data() {
    return {
      toolsBarConfig: {
        size: "small",
        perfect: true,
        slots: {
          buttons: "buttons",
        },
      },
    };
  },
  watch: {
    requestCall: {
      handler() {
        this.loadTableData();
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    tableEditConfig() {
      return {
        trigger: 'manual',
        mode: 'row',
        autoClear: false,
        ...this.editConfig
      };
    }
  },
  async created() {
    console.log("=============", this);
    this.$nextTick(() => {
      this.loadTableData();
      this.$emit("height", window.document.body.clientHeight - 120);
      if (this.height) {
        this.tableHeight = this.height;
      } else {
        this.tableHeight = window.document.body.clientHeight - 120;
      }
      window.onresize = () => {
        if (!this.fixedHeight) {
          this.tableHeight = window.document.body.clientHeight - 120;
        }
      };
    });
  },
  methods: {
    searchTable() {
      this.$emit('searchMethod')
    },
    resetClick() {
      this.$emit('resetClick');
    },
    getTable() {
      return this.$refs["tableRef"];
    },
    getRef() {
      return this.$refs["queryForm"].getRef();
    },
    /**
     * 初始化加载表格
     */
    loadTableData() {
      if (!this.requestCall) {
        this.$messageTips.warning("请求地址不存在，请检查配置.");
        return false;
      }
      if (typeof this.requestCall === "function") {
        if (this.pagination) {
          this.queryParams.rows = this.tablePage.pageSize;
          this.queryParams.page = this.tablePage.currentPage;
        }
        this.requestCall(this.queryParams).then((response) => {
          if (this.pagination && this.$refs["tableRef"]) {
            const { rows, total } = response;
            this.$nextTick(() => {
              this.$refs["tableRef"].loadData(rows);
              this.tablePage.total = total;
              if (this.callback) {
                this.callback(rows);
              }
            });
          } else {
            if (this.$refs["tableRef"]) {
              this.$refs["tableRef"].loadData(response.data);
              if (this.callback) {
                this.callback(response.data);
              }
            }
          }
        });
      } else if (Array.isArray(this.requestCall) && this.$refs["tableRef"]) {
        this.$refs["tableRef"].loadData(this.requestCall);
      } else if (typeof this.requestCall == "object") {
        if (this.pagination && this.$refs["tableRef"]) {
          this.$refs["tableRef"].loadData(this.requestCall["rows"]);
          this.tablePage.total = this.requestCall["total"];
        } else {
          this.tableData = this.requestCall;
        }
      }
    },
    /**
     * 获取多条件展开
     */
    getFolding() {
      const bool = !this.collapse;
      this.$store.dispatch("changeCollapse", bool);
      this.collapse = bool;
    },
    newInstance() {
      return this.$refs["tableRef"];
    },
    getCheckboxRecords() {
      return this.$refs["tableRef"].getCheckboxRecords();
    },
    reload() {
      if (this.pagination) this.tablePage.currentPage = 1;
      this.loadTableData();
    },
    pageChange({ type, currentPage, pageSize }) {
      if (type === "size") {
        this.tablePage.currentPage = 1;
        this.tablePage.pageSize = pageSize;
      } else {
        this.tablePage.currentPage = currentPage;
      }
      this.loadTableData();
    },
    currentChange(event) {
      this.$emit("current-change", event);
    },
    filterMethod({ value, row, column }) {
      console.log(value, row, column);
    },
    /**
     * 往表格插入临时数据，从指定位置插入一行或多行；
     * 第二个参数：row 指定位置（不支持树表格）、
     * null从第一行插入、-1 从最后插入
     * 返回: records: Array<object>, row?: Row
     * 用法:
     */
    async insertAt(records = {}, row) {
      let table = this.newInstance();
      let hasActive = table.getActiveRecord();
      if (hasActive) {
        return Promise.reject(hasActive);
      }
      let result = { row_status: 'add', ...records, row_add: true };
      const { row: newRow } = await table.insertAt(result, row);
      this.newInstance().setActiveRow(newRow);
      return Promise.resolve(newRow);
    },
    // 获取新增内容
    getInsertRecords() {
      return Promise.resolve(this.newInstance().getInsertRecords());
    },
    // 获取修改内容
    getUpdateRecords() {
      return Promise.resolve(this.newInstance().getUpdateRecords());
    },
    // 获取删除内容
    getRemoveRecords() {
      return Promise.resolve(this.newInstance().getRemoveRecords());
    },
    getAllRecords() {
      return Promise.resolve(this.newInstance().getTableData());
    },
    // 还原操作
    revertAt() {
      return this.newInstance().revertData();
    },
    // 打开编辑操作
    setActiveRow(row) {
      return this.newInstance().setActiveRow(row);
    },
    clearActived() {
      return this.newInstance().clearActived();
    },

    batchLines(row) {
      let rows = this.batchSave(row);
      return new Promise(resolve => {
        this.newInstance().reloadData(rows).then(() => {
          resolve({ rows, row });
        });
      });
    },
    batchSave(row) {
      /**
       * 此处待优化
       * 1. vxe-table 里面有getCheckboxRecords()方法
       */
      let isCheckboxConfig = !!Object.keys(this.checkboxConfig || {}).length,
        checkboxKey = isCheckboxConfig ? this.checkboxConfig.checkField : '';
      return this.tableData.map(tr => {
        if (isCheckboxConfig && tr[checkboxKey]) {
          for (let key in row) {
            let td = row[key];
            if (!(td == null || td.length === 0)) {
              tr[key] = td;
            }
          }
        }
        return tr;
      });
    },
    removeRow(row) {
      return this.newInstance().remove(row);
    },
    // 表格调度中心 = 代理 + 适配 模式
    tableDispatch(methodName, ...args) {
      return this.getTable()[methodName](...args);
    }
  },
}
</script>

<style scoped lang="less">
/deep/ .el-card__body {
  padding: 0 !important;
}

/deep/ .el-card__header {
  padding: 10px;
  background: #f8f8f9 !important;

  .clearfix {
    span {
      i {
        margin-right: 5px;
      }
    }
  }
}

/deep/ .cms-form .r-main {
  padding: 0;
}

/deep/ .cms-form .r-bottom {
  line-height: 55px;
  height: 45px;
  padding: 0 !important;
}

.cms-search-container {
  display: flex;
  width: 100%;
  flex-direction: row;

  .cms-search-form {
    flex: 1;
  }

  .cms-search-tools {
    width: auto;
    padding-top: 10px;
    padding-left: 10px;
  }
}

.toolbar-tools {
  display: flex;
  flex-direction: row;

  .toolbar-tools-left {
    flex: 1;
  }

  .toolbar-tools-right {
    width: auto;
  }
}
</style>
