<template>
  <a-spin style="width: 100%; line-height: 300px" :spinning="!aList">
    <div v-if="aList">
      <p-card
        v-for="(item, index) of aList"
        :key="item.key"
        style="margin-bottom: 5px"
        :tab-list="handleFirst(index, item.list)"
        :active-tab-key="item.checkedKey"
        @tabChange="(key) => (item.checkedKey = key)"
      >
        <template v-slot:c1z2x3e4q>
          <p-button type="link" style="margin-right: -40px" @click="handleBack">
            <p-icon type="arrow-left" />
          </p-button>
        </template>
        <template v-slot:tabBarExtraContent>
          <!-- 显隐 content 内容 -->
          <p-button v-if="item.isShowBoxBtn" @click.stop="handleShowBoxBtn(item)"
            >{{ item._box_show ? "隐藏" : "显示" }}
          </p-button>
          <!-- 私自 -->
          <!-- <c-btn
            v-for="(btn, i) of item.list.find((tt) => tt.key === item.checkedKey).btns"
            style="margin-left: 20px"
            :key="i"
            :item="btn"
            v-action:[btn.vaction]
          /> -->
          <template v-for="(btn, i) of item.list.find((tt) => tt.key === item.checkedKey).btns">
            <c-btn v-if="btn.vaction" style="margin-left: 20px" :key="i" :item="btn" v-action:[btn.vaction] />
            <c-btn v-else style="margin-left: 20px" :key="i" :item="btn" />
          </template>
          <!-- 公共 -->
          <template v-for="(btn, i) of item.btns">
            <c-btn v-if="btn.vaction" style="margin-left: 20px" :key="i" :item="btn" v-action:[btn.vaction] />
            <c-btn v-else style="margin-left: 20px" :key="i" :item="btn" />
          </template>
        </template>
        <div v-show="item._box_show">
          <template v-for="subitem of item.list">
            <div
              v-show="item.checkedKey === subitem.key"
              :key="subitem.key"
              :style="{ height: item.height || 'auto' }"
              class="box-main"
            >
              <slot :name="subitem.key"></slot>
              <p-grid-form
                v-if="subitem.item.type === 'p-grid-form'"
                :ref="subitem.key"
                :span="6"
                :items="subitem.item.config"
              />
              <editor-table
                v-if="subitem.item.type === 'p-table-edit'"
                :ref="subitem.key"
                :isView="isView"
                :columns="subitem.item.config"
                :rowKey="subitem.item.rowKey"
                :rowSelectType="subitem.item.rowSelectType || 2"
                :colChange="subitem.item.colChange"
                :colSelect="subitem.item.colSelect"
                :operations="subitem.item.operations || []"
                :onClick="subitem.item.onClick || null"
                :onDblClick="subitem.item.onDblClick || null"
                :onSelectRow="subitem.item.onSelectRow || null"
                :getCheckboxProps="subitem.item.getCheckboxProps || null"
              />
              <p-table
                v-if="subitem.item.type === 'p-table'"
                :ref="subitem.key"
                :columns="subitem.item.config"
                :rowKey="subitem.item.rowKey"
                :rowSelectType="subitem.item.rowSelectType || 2"
                :colChange="subitem.item.colChange"
                :colSelect="subitem.item.colSelect"
                :operations="subitem.item.operations || []"
                :remoteUrl="subitem.item.tableRemoteUrl"
                :remoteBefore="subitem.item.remoteBefore"
                :remoteData="subitem.item.remoteParams"
                :remoteParams="subitem.item.remoteParams"
                :autoLoad="subitem.item.autoLoad"
                :onClick="subitem.item.onClick || null"
                :onDblClick="subitem.item.onDblClick || null"
                :onSelectRow="subitem.item.onSelectRow || null"
              />
              <p-table-sheet
                v-if="subitem.item.type === 'p-table-sheet'"
                :ref="subitem.key"
                :rowKey="subitem.item.rowKey"
                :columns="subitem.item.config"
                :rowSelectType="subitem.item.rowSelectType || 2"
                :hasRowSelectCheck="subitem.item.hasRowSelectCheck"
                :operations="subitem.item.operations || []"
                :dataSource="dataBuffers[subitem.key]"
                @onChange="(p) => (subitem.item.colChange ? subitem.item.colChange(p) : null)"
                @onClick="(p) => (subitem.item.onClick ? subitem.item.onClick(p) : null)"
                @onBlur="(p) => (subitem.item.onBlur ? subitem.item.onBlur(p) : null)"
                @onSelect="(p) => (subitem.item.onSelectRow ? subitem.item.onSelectRow(p) : null)"
              />
              <search-table
                v-if="subitem.item.type === 'p-search-table'"
                :ref="subitem.key"
                :rowSelectType="subitem.item.rowSelectType || 2"
                :searchItems="subitem.item.config.searchItems"
                :tableColumns="subitem.item.config.columns"
                :tableRowKey="subitem.item.rowKey"
                :tableRemoteUrl="subitem.item.remoteUrl"
                :tableRemoteParams="subitem.item.remoteParams"
                :tableOperators="subitem.item.operators"
                :tableAutoLoad="subitem.item.autoLoad"
                :tableDoneBefore="subitem.item.doneBefore"
                :selectChange="subitem.item.selectChange"
                :scroll="subitem.item.scroll"
              />
            </div>
          </template>
        </div>
      </p-card>
    </div>
  </a-spin>
