<template>
  <div id="containt">
    <template v-if="layoutType == 'PC'">
      <x-tabs
        ref="xTabs"
        v-model="activeName"
        class="tab-box"
        :tabNameEnable="true"
      >
        <el-tab-pane :label="$t2('常规')" name="first">
          <vFormRender
            ref="edit"
            :formCode.sync="formCode1"
            :dataId.sync="dataId"
            :param="param"
            :formData="formData"
            v-if="showEdit"
            visible-key="showEdit"
            :visiable.sync="showEdit"
            :parent-target="_self"
            @reload="reload"
            @openCopyEditTab="openCopyEditTab"
          ></vFormRender>
        </el-tab-pane>
        <el-tab-pane
          :label="$t2(formConfig.customListTabLabel || '列表')"
          name="second"
        >
          <div class="grid-height">
            <vFormRender
              ref="list"
              :formCode="formCode"
              :param="param"
              style="height: 100%"
              v-if="showRender"
              visible-key="showRender"
              :visiable.sync="showRender"
              :parent-target="_self"
              @reload="$reloadHandle"
              :openEditDialog="openEditDialog"
            ></vFormRender>
          </div>
        </el-tab-pane>
        <el-tab-pane
          v-for="(item, index) in otherTabList"
          :key="index"
          :label="$t2(item.label)"
          :name="`otherTab${index}`"
        >
          <div class="grid-height">
            <vFormRender
              :ref="`list${index}`"
              :formCode.sync="item.formCode"
              :dataId.sync="item.dataId"
              :param="item.param"
              v-if="item.showContent"
              :parent-target="_self"
              @reload="
                (...args) => {
                  reloadAutoContent(...args);
                }
              "
              :openEditDialog="openEditDialog1"
            ></vFormRender>
          </div>
        </el-tab-pane>
        <template #editTab="{ tab, index, reloadTabContent }">
          <el-tab-pane
            :key="tab.tabName"
            :label="tab.data[tab.tabLabelField]"
            :name="tab.tabName"
            :closable="true"
          >
            <vFormRender
              ref="multiEdit"
              :formCode.sync="tab.formCode"
              :dataId.sync="tab.dataId"
              :param="tab.param"
              v-if="tab.showContent"
              :parent-target="_self"
              @reload="
                (...args) => {
                  formData = {};
                  reloadTabContent(...args);
                }
              "
              @openCopyEditTab="openCopyEditTab"
            ></vFormRender>
          </el-tab-pane>
        </template>
      </x-tabs>
    </template>
    <template v-else-if="layoutType == 'H5'">
      <el-dialog
        :title="$t1('明细详情')"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :visible.sync="showEditDialog"
        :modal="false"
        custom-class="dialog-style h5view-dialog"
        width="100%"
        top="0px"
        v-el-drag-dialog
        v-el-dialog-center
        :destroy-on-close="true"
      >
        <div class="cont" style="height: calc(100vh - 73px)">
          <vFormRender
            :formCode="formCode1"
            :dataId.sync="dataId"
            :param="param"
            v-if="showEditDialog && showEdit"
            visible-key="showEdit"
            :parent-target="_self"
            @reload="$reloadHandle"
          ></vFormRender>
        </div>
      </el-dialog>
      <vFormRender
        :formCode="formCode"
        :param="param"
        style="height: 100%"
        v-if="showRender"
        visible-key="showRender"
        :parent-target="_self"
        @reload="$reloadHandle"
        :openEditDialog="openEditDialog"
      ></vFormRender>
    </template>
  </div>
</template>

<script>
import vFormRender from "../../../../views/user/form/vform/render";

