<template>
  <div class="obpm-form">
    <div class="obpm-title">
      <div class="d-inline-block">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane :label="$t('form.basic')" name="basic"></el-tab-pane>
          <el-tab-pane :label="$t('form.format')" name="content"></el-tab-pane>
          <el-tab-pane :label="$t('form.activity')" name="btnAction" v-if="showBtnAction"></el-tab-pane>
          <el-tab-pane :label="$t('form.summary')" name="summary" v-if="showSummary"></el-tab-pane>
          <el-tab-pane :label="$t('form.mapping')" name="mapping" v-if="this.params.type === 65536"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="bar d-inline-block float-right">
        <el-button type="primary" size="small" @click="showMenuDialog" :disabled="showMenuBtn || params.id === ''">{{ $t("btns.create_menu") }}</el-button>
        <el-button type="primary" size="small" @click="resetAllFieldId">{{ $t("btns.reset_field_id") }}</el-button>
        <el-button type="danger" plain size="small" @click="showClearField" :disabled="showMenuBtn">{{ $t("btns.clear_data") }}</el-button>
        <el-button type="primary" size="small" @click="handleGenerateView" :disabled="showMenuBtn">{{ $t("btns.onekey_creview") }}</el-button>
        <el-button type="primary" size="small" @click="openAllScren" v-if="activeName == 'content'">{{ $t("btns.full_screen") }}</el-button>
        <el-button type="primary" size="small" @click="saveBtn" :disabled="saveDisabled"><i class="el-icon-loading" v-if="saveDisabled"></i>{{ $t("btns.save") }}</el-button>
        <el-button size="small" @click="goback" v-if="showLinkBack">{{ $t("btns.exit") }}</el-button>
      </div>
    </div>
    <div>
      <!-- 基本 -->
      <FormBasic ref="formBasic" v-show="activeName == 'basic'" :formId="params.id" :moduleId="params.moduleId" :showType="params.showType" :editForm="editFormType" :isEdit="edit" @updateFormType="updateFormType" />

      <!-- 内容 -->
      <FormFormat ref="formFormat" v-show="activeName == 'content'" :showType="params.showType" :formId="params.id" :moduleId="params.moduleId" />
      <!-- 操作 -->
      <FormOperation v-if="activeName == 'btnAction'" :formId="params.id" />
      <!-- 摘要 -->
      <FormSummary v-if="activeName == 'summary'" :formId="params.id" :moduleId="params.detailData" />

      <!-- 映射 -->
      <FormMapping ref="mapping" v-show="activeName == 'mapping'" :type="params.type" :formId="params.id" :isEdit="edit" />
    </div>

    <div>
      <!-- 创建菜单 -->
      <CreateMenu ref="createMenu" :formId="params.id" type="form" />
      <!-- 清除数据 -->
      <FormCleanData ref="cleanData" :formId="params.id" />
    </div>
    <div v-for="item in tabList" :key="item.formId">
      <el-dialog :visible.sync="item.tabVisible" width="80%" custom-class="subFormHeight" :before-close="changeformVisible(item)" append-to-body>
        <formDetail
          :edit="edit"
          :ref="item.formId"
          v-if="item.tabFormVisible"
          :detailData="item.tabDetailData"
          :visible.sync="item.tabFormVisible"
          :editFormType="true"
          @changeformVisible="changeformVisible(item)"
          :showLinkBack="false"
        />
        <viewDetail :edit="edit" v-if="item.tabViewVisible" :detailData="item.tabDetailData" :visible.sync="item.tabViewVisible" @changeviewVisible="changeformVisible(item)" :showLinkBack="false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { generateView, createForms, updateForm, getModuleForm } from "@/service/FormApi.js"
import { getModuleViewData } from "@/service/ViewApi.js"

import FormMapping from "@/components/modulesDetail/FormMapping"
import FormSummary from "@/components/modulesDetail/FormSummary"
import FormCleanData from "@/components/modulesDetail/FormCleanData"
import FormOperation from "@/components/modulesDetail/FormOperation"
import FormFormat from "@/components/modulesDetail/FormFormat"
import FormBasic from "@/components/modulesDetail/FormBasic"

import CreateMenu from "@/components/CommonTool/createMenu"
import viewDetail from "@/components/Modules/View.vue"

