<template>
  <vxe-grid
    ref="tableRef"
    size="small"
    v-bind="$attrs"
    v-on="listeners"
    :columns="columns"
    :loading="customLoading"
    :height="tableHeight"
    :keyboard-config="{isArrow: true}"
    :show-overflow="showOverflow"
    :checkbox-config="{
      highlight: true,
      trigger: 'row',
      checkMethod: defaultCheckMethod
    }"
    :export-config="{}"
    :toolbar-config="toolsBar ? toolsBarConfig : false"
  >
    <slot></slot>
    <template slot="form" v-if="showSearchForm">
      <el-card class="box-card">
        <div class="cms-search-container">
          <cms-query-form
            :label-width="labelWidth"
            :form-model="queryParams"
            label-align="right"
            size="small"
            class="cms-search-form"
          >
            <el-row>
              <cms-query-item
                v-for="(item, index) in items"
                :prop="item.prop"
                :column="itemColumn"
                :key="index"
                :collapse.sync="collapse"
                :folding="index > (itemColumn ? itemColumn - 1 : 2)"
                :collapse-node="index > (itemColumn ? itemColumn - 1 : 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 size="small">
              <cms-button
                :disabled="disabled"
                size="small"
                @click="searchTable"
                type="primary"
                icon="el-icon-search"
              >
                {{ this.$t("common.button.search") }}
              </cms-button>
              <cms-button size="small" :disabled="disabled" @click="resetClick" icon="el-icon-s-promotion">
                <span>{{ $t("common.button.reset") }}</span>
              </cms-button>
              <cms-button
                :disabled="disabled"
                size="small"
                v-if="items.length > (itemColumn ? itemColumn : 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">
      <cms-button-group v-if="toolsBar">
        <cms-button
          size="small"
          v-for="item in toolsBar"
          :disabled="item.disabled || disabled"
          :key="item.title"
          :type="item.status"
          @click="item.onClick"
        >
          <i v-if="item.customIcon" :class="'icon ' + item.icon" style="font-size: 13px;margin-right: 7px"></i>
          <i v-else :class="item.icon"></i>
          {{ item.title }}
        </cms-button>
        <slot name="buttons"></slot>
      </cms-button-group>
    </template>
    <template #tools>
      <cms-button-group>
        <cms-link size="small" :underline="false">
          <i class="el-icon-printer"></i> 打印表格
        </cms-link>
        <cms-link size="small" :underline="false" @click="openExportEvent">
          <i class="el-icon-download"></i> 导出表格
        </cms-link>
        <el-popover
          placement="bottom"
          width="350"
          popper-class="table-setting"
          trigger="click">
          <cms-link size="small" slot="reference" :underline="false">
            <i class="el-icon-setting"></i> 表格设置
          </cms-link>
          <template>
            <el-tabs :stretch="true" v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="列顺序" name="first">
                <div class="cms-card">
                  <el-tag
                    type="info" v-for="column in columns" :key="column.field"
                    style="height: 30px;line-height: 30px; margin: 5px">
                    {{ column.type ? (column.type === 'radio' ? '单选框' : '多选框') : column.title }}
                  </el-tag>
                </div>
              </el-tab-pane>
              <el-tab-pane label="冻结列" name="second">
                未冻结元素
                <div class="cms-card">
                  <span v-for="column in columns" :key="column.field">
                    <el-tag
                      type="info"
                      v-if="!column.fixed"
                      style="height: 30px;line-height: 30px; margin: 5px">
                      {{ column.type ? (column.type === 'radio' ? '单选框' : '多选框') : column.title }}
                    </el-tag>
                  </span>
                </div>
                <el-row :gutter="5">
                  <el-col :span="12">
                    冻结到左侧
                    <div class="cms-card cms-card-left">
                      <span v-for="column in columns" :key="column.field">
                        <el-tag
                          type="info"
                          v-if="column.fixed && column.fixed === 'left'"
                          style="height: 30px;line-height: 30px; margin: 5px">
                          {{ column.type ? (column.type === 'radio' ? '单选框' : '多选框') : column.title }}
                        </el-tag>
                      </span>
                    </div>
                  </el-col>
                  <el-col :span="12">
                    冻结到右侧侧
                    <div class="cms-card cms-card-right">
                      <span v-for="column in columns" :key="column.field">
                        <el-tag
                          type="info"
                          v-if="column.fixed && column.fixed === 'right'"
                          style="height: 30px;line-height: 30px; margin: 5px">
                          {{ column.type ? (column.type === 'radio' ? '单选框' : '多选框') : column.title }}
                        </el-tag>
                      </span>
                    </div>
                  </el-col>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="隐藏列" name="third">
                <div class="cms-card">
                  <el-checkbox-group
                    v-model="checkedCities">
                    <el-checkbox v-for="column in columns" :label="column.field" :key="column.field">
                      {{ column.type ? (column.type === 'radio' ? '单选框' : '多选框') : column.title }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-tab-pane>
            </el-tabs>
            <div style="height: 50px; line-height: 40px;text-align: right; padding: 5px">
              <cms-button size="small" type="primary">确定</cms-button>
              <cms-button size="small" type="primary">重置</cms-button>
              <cms-button size="small" type="info">取消</cms-button>
            </div>
          </template>
        </el-popover>
      </cms-button-group>
    </template>
    <template slot="pager" v-if="pagination">
      <vxe-pager
        :size="this.$attrs.size"
        @page-change="pageChange"
        :loading="this.customLoading"
        :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="empty">
      <slot name="empty">
        <div>
          {{ $t("common.message.emptyText") }}
        </div>
      </slot>
    </template>
    <template slot="top">
      <slot name="top"></slot>
    </template>
    <template slot="bottom">
      <slot name="bottom"></slot>
    </template>
  </vxe-grid>
</template>

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

export default {
  name: "CmsTreeTable",
  mixins: [ mixTableConstants ],
  data() {
    return {
      tableHeight: 400,
      activeName: 'first',
      checkedCities: [],
      formInline: {
        radio3: undefined,
      },
      toolsBarConfig: {
        size: "small",
        perfect: true,
        slots: {
          buttons: "buttons",
          tools: "tools",
        },
      },
      items: [],
      itemColumn: undefined,
    };
  },
  // 激活组件
  async created() {
    this.initTableData();
  },
  activated() {
    this.initTableData();
  },
  watch: {
    requestCall: {
      handler(val) {
        if (Array.isArray(val)) {
          if (this.$refs["tableRef"]) this.$refs["tableRef"].loadData(val);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    defaultCheckMethod(params) {
      if (this.checkMethod) {
        return this.checkMethod(params);
      }
      const row = params.row;
      return row['approvalStatus'] !== 4;

    },
    /**
     * 导出操作
     */
    openExportEvent() {
      const cols = []
      this.columns.forEach(item => {
        if (item.field !== 'opts' && item.field !== 'checkbox' && item.field !== 'radio') {
          cols.push(item)
        }
      })
      this.$refs.tableRef.openExport({
        columns: cols,
      })
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    searchTable() {
      if (this.showLoading) {
        this.customLoading = true;
      }
      if (this.searchMethod) {
        this.searchMethod()
      }
    },
    initTableData() {
      this.$nextTick(() => {
        this.customLoading = false;
        this.$forceUpdate();
        if (!Array.isArray(this.formItemConfig)) {
          this.items = this.formItemConfig.items;
          this.itemColumn = this.formItemConfig.column;
        } else {
          this.items = this.formItemConfig;
        }
        if (this.constantLoad) {
          if (typeof this.constantLoad === 'function')
            this.constantLoad().then(() => {
              this.customLoading = true;
              setTimeout(() => {
                this.loadTableData();
              }, 100)
            })
        } else {
          this.loadTableData();
        }
        if (!this.fixedHeight) {
          // window.onresize = () => {
          //   if (!this.fixedHeight) {
          //     this.tableHeight = window.document.body.clientHeight;
          //   }
          // };
        }
        if (this.height) {
          this.tableHeight = this.height;
        } else {
          this.tableHeight = window.document.body.clientHeight;
        }
      });
    },


    resetClick() {
      for (const key in this.queryParams) {
        this.queryParams[key] = undefined
      }
      this.$emit('resetClick')
    },
    /**
     * 初始化加载表格
     */
    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;
              this.customLoading = false;
              if (this.callback) {
                this.callback(rows);
              }
            });
          } else {
            if (this.$refs["tableRef"]) {
              this.$refs["tableRef"].loadData(response.data);
              if (this.callback) {
                this.callback(response.rows);
              }
            }
            this.customLoading = false;
          }
        });
      } else if (Array.isArray(this.requestCall)) {
        this.$refs["tableRef"].loadData(this.requestCall);
        this.customLoading = false;
      } 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.data;
          this.$refs["tableRef"].loadData(this.requestCall.data);
          console.log(this.tableData, '===============')
        }
        this.customLoading = false;
      }
    },
    /**
     * 获取多条件展开
     */
    getFolding() {
      this.collapse = !this.collapse;
    },
    newInstance() {
      return this.$refs["tableRef"];
    },
    getCheckboxRecords() {
      return this.$refs["tableRef"].getCheckboxRecords();
    },
    reload() {
      this.customLoading = true;
      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);
    },
    cellDblClick(data) {
      this.$emit("cell-dblclick", data);
    },
  },
  computed: {
    customLoading: {
      get() {
        return this.showLoading ? this.loading : false;
      },
      set(val) {
        if (this.showLoading)
          this.loading = val;
      }
    }
  },
};
</script>

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

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

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

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

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

.vxe-toolbar .vxe-buttons--wrapper {
  -webkit-box-flex: 1;
  flex-grow: 1;
  padding-left: 5px;
  padding-right: 5px;
}

.cms-search-container {
  display: flex;
  width: 100%;
  padding-right: 5px;
  flex-direction: row;

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

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

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

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

  .toolbar-tools-right {
    width: auto;
  }
}

.el-popover__reference-wrapper {
  a:hover {
    text-decoration: none;
  }
}
.el-button-group {
  .el-button {
    padding: 8px !important;
  }
}
</style>