export default {
  name: "form_view:list",
  components: { vFormRender },
  mounted() {},
  data() {
    let that = this;
    return {
      activeName: "second",
      showEdit: false,
      formJson: { formConfig: {} },
      formConfig: {},
      showRender: false,
      formTemplate: null,
      /*      formCode: null,*/
      layoutType: null,
      formCode: null,
      formCode1: null,
      formCode2: null,
      addFormCode: null,
      dataId: null,
      showEditDialog: false,
      param: {},
      multiTabLabelField: null,
      formData: null,
      otherTabList: [],
    };
  },
  watch: {
    activeName(val) {
      if (
        this.formJson.formConfig.otherTabEnabled &&
        this.otherTabList.length > 0 &&
        val.startsWith("otherTab")
      ) {
        let num = Number(val.substring("otherTab".length));
        this.otherTabList[num].showContent = true;
      }
      this.handleTabChange(val);
    },
  },
  created() {
    this.initParam();
    this.getReportTemplate();
  },
  provide() {
    return {
      _self: this,
    };
  },
  methods: {
    handleTabChange(tabName) {
      if (tabName == "second") {
        this.$refs.list.dataTableSearch();
      } else if (tabName.startsWith("otherTab")) {
        let refName = tabName.replace("otherTab", "list");
        if (this.$refs[refName]?.length)
          this.$refs[refName][0].dataTableSearch();
      }
    },
    parseViewParam() {
      let param = {};
      let rawParam = this.$attrs.param ?? this.$route.query.param;
      if (rawParam) {
        if (typeof rawParam === "string") {
          try {
            param = JSON.parse(rawParam) || {};
          } catch (e) {
            param = {};
          }
        } else if (typeof rawParam === "object") {
          param = { ...rawParam };
        }
      }
      return param;
    },
    initParam() {
      let path = this.$route.path;
      let pathSegments = path.split("/").reverse();

      this.formCode = this.$attrs.formCode || pathSegments[0];
      this.param = this.parseViewParam();
      this.showRender = true;
    },
    getReportTemplate() {
      this.$http({
        // aes: true,
        url: USER_PREFIX + `/formTemplate/getByFormCode`,
        method: `post`,
        data: { stringOne: this.formCode },
        // isLoading: true,
        // loadingTarget: document.body,
        // modalStrictly: true,
        success: async (res) => {
          let formTemplate = res.objx || {};
          this.formTemplate = formTemplate;
          let formJson = formTemplate.formViewContent
            ? JSON.parse(formTemplate.formViewContent)
            : {};
          this.formJson = formJson;
          this.formConfig = formJson.formConfig || {};
          this.layoutType = formJson.formConfig?.layoutType;
          let addFormCode = formJson.formConfig?.addFormCode ?? null;
          let formCode2 = formJson.formConfig?.editFormCode ?? null;
          this.formCode2 = formCode2;
          if (!addFormCode) {
            addFormCode = formCode2;
          }
          this.addFormCode = addFormCode;
          this.multiTabLabelField = formJson.formConfig?.multiTabLabelField;
          this.initOtherTabList();
        },
      });
    },
    openOtherTab(row, param, option) {
      let dataId = row && row.id ? row.id : null;
      let formCode = option.formCode;
      let otherTab = this.otherTabList.find(
        (item) => item.formCode == formCode
      );
      let otherTabIndex = this.otherTabList.findIndex(
        (item) => item.formCode == formCode
      );
      this.activeName = `otherTab${otherTabIndex}`;

      otherTab.dataId = dataId;
      otherTab.param = param;
      this.$nextTick(() => {
        otherTab.showContent = false;
        this.$nextTick(() => {
          otherTab.showContent = true;
        });
      });
    },
    openEditDialog(row, param, option) {
      debugger;
      if (option?.otherTab) {
        this.openOtherTab(row, param, option);
        return;
      }
      if (this.layoutType == "H5") {
        this.openEditH5Dialog(row, param);
        return;
      }
      let formConfig = this.formJson.formConfig;
      let tabLabelField =
        option?.multiTabLabelField || formConfig.multiTabLabelField;
      let multiTabEnabled = false;
      if (tabLabelField) {
        if (option?.multiTabEnabled) {
          multiTabEnabled = true;
        } else if (
          formConfig.multiTabEnabled &&
          option?.multiTabEnabled !== false
        ) {
          multiTabEnabled = true;
        }
      }

      let dataId = row && row.id ? row.id : null;
      this.dataId = dataId;
      let formCode = null;
      if (!dataId) {
        formCode = option?.formCode || this.addFormCode;
      } else {
        formCode = option?.formCode || this.formCode2;
      }
      if (multiTabEnabled && dataId) {
        this.$refs.xTabs.openEditTab(row, param, {
          tabParam: {
            formCode,
            tabLabelField,
            tabName: formCode + dataId,
          },
        });
      } else {
        this.formCode1 = formCode;
        this.activeName = option.activeName || "first";
        this.showEdit = false;
        this.showEditDialog = true;
        this.param = param;
        this.formData = null;
        this.$openEditView("showEdit");
      }
    },
    openEditDialog1(row, param, option) {
      this.openEditDialog(row, param, { multiTabEnabled: false, ...option });
    },
    openEditH5Dialog(row, param) {
      debugger;
      this.formCode1 = this.addFormCode;
      this.dataId = row && row.id ? row.id : null;
      this.param = param;
      this.activeName = "first";
      this.showEdit = false;
      this.showEditDialog = true;
      this.$nextTick(() => {
        this.$openEditView("showEdit");
      });
    },

    openCopyEditTab(formData) {
      this.dataId = null;
      this.formCode1 = this.addFormCode;
      this.activeName = "first";
      this.showEdit = false;
      this.showEditDialog = true;
      // this.param = param
      this.formData = formData;
      this.$openEditView("showEdit");
    },
    reload(...args) {
      this.formData = {};
      this.$reloadHandle(...args);
    },
    reload2() {
      this.formData = {};
      this.$reloadHandle(...arguments);
    },
    initOtherTabList() {
      if (!this.formJson.formConfig.otherTabEnabled) return;
      this.otherTabList = this.formJson.formConfig.otherTabList
        .filter((item) => !!item.formCode && !!item.label)
        .map((item) => {
          return {
            label: item.label,
            formCode: item.formCode,
            showContent: false,
            dataId: null,
            param: null,
          };
        });
    },
    reloadAutoContent(target, param, tab) {
      let updateParam =
        param != null && param.updateParam != null ? param.updateParam : {};
      for (let key in updateParam) {
        target.$emit("update:" + key, updateParam[key]);
      }

      if (!tab) {
        let activeName = this.activeName;
        tab = this.tabs.find((item) => item.label == activeName);
      }
      if (tab) {
        tab.showContent = false;
        setTimeout(() => {
          tab.showContent = true;
        }, 200);
      }
    },
  },
};
</script>
