<template>
  <div class="cms-table__custom">
    <el-card class="box-card" v-if="showSearchForm">
      <cms-query-form-condition
        ref="queryFormRef"
        :disabled="disabled"
        :query-params="queryParams"
        :query-rules="queryRules"
        :label-width="labelWidth"
        :items="items"
        :item-column="itemColumn"
        @search="searchTable"
        @reset="resetClick">
        <template v-for="(item) in items" :slot="item.prop">
          <slot :name="item.prop"></slot>
        </template>
      </cms-query-form-condition>
    </el-card>
    <vxe-toolbar v-if="(Array.isArray(toolsBar) && toolsBar.length > 0)">
      <template #buttons>
        <cms-button-group>
          <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>
    </vxe-toolbar>
    <vxe-table
      ref="tableRef"
      size="small"
      v-bind="$attrs"
      v-on="listeners"
      :loading="loading && partialLoading"
      :height="tableHeight"
      :menu-config="menuConfig"
      :valid-config="validConfig"
      :keyboard-config="keyboardConfig"
      :custom-config="customConfig"
      :mouse-config="mouseConfig"
      :show-overflow="showOverflow"
      :scroll-y="{mode: 'wheel'}"
      :checkbox-config="Object.assign({}, {
        highlight: true,
        trigger: 'row',
        checkMethod: defaultCheckMethod
      }, checkboxConfig || {})"
      :row-config="Object.assign({
        useKey: false,
        keyField: 'id',
        isCurrent: true,
        isHover: true,
      }, rowConfig || {})"
    >
      <template slot="empty">
        <slot name="empty">
          <div>
            {{ $t("common.message.emptyText") }}
          </div>
        </slot>
      </template>
      <template>
        <slot name="columns"></slot>
      </template>
    </vxe-table>
    <vxe-pager
      v-if="pagination"
      @page-change="pageChange"
      :auto-hidden="false"
      :current-page.sync="tablePage.currentPage"
      :perfect="true"
      :page-size.sync="tablePage.limit"
      :total="tablePage.total"
      :layouts="layouts ? layouts : [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total',
      ]">
    </vxe-pager>
  </div>
</template>

<script>
import { mixTableConfig, mixTableConstants } from "../mixin/common-mixins";
import CmsColumnConfig from "./CmsColumnConfig";
import HttpService from "@/utils/HttpService";

