<template>
  <container-item-wrapper :widget="widget">
    <div
      :key="widget.id"
      class="table-container"
      v-show="!widget.options.hidden"
    >
      <table
        :ref="widget.id"
        class="table-layout table-d-box"
        :class="[customClass, widget.options.styleTableClass]"
        :style="tableStyle"
      >
        <tbody>
          <tr v-for="(row, rowIdx) in widget.rows" :key="row.id">
            <template v-for="(colWidget, colIdx) in row.cols">
              <table-cell-item
                v-if="!colWidget.merged"
                :widget="colWidget"
                :key="colIdx"
                :parent-list="widget.cols"
                :row-index="rowIdx"
                :col-index="colIdx"
                :parent-widget="widget"
                :parent-target="_self"
                :row.sync="rowData"
              >
                <!-- 递归传递插槽！！！ -->
                <template
                  v-for="slot in Object.keys($scopedSlots)"
                  v-slot:[slot]="scope"
                >
                  <slot :name="slot" v-bind="scope" />
                </template>
              </table-cell-item>
            </template>
          </tr>
        </tbody>
      </table>
    </div>
  </container-item-wrapper>
</template>

<script>
import emitter from "../../../../components/xform/utils/emitter";
import i18n from "../../../../components/xform/utils/i18n";
import refMixin from "../../../../components/xform/form-render/refMixin";
import ContainerItemWrapper from "./container-item-wrapper";
import TableCellItem from "./table2-cell-item";
import containerItemMixin from "./containerItemMixin";
import { generateId } from "../../../../components/xform/utils/util";

