<template>
  <div>
    <vxe-grid
      ref="tableRef"
      size="small"
      v-bind="$attrs"
      v-on="listeners"
      :columns="columns"
      :loading="loading"
      :height="(tableHeight - 1)"
      :show-overflow="showOverflow"
      :checkbox-config="{
        trigger: 'row',
        highlight: true,
        checkMethod: defaultCheckMethod
      }"
      :expand-config="{
        expandAll: true
      }"
      :menu-config="menuConfig"
      :valid-config="validConfig"
      :keyboard-config="keyboardConfig"
      :custom-config="customConfig"
      :tree-config="treeConfig"
      :mouse-config="mouseConfig"
      :export-config="{}"
      :toolbar-config="toolsBar ? toolsBarConfig : false"
    >
      <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"
              ref="queryFormRef"
              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="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 "../CmsQueryTable/CmsColumnConfig";

export default {
  name: "CmsTreeTable",
  mixins: [ mixTableConstants ],
  components: { CmsColumnConfig },
  data() {
    return {
      visibleColumnConfig: false,
      tableHeight: "auto",
      activeName: 'first',
      checkedCities: [],
      formInline: {
        radio3: undefined,
      },
      toolsBarConfig: {
        size: "small",
        perfect: true,
        slots: {
          buttons: "buttons",
          tools: "tools",
        },
      },
      items: [],
      itemColumn: undefined,
    };
  },
  // 激活组件
  async created() {
    this.initColumns();
    if (this.fixedHeight) {
      this.tableHeight = this.height;
    } else {
      const h = window.document.body.clientHeight;
      if (h < 800) this.tableHeight = h - this.marginTop - 2;
      else this.tableHeight = h - this.marginTop;
    }
    console.log('-----tableHeight', this.tableHeight);
    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,
    },
    'height': {
      handler(val) {
        if (this.fixedHeight) {
          this.tableHeight = val;
          console.log('------watch height', val);
        }
      },
      immediate: 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() {
      this.$refs.queryFormRef.validate(valid => {
        if (valid) {
          if (this.searchMethod) {
            this.searchMethod()
          }
        }
        return false;
      })
    },
    initTableData() {
      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 && typeof this.constantLoad === 'function') {
        this.constantLoad().then(() => {
          this.loading = true;
          setTimeout(() => {
            this.loadTableData();
          }, 200)
        })
      } else {
        this.loadTableData();
      }
    },
    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
      setTimeout(() => {
        if (typeof this.requestCall === "function") {
          this.requestCall(this.queryParams, { loading: false }).then((response) => {
            if (this.$refs["tableRef"]) {
              this.$refs["tableRef"].loadData(response.data);
              if (this.callback) {
                this.callback(response.rows);
              }
            }
            this.loading = false
          }).catch(() => {
            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.$refs["tableRef"]) {
            this.$refs["tableRef"].loadData(this.requestCall["data"]);
          } else {
            this.tableData = this.requestCall;
          }
          this.loading = false
        }
      }, 300);
    },
    /**
     * 获取多条件展开
     */
    getFolding() {
      this.collapse = !this.collapse;
    },
    newInstance() {
      return this.$refs["tableRef"];
    },
    getCheckboxRecords() {
      return this.$refs["tableRef"].getCheckboxRecords();
    },
    reload() {
      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) {
      this.visibleColumnConfig = visible;
    },
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        const _this = this;
        if (!this.fixedHeight) {
          window.onresize = () => (() => {
            const h = window.document.body.clientHeight;
            if (h < 800) _this.tableHeight = h - this.marginTop - 2;
            else _this.tableHeight = h - this.marginTop;
          })();
        }
      })();
    };
  },
  props: {
    columns: {
      type: Array,
      default: () => {
        return []
      }
    },
    treeConfig: {
      type: Object,
      default: () => {
        return {
          expandRowKeys: [],
          children: 'children',
          hasChild: 'hasChild',
        }
      }
    },
    expandConfig: Object,
    menuConfig: Object,
    validConfig: Object,
    mouseConfig: Object,
    customConfig: Object,
    keyboardConfig: {
      type: Object,
      default: () => {
        return { isArrow: true }
      }
    },
    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>
