<template>
  <div>
    <vxe-grid
      ref="tableRef"
      size="small"
      v-bind="$attrs"
      v-on="listeners"
      :columns="columns"
      :loading="loading"
      :height="tableHeight"
      :keyboard-config="{isArrow: true}"
      :show-overflow="showOverflow"
      :toolbar-config="toolsBar ? toolsBarConfig : false"
      :checkbox-config="{
        trigger: 'row',
        highlight: true,
        range: false,
        checkMethod: defaultCheckMethod
      }"
    >
      <slot slot="default"></slot>
      <template slot="form" v-if="showSearchForm">
        <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"
              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"
            @click="item.onClick"
            :disabled="item.disabled || disabled"
            :key="item.title"
            :type="item.status">
            <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>
          <cms-link size="small" @click="visibleColumnConfig = true" :underline="false">
            <i class="el-icon-setting"></i> 表格设置
          </cms-link>
        </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>
    <cms-column-config
      v-if="visibleColumnConfig"
      v-model="visibleColumnConfig"
      @onCancel="closeModalCallback"
      :finish-callback="finishCallback"
      :columns="columns"
    />
  </div>

</template>

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

export default {
  name: "CmsQueryTable",
  components: { CmsColumnConfig },
  mixins: [ mixTableConstants ],
  data() {
    return {
      tableHeight: "auto",
      activeName: 'first',
      visibleColumnConfig: false,
      checkedCities: [],
      formInline: {
        radio3: undefined,
      },
      toolsBarConfig: {
        size: "small",
        perfect: true,
        slots: {
          buttons: "buttons",
          tools: "tools",
        },
      },
      items: [],
      itemColumn: undefined,
    };
  },
  // 激活组件
  async created() {
    this.initColumns();
    this.$emit('height', window.document.body.clientHeight - 120);
    if (this.height) {
      this.tableHeight = this.height;
    } else {
      this.tableHeight = window.document.body.clientHeight - 120;
    }
    const _this = this;
    if (!this.fixedHeight) {
      window.onresize = () => (() => {
        _this.tableHeight = window.document.body.clientHeight - 120;
      })();
    }
    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: {
    initColumns() {
      this.columns.forEach(col => {
        if (!col.visible) {
          col.visible = true;
        }
        if (!col.fixed) {
          // col.fixed = 'none'
        }
        if (!col.align) {
          col.align = 'left'
        }
      })

      if (this.tableConfig.enable) {
        const params = { configCode: this.tableConfig.configCode };
        this.tableConfig.queryConfigUrl({ ...params }).then(res => {
          if (res.code === 200) {

          }
        })
      }
    },
    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.loading = false
        this.$forceUpdate();
        // if (this.showLoading) { this.customLoading = true;}
        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.loading = 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;
      }
      this.loading = true
      if (typeof this.requestCall === "function") {
        if (this.pagination) {
          this.queryParams.rows = this.tablePage.pageSize;
          this.queryParams.page = this.tablePage.currentPage;
        }
        this.requestCall(this.queryParams, { loading: false }).then((response) => {
          if (this.pagination && this.$refs["tableRef"]) {
            const { rows, total } = response;
            this.$nextTick(() => {
              this.$refs["tableRef"].loadData(rows);
              this.tablePage.total = total;
              this.loading = false
              if (this.callback) {
                this.callback(rows);
              }
            });
          } else {
            if (this.$refs["tableRef"]) {
              this.$refs["tableRef"].loadData(response.rows);
              if (this.callback) {
                this.callback(response.rows);
              }
            }
            this.loading = false
          }
        });
      } else if (Array.isArray(this.requestCall)) {
        this.$refs["tableRef"].loadData(this.requestCall);
        this.loading = 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;
        }
        this.loading = 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);
    },
    // finishCallback 配置完成进行重新加载， 并且保存到数据库
    finishCallback(columns) {
      this.visibleColumnConfig = false;
      console.log('finishCallback:', columns);
      this.$refs['tableRef'].reloadColumn(columns);
      if (this.tableConfig.enable) {
        const params = { configCode: this.tableConfig.configCode };
        this.tableConfig.saveConfigUrl({ ...params }).then(res => {
          if (res.code === 200) {
            this.$messageTips.success(res.msg);
          }
        })
      }
    },
    closeModalCallback(visible) {
      console.log('回调关闭方法')
      this.visibleColumnConfig = visible;
    },
  },
  computed: {
    buttonSize() {
      return this.$store.getters["setting/getButtonSize"];
    },
    customLoading: {
      get() {
        return this.showLoading ? this.loading : false;
      },
      set(val) {
        if (this.showLoading)
          this.loading = val;
      }
    }
  },

  props: {
    columns: {
      type: Array,
      default: () => {
        return []
      },
    },
    tableConfig: {
      type: Object,
      default: () => {
        return {
          enable: false,  // 是否启用表格配置
          configCode: undefined, // 配置表格的编号， 唯一值
          saveConfigUrl: Function, // 保存表格配置信息的地址
          queryConfigUrl: Function, // 查询表格配置信息的地址
        }
      }
    }
  }
};
</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>