export default {
  name: "table2-item",
  componentName: "ContainerItem",
  mixins: [emitter, i18n, refMixin, containerItemMixin],
  components: {
    ContainerItemWrapper,
    TableCellItem,
  },
  props: {
    widget: Object,
  },
  inject: ["refList", "sfRefList", "globalModel"],
  provide: {
    getRows: () => this.rows,
  },
  computed: {
    tableStyle() {
      return this.widget.options.fullWidth ? "width:100%;" : "";
    },
    formModel: {
      cache: !1,
      get: function () {
        return this.globalModel.formModel;
      },
    },
    formDataId() {
      let formRef = this.getFormRef();
      return formRef.dataId;
    },
  },
  created() {
    this.initRefList();
    this.handleOnCreated();
  },
  mounted() {
    this.handleOnMounted();
  },
  beforeDestroy() {
    this.unregisterFromRefList();
  },
  data() {
    return {
      rows: [],
      rowData: {},
      typeMap: {
        0: "input",
        1: "textarea",
        2: "date",
        3: "number",
        4: "text",
        5: "select",
      },
    };
  },
  watch: {},
  methods: {
    getRowData() {
      return this.rowData;
    },
    getValue() {
      return this.rows;
    },
    getType(f_field_type) {
      return this.typeMap[f_field_type];
    },
    setValue(items = []) {
      let dataMap = {};
      let widgetRows = [];
      let currentSpan = 0;
      let index = -1;

      let formRef = this.getFormRef();
      items.forEach((item, rowIndex) => {
        if (item.f_field_value === undefined) {
          item.f_field_value = null;
        }
        let type = this.getType(item.f_field_type);
        let tableCell = this.$baseLodash.cloneDeep(
          formRef.getContainerByType("table-cell")
        );
        tableCell.options.rowIndex = rowIndex;
        let colspan = 1;
        let tc = 0;
        if (type == "textarea") {
          if (currentSpan && currentSpan < 4) {
            tc = 4 - currentSpan;
          }
          colspan = 4;
          tableCell.options.colspan = 4;
        }

        let widget = type
          ? this.$baseLodash.cloneDeep(formRef.getFieldWidgetByType(type))
          : null;
        if (widget) {
          let options = widget.options;
          options.keyNameEnabled = true;
          options.keyName = item.f_key;
          options.label = item.f_field_name;
          options.required = item.f_is_required;
          tableCell.widgetList.push(widget);

          if (type === "select") {
            if (item.f_enum_values) {
              let enumValues = item.f_enum_values
                .split(",")
                .filter((value) => !!value);
              options.optionItems = enumValues.map((value) => ({
                label: value,
                value: value,
              }));
            } else {
              options.optionItems = [];
            }
          }
        }

        if (index === -1) {
          index++;
          widgetRows.push({
            id: "table-row-" + generateId(),
            merged: false,
            cols: [],
          });
          currentSpan = colspan;
        } else if (currentSpan + colspan > 4) {
          index++;
          widgetRows.push({
            id: "table-row-" + generateId(),
            merged: false,
            cols: [],
          });
          currentSpan = colspan;
        } else {
          currentSpan = colspan + currentSpan;
        }

        for (let i = 0; i < tc; i++) {
          widgetRows[index - 1].cols.push(
            this.$baseLodash.cloneDeep(formRef.getContainerByType("table-cell"))
          );
        }

        let cols = widgetRows[index].cols;

        cols.push(tableCell);

        dataMap[item.f_key] = item.f_field_value ?? null;
      });

      this.rows = items;
      this.$set(this.formModel, this.fieldKeyName, items);

      this.rowData = dataMap;
      this.widget.rows.length = 0;
      this.widget.rows.push(...widgetRows);
    },
    loadDataDefaultHandle(flag) {
      // this.init();
      // return
      let dataId = this.formDataId;
      if (flag !== true && !dataId) return;
      let reportTemplate = this.getFormRef().reportTemplate;
      let formCode = reportTemplate.formCode;
      let formScriptEnabled = this.widget.options.formScriptEnabled || false;
      let scriptCode = this.widget.options.formScriptCode;
      if (!scriptCode) return;
      let accessParam = this.handleCustomEvent(
        this.widget.options.formScriptParam
      );
      return this.formHttp({
        scriptCode: scriptCode,
        data: {
          formCode: formCode,
          formVersion: reportTemplate.formVersion,
          taBm: this.fieldKeyName,
          data: {
            id: dataId,
            ...accessParam,
          },
        },
        success: (res) => {
          let rows = res.objx || [];
          this.handleCustomEvent(
            this.widget.options.formScriptSuccess,
            ["res"],
            [res]
          );
          this.setValue(rows);
        },
      });
    },
    init() {
      let items = [
        {
          f_field_name: "a",
          f_key: "a",
          f_field_type: 0,
          f_is_required: true,
          f_field_value: "1",
        },
        {
          f_field_name: "b",
          f_key: "b",
          f_field_type: 3,
          f_is_required: true,
          f_field_value: 2,
        },
        {
          f_field_name: "c",
          f_key: "c",
          f_field_type: 1,
          f_is_required: true,
          f_field_value: "11111",
        },
        {
          f_field_name: "d",
          f_key: "d",
          f_field_type: 0,
          f_is_required: true,
          f_field_value: "3",
        },
        {
          f_field_name: "e",
          f_key: "e",
          f_field_type: 0,
          f_is_required: true,
          f_field_value: "4",
        },
        {
          f_field_name: "f",
          f_key: "f",
          f_field_type: 0,
          f_is_required: true,
          f_field_value: "5",
        },
        {
          f_field_name: "g",
          f_key: "g",
          f_field_type: 0,
          f_is_required: true,
          f_field_value: "6",
        },
        {
          f_field_name: "姓名", //显示名称
          f_key: "name", //字段名
          f_field_type: 4, //类型，0: "文本输入框",1: "多行输入框",2: "日期输入框",3: "数字输入框",4:"纯文本",5: "下拉框"
          f_is_required: false, //是否必填
          f_field_value: "张三", //字段值
          f_enum_values: "张三,李四,王五", //下拉框选项
        },
      ];
      let a = 1;
      this.setValue(items);
    },
  },
};
</script>

<style lang="scss" scoped>
div.table-container {
  table.table-layout {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
  }
}
</style>