</template>

<script>
import EditorTable from "./editor-table";
import SearchTable from "./search-table";
import CBtn from "./btn";
import { forSelectText } from "../../utils";

export default {
  components: {
    "editor-table": EditorTable,
    "search-table": SearchTable,
    "c-btn": CBtn,
  },

  props: {
    list: {
      type: Array,
      default: null,
    },
    defData: {
      type: Array | Object,
      default: null,
    },
    isView: {
      type: Boolean,
      default: false,
    },
    handleBack: {
      type: Function,
      default: null,
    },
  },
  watch: {
    list: {
      handler(list) {
        if (!list) return;
        this.handleList(list);
      },
      immediate: true,
    },
    defData: {
      handler(data) {
        if (data) {
          if (this.isOk) this.setDetailData(data);
        } else {
          this.resetData();
        }
      },
      // immediate: true
    },
  },

  data() {
    return {
      isOk: false,
      aList: null,
      dataBuffers: {},
    };
  },

  methods: {
    handleList(list) {
      console.log(list, "list");
      let ps = [];
      list.forEach((item) => {
        this.$set(item, "_box_show", true);
        item.list.forEach((config) => {
          if (config.item.type === "p-search-table") {
            ps.push(config.item.config.columns);
            return;
          }
          ps.push(config.item.config);
        });
      });
      forSelectText(ps)
        .then((arr) => {
          let n = 0;
          list.forEach((item) => {
            item.list.forEach((config) => {
              if (config.item.type === "p-search-table") {
                config.item.config.columns = arr[n++];
                return;
              }
              config.item.config = arr[n++];
            });
          });
          this.aList = list;
        })
        .then((res) => {
          this.isOk = true;
          this.$nextTick(() => {
            if (this.defData) this.setDetailData(this.defData);
            this.$emit("ok");
          });
        });
    },

    getDetailData(valid = true, selected = false) {
      let detailData = {};
      let promiseMap = {};
      let isPassed = this.list.every((t) => {
        return t.list.every((tt) => {
          let val = null;
          if (tt.item.type === "p-grid-form") {
            val = this.getFormVals(tt.key, valid);
          } else if (tt.item.type === "p-table-edit") {
            val = this.getEditorTableVals(tt.key, valid, selected);
          } else if (tt.item.type === "p-table") {
            val = [];
          } else if (tt.item.type === "p-table-sheet") {
            let ref = this.$refs[tt.key][0];
            promiseMap[tt.key] = ref
              .getDataSource(selected, valid)
              .then((res) => {
                detailData[tt.key] = res;
                return true;
              })
              .catch((err) => {
                t.checkedKey = tt.key;
                t._box_show = true;
                isPassed = false;
                return false;
              });
            val = [];
          }
          if (val) {
            detailData[tt.key] = val;
            return true;
          } else {
            t.checkedKey = tt.key;
            t._box_show = true;
            return false;
          }
        });
      });
      if (
        this.list.some((t) => {
          return t.list.some((tt) => {
            return tt.item.type === "p-table-sheet";
          });
        })
      ) {
        return Promise.all(Object.values(promiseMap))
          .then((res) => {
            if (!valid) return detailData;
            if (isPassed) return detailData;
            return false;
          })
          .catch((err) => {});
      }
      // if (Object.keys(promiseMap).length > 0){}
      if (!valid) return detailData;
      if (isPassed) return detailData;
      else return false;
    },

    resetData() {
      this.list.forEach((t) => {
        t.list.forEach((tt) => {
          if (tt.item.type === "p-grid-form") {
            this.$refs[tt.key][0].form.resetFields();
          } else if (tt.item.type === "p-table-edit") {
            this.$refs[tt.key][0].data = [];
            this.$refs[tt.key][0].selectedRowKeys = [];
          } else if (tt.item.type === "p-table-sheet") {
            this.$refs[tt.key][0].resetFields();
          }
        });
      });
    },

    setDetailData(data) {
      this.list.forEach((t) => {
        t.list.forEach((tt) => {
          let val = data[tt.key];
          // null
          if (!val && typeof val === "object") {
            val = "";
          }
          if (typeof val === "undefined") {
            val = "";
          }
          this.$nextTick(() => {
            if (tt.item.type === "p-grid-form") {
              this.setFormData(this.$refs[tt.key][0], val);
            } else if (tt.item.type === "p-table-edit") {
              this.setTableEditData(this.$refs[tt.key][0], val);
            } else if (tt.item.type === "p-table-sheet") {
              this.$set(this.dataBuffers, tt.key, val);
              this.$refs[tt.key][0].selectedRowKeys = [];
              this.$refs[tt.key][0].selectedRows = [];
            }
          });
        });
      });
    },

    setFormData(ref, data) {
      if (typeof data != "object" || data === null) return;
      ref.form.setFieldsValue(data);
    },

    setTableEditData(ref, data) {
      ref.setItems(data);
    },

    getFormVals(key, valid) {
      let val = null;
      if (!valid) return this.$refs[key][0].form.getFieldsValue();
      this.$refs[key][0].form.validateFields((errs, vals) => {
        if (errs) {
          return;
        }
        val = vals;
      });
      return val;
    },

    getEditorTableVals(key, valid, selected) {
      let ref = this.$refs[key][0];
      if (!valid) {
        if (selected) {
          return ref.data.filter((t) => {
            return ref.selectedRowKeys.some((k) => k == t[ref.rowKey]);
          });
        } else {
          return ref.data;
        }
      }
      return ref.getListData(selected);
    },

    handleFirst(index, list) {
      if (index > 0) {
        return list;
      }
      if (typeof this.handleBack === "function") {
        return [{ key: "c1z2x3e4q", scopedSlots: { tab: "c1z2x3e4q" } }, ...list];
      }
      return list;
    },

    // 表单的操作
    triggerFormItemVisible(key, isShow, items) {
      if (isShow) {
        this.$refs[key][0].form.unhiddenItem(items);
      } else {
        this.$refs[key][0].form.hiddenItem(items);
      }
    },
    triggerFormItemEnable() {},

    handleShowBoxBtn(item) {
      console.log("handleShowBoxBtn11", item);
      //   item._box_show = !item._box_show;
      item._box_show = item._box_show ? false : true;
      console.log(item._box_show);
    },
  },
};
</script>

<style scoped>
.box-main {
  overflow-y: auto;
}
</style>