export default {
  name: "page",
  components: {
    viewDetail,
    FormMapping,
    FormSummary,
    CreateMenu,
    FormCleanData,
    FormOperation,
    FormFormat,
    FormBasic,
  },
  props: {
    detailData: Object,
    showLinkBack: {
      // 是否显示有调整链接的按钮
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      activeName: "basic",
      tabList: [], // 选项卡的列表数组

      saveDisabled: false, //保存的状态
      // formDetailRef: null,
      showBtnAction: false, // tab栏 操作显示隐藏
      showSummary: false, // tab栏 操作摘要隐藏
      showMenuBtn: false, // 创建菜单

      params: {},
      edit: false, // 是否为编辑状态
      editFormType: false, // 编辑表单类型
    }
  },
  mounted() {
    this.$store.dispatch("rightHelpPageParams", {
      title: "表单信息",
      url: "application/application_module_form_info_help.html",
    })
    // 监测选项卡
    let that = this
    window["openTabForm"] = (type, formId, moduleId) => {
      console.log("点击了选项卡啊", type, formId, moduleId)
      // 判断列表中有没有当前的数据
      let flag = false
      for (let i = 0; i < that.tabList; i++) {
        if (that.tabList[i].formId == formId) {
          flag = true
          break
        }
      }
      if (!flag) {
        // 将数据添加到选项卡列表中
        that.tabList.push({
          formId: formId,
          tabVisible: false,
          tabFormVisible: false,
          tabViewVisible: false,
          tabDetailData: {},
        })
      }
      // 打开选项卡
      that.openTabFormMethod(type, formId, moduleId)
    }
  },
  created() {
    this.params = this.detailData || this.$route.query.params
    console.log(this.params.id, "id", this.detailData)
    if (this.params.id) {
      this.edit = true
      // this.formDetailRef = this.params.id
    }
  },
  methods: {
    openTabFormMethod(type, formId, moduleId) {
      console.log("tab", type, formId, moduleId)
      // 找到对应的选项卡
      let index = null
      for (let i = 0; i < this.tabList.length; i++) {
        if (this.tabList[i].formId == formId) {
          index = i
          break
        }
      }
      if (index !== null) {
        // 重置选项卡中的弹窗
        this.tabList[index].tabVisible = false
        this.tabList[index].tabFormVisible = false
        this.tabList[index].tabViewVisible = false
        // 获取选项卡中的数组
        if (type == "form" && formId && moduleId) {
          //获取detailData
          getModuleForm(formId, {
            onSucess: (response) => {
              if (response.data.errcode == 0) {
                this.tabList[index].tabVisible = true
                this.tabList[index].tabFormVisible = true
                this.tabList[index].tabViewVisible = false
                Object.assign(this.tabList[index].tabDetailData, this.params, response.data.data, { moduleId: moduleId })
                this.params.id = this.tabDetailData.id
                debugger
                console.log("111", this.tabList[index])
              }
            },
          })
        } else if (type == "view" && formId && moduleId) {
          //获取detailData
          getModuleViewData(formId, {
            onSucess: (response) => {
              if (response.data.errcode == 0) {
                this.tabList[index].tabVisible = true
                this.tabList[index].tabFormVisible = false
                this.tabList[index].tabViewVisible = true
                Object.assign(this.tabList[index].tabDetailData, this.params, response.data.data, { moduleId: moduleId, viewId: formId })
                this.params.id = this.tabDetailData.id
              }
            },
          })
        } else {
          this.$message.error(this.$t("msg.select_tab_view"))
        }
      }
    },

    updateFormType(val) {
      this.$emit("updateDetailData", this.params, val)
    },
    /**
     * 显示菜单
     */
    showMenuDialog() {
      this.$refs["createMenu"].showCreateDialog()
    },

    /**
     * 显示清除数据弹窗
     */
    showClearField() {
      this.$refs["cleanData"].onClearField()
    },

    //vue中的全屏按钮点击事件
    openAllScren() {
      this.$refs["formFormat"].openAllScren()
    },

    /**
     * 切换页签
     */
    handleClick(tab) {
      let id = this.params.id
      //操作列
      if (id != "" && tab.name == "btnAction") {
        this.$store.dispatch("rightHelpPageParams", {
          title: this.$t("msg.form_info"),
          url: "application/application_module_form_info_activity_help.html",
        })
      } else if (id != "" && tab.name == "summary") {
        this.$store.dispatch("rightHelpPageParams", {
          title: this.$t("form.summary"),
          url: "application/application_module_form_reminder_help.html",
        })
      } else if (id != "" && tab.name == "mapping") {
        this.$store.dispatch("rightHelpPageParams", {
          title: this.$t("msg.form_info"),
          url: "application/application_module_form_info_activity_help.html",
        })
      } else if (id != "" && tab.name == "basic") {
        this.$store.dispatch("rightHelpPageParams", {
          title: this.$t("msg.form_message"),
          url: "application/application_module_form_info_help.html",
        })
      } else if (id != "" && tab.name == "content") {
        this.$store.dispatch("rightHelpPageParams", {
          title: this.$t("msg.form_info_senior"),
          url: "application/application_module_form_info_advance_help.html",
        })
      }
    },

    /**
     * 退出
     */
    goback() {
      this.$store.dispatch("rightHelpPageParams", {
        title: this.$t("form.title"),
        url: "application/application_module_form_help.html",
      })
      this.$router.push({ path: "/home/softwaresdetails/pagelist", query: { edit: true, moduleId: this.params.moduleId } })
    },
    changeformVisible(item) {
      // 找到对应的选项然后重置
      let index = ""
      for (let i = 0; i < this.tabList; i++) {
        if (this.tabList[i].formId == item.formId) {
          index = i
          break
        }
      }
      if (index !== "") {
        this.tabList[index].tabVisible = false
        this.tabList[index].tabDetailData = {}
      }
      // this.$refs.formFormat.contentWindow.location.reload(true); // 选项卡退出会重置页面
    },

    /**
     * 一键生成视图
     */
    handleGenerateView() {
      if (this.params.id == "") {
        this.$message({
          type: "info",
          message: this.$t("msg.save_first"),
        })
        return false
      } else {
        generateView(this.params.id, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              this.$message({
                message: this.$t("msg.generate_view"),
                type: "success",
              })
            }
          },
        })
      }
    },

    /**
     *保存表单
     */
    saveBtn() {
      this.saveDisabled = true
      // 先判断有无数据源
      if (!this.$store.state.dataSourceId) {
        this.$message.error(this.$t("msg.set_datasource_first"))
        return false
      }

      // 接收表单基本的数据
      let basicData = this.$refs["formBasic"].save()
      if (basicData == false) {
        this.saveDisabled = false
        return false
      }

      // 接收表单格式的诗句
      let formatData = this.$refs["formFormat"].save()
      if (!formatData) {
        if (formatData === "") {
          this.saveDisabled = false
          this.$message.error(this.$t("msg.content_notnull"))
          return false
        } else if (formatData == false) {
          this.saveDisabled = false
          return false
        }
      }

      basicData.templatecontext = formatData

      let mapFlag = this.$refs["mapping"].verifyMapping()
      if (mapFlag) {
        basicData.mappingStr = mapFlag
      } else {
        basicData.mappingStr = ""
      }

      if (this.params.id) {
        basicData.id = this.params.id
        updateForm(basicData, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              this.$message({
                message: this.$t("msg.ss"),
                type: "success",
              })
            }

            this.saveDisabled = false
          },
        })
      } else {
        createForms(basicData, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              let params = {
                ...basicData,
                id: response.data.data.id,
              }
              this.params = params;
              this.$message({
                message: this.$t("msg.ss"),
                type: "success",
              })
            }

            this.saveDisabled = false
          },
        })
      }
    },

    /**
     * 重置所有字段id
     */
    resetAllFieldId() {
      this.$refs["formFormat"].resetId()
    },
  },

  watch: {
    "params.type": {
      handler() {
        // 操作
        if (this.params.id && this.params.type != 2 && this.params.type != 256) {
          this.showBtnAction = true
        } else {
          this.showBtnAction = false
        }
        // 摘要
        if (this.params.id && this.params.type != 2 && this.params.type != 256 && this.params.type != 1048576) {
          this.showSummary = true
        } else {
          this.showSummary = false
        }
        // 菜单
        if (this.params.type == "2" || this.params.type == "256" || this.params.type == "1048576") {
          this.showMenuBtn = true
        } else {
          this.showMenuBtn = false
        }
      },
      deep: true,
      immediate: true,
    },
    "$store.state.rightHelpPageParams": {
      handler() {
        if (this.$store.state.rightHelpFrame) {
          this.$store.state.rightHelpFrame.contentWindow.showHelpContentHtml(this.$store.state.rightHelpPageParams.title, this.$store.state.rightHelpPageParams.url)
        }
      },
      deep: true,
    },
  },
}
</script>