export default {
  name: "CmsCustomTable",
  components: { CmsColumnConfig },
  mixins: [ mixTableConstants ],
  data() {
    return {
      tableHeight: 400,
      activeName: 'first',
      visibleColumnConfig: false,
      defaultQueryForm: { ...this.queryParams, extendMap: undefined },
      toolsBarConfig: {
        size: "small",
        perfect: true,
        slots: {
          buttons: "buttons",
          tools: "tools",
        },
      },
      items: [],
      itemColumn: undefined,
      // 初始化表格配置参数
      tableConfigColumnList: [],
    };
  },
  async created() {
    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;
    }
  },
  // 激活组件
  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() {
      const columns = this.columns;
      for (let col of columns) {
        if (!col.visible) {
          col.visible = true;
        }
        if (!col.fixed) {
          // col.fixed = 'none'
        }
        if (!col.align) {
          col.align = 'left'
        }
        this.tableConfigColumnList.push(col);
      }
      if (this.tableConfig.enable) {
        const params = { tableCode: this.tableCode };
        this.tableConfig.queryConfigUrl({ ...params }).then(res => {
          if (res.code === 200) {
            console.log('-----------', res);
          }
        })
      }
    },
    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.getExtendMapQueryParams();
      if (this.searchMethod) {
        this.searchMethod()
      }
    },
    setTableData(data = []) {
      this.$refs["tableRef"].loadData(data);
    },
    // 搜索添加验证
    validate(callback) {
      this.$refs.queryFormRef.validate(valid => {
        if (callback) callback(valid);
        return false;
      })
    },
    async 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') {
        await this.constantLoad({});
        if (this.initLoadTableData) {
          setTimeout(() => {
            this.loadTableData();
          }, 300)
        }
      } else {
        if (this.initLoadTableData) {
          this.loadTableData();
        }
      }
    },
    resetClick() {
      for (const key in this.queryParams) {
        this.queryParams[key] = undefined
      }
      this.$emit('resetClick')
    },
    /**
     * 初始化加载表格
     */
    async loadTableData() {
      if (!this.requestCall) {
        this.$messageTips.warning("请求地址不存在，请检查配置.");
        return false;
      }
      this.loading = true
      if (typeof this.requestCall === "function") {
        if (this.pagination) {
          this.defaultQueryForm.rows = this.tablePage.pageSize;
          this.defaultQueryForm.page = this.tablePage.currentPage;
        }
        const response = await this.requestCall(this.defaultQueryForm, { loading: !this.partialLoading }).catch(() => {
          this.loading = false;
        });
        if (this.pagination && this.$refs["tableRef"] && response) {
          const { rows, total, extraMap, code } = response;
          if (code === 200) {
            this.tablePage.total = total;
            if (this.resultCallback) {
              const resultCallback = this.resultCallback(rows, extraMap);
              this.$refs["tableRef"].loadData(resultCallback ? resultCallback : rows);
            } else {
              this.$refs["tableRef"].loadData(rows);
            }
            setTimeout(() => {
              this.loading = false;
              delete this.defaultQueryForm.extendMap;
            }, 300);
          } else {
            this.loading = false
            this.$messageTips.error(response.msg);
          }
        }
        else {
          if (this.$refs["tableRef"] && response) {
            const { data, extraMap } = response;
            console.log('--------------', response);
            debugger;
            if (this.resultCallback) {
              const resultCallback = this.resultCallback(data, extraMap);
              this.$refs["tableRef"].loadData(resultCallback ? resultCallback : data);
            } else {
              this.$refs["tableRef"].loadData(data);
            }
          }
          this.loading = false
        }
      } else if (Array.isArray(this.requestCall)) {
        if (this.$refs["tableRef"]) {
          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
      } else if (typeof this.requestCall == "string") {
        if (this.pagination) {
          this.defaultQueryForm.rows = this.tablePage.pageSize;
          this.defaultQueryForm.page = this.tablePage.currentPage;
        }
        const config = { loading: !this.partialLoading };
        const response = await HttpService.page(this.requestCall, { ...this.defaultQueryForm }, config).catch(() => {
          this.loading = false;
        });
        if (this.pagination && this.$refs["tableRef"] && response) {
          const { rows, total, extraMap, code } = response;
          if (code === 200) {
            this.tablePage.total = total;
            if (this.resultCallback) {
              const resultCallback = this.resultCallback(rows, extraMap);
              this.$refs["tableRef"].loadData(resultCallback ? resultCallback : rows);
            } else {
              this.$refs["tableRef"].loadData(rows);
            }
            setTimeout(() => {
              this.loading = false;
              delete this.defaultQueryForm.extendMap;
            }, 300);
          } else {
            this.loading = false
            this.$messageTips.error(response.msg);
          }
        } else {
          if (this.$refs["tableRef"] && response) {
            const { data, extraMap } = response;
            if (this.resultCallback) {
              const resultCallback = this.resultCallback(data, extraMap);
              this.$refs["tableRef"].loadData(resultCallback ? resultCallback : data);
            } else {
              this.$refs["tableRef"].loadData(data);
            }
          }
          setTimeout(() => {
            this.loading = false;
          }, 300);
        }
      }
    },
    /**
     * 获取多条件展开
     */
    getFolding() {
      this.collapse = !this.collapse;
    },
    newInstance() {
      return this.$refs["tableRef"];
    },
    getCheckboxRecords() {
      return this.$refs["tableRef"].getCheckboxRecords();
    },
    reload() {
      this.loadTableData();
    },
    getExtendMapQueryParams() {
      const config = this.extendTemplateConfig;
      if (config && config.enable && this.extendTemplateFieldList.length > 0) {
        const fieldKeyList = [];
        this.extendTemplateFieldList.forEach(row => fieldKeyList.push(row.fieldKey));
        const extendMap = {};
        fieldKeyList.forEach(fieldKey => {
          Object.keys(this.defaultQueryForm).forEach(newFieldKey => {
            if (fieldKey === newFieldKey) {
              extendMap[[ fieldKey ]] = this.defaultQueryForm[fieldKey];
            }
          })
        })
        this.$set(this.defaultQueryForm, 'extendMap', extendMap);
      }
    },
    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) {
      if (this.tableConfig.enable) {
        const params = { tableCode: this.tableCode, tableTitle: this.tableTitle };
        this.tableConfig.saveConfigUrl({ ...params }).then(res => {
          if (res.code === 200) {
            this.$messageTips.success(res.msg);
            this.visibleColumnConfig = false;
            this.$refs['tableRef'].reloadColumn(columns);
          }
        })
      }
    },
    closeModalCallback(visible) {
      this.visibleColumnConfig = visible;
    },
    initResizeTable() {
      const _this = this;
      if (!this.fixedHeight) {
        const h = window.document.body.clientHeight;
        if (h < 800) _this.tableHeight = h - this.marginTop - 2;
        else _this.tableHeight = h - this.marginTop;
      }
    }
  },
  beforeDestroy() {
    document.body.removeEventListener('resize', this.initResizeTable);
    window.removeEventListener('resize', this.initResizeTable);
  },
  async mounted() {
    // 获取扩展字段
    const config = this.extendTemplateConfig;
    if (config && config.enable && config.dataSource && this.columns.length > 0) {
      const newVar = { funCode: config.funCode, operationType: config.operationType };
      const { code, data } = await HttpService.post(config.dataSource, newVar);
      if (code === 200) {
        const columnList = this.columns;
        if (data && data.length > 0) {
          console.log('---------------data： ', data)
          let opts = undefined;
          this.extendTemplateFieldList = data;
          for (let i = 0; i < this.columns.length; i++) {
            if (this.columns.hasOwnProperty(i)) {
              const row = this.columns[i];
              if (row.field === 'opts') {
                opts = row;
                for (let dataKey in data) {
                  if (data.hasOwnProperty(dataKey)) {
                    const row = data[dataKey];
                    columnList.splice(i - 1 + parseInt(dataKey), 1, {
                      ...mixTableConfig.default,
                      title: row.fieldName,
                      field: row.fieldKey,
                      slots: {
                        default: ({ row, column }) => {
                          if (row.extendMap) {
                            return row.extendMap[column.property]
                          } else {
                            return row[column.property];
                          }
                        }
                      }
                    })
                  }
                }
                columnList.push(opts);
                this.$refs.tableRef.reloadColumn(columnList);
                break;
              }
            }
          }
          const fields = this.extendTemplateFieldList;
          for (let index in fields) {
            if (fields.hasOwnProperty(index)) {
              const row = fields[index];
              this.$set(this.defaultQueryForm, row['fieldKey'], undefined);
            }
          }
          console.log(Object.assign(this.defaultQueryForm), '----------------')
        }
      } else {
        // this.$message.error(msg);
        if (this.columns.length) {
          this.$refs.tableRef.reloadColumn(this.columns);
        }
      }
      await this.initColumns();
      await this.initTableData();
    } else {
      if (this.columns.length) {
        this.$refs.tableRef.reloadColumn(this.columns);
      }
      await this.initColumns();
      await this.initTableData();
    }
    document.body.addEventListener('resize', this.initResizeTable, false);
    window.addEventListener('resize', this.initResizeTable, false);
    setTimeout(this.initResizeTable, 1000);
  },
  props: {
    columns: {
      type: Array,
      default: () => {
        return []
      },
    },
    layouts: Array,
    tableConfig: {
      type: Object,
      default: () => {
        return {
          enable: false,  // 是否启用表格配置
          saveConfigUrl: Function, // 保存表格配置信息的地址
          queryConfigUrl: Function, // 查询表格配置信息的地址
        }
      }
    }
  }
};
</script>

<style lang="scss">
.cms-table__custom {
  .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;
    }
  }

  .vxe-tools--wrapper {
    .el-link {
      .el-link--inner {
        padding: 0 !important;
      }
    }
  }
}
</style>
