<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>
    <el-dialog width="90%" :fullscreen="true" :title="$t('新建表单')" :visible.sync="openNewFormFlag"  :destroy-on-close='true' v-if="openNewFormFlag">
        <div class="obpm-form">
          <div class="obpm-title">
           <div class="d-inline-block">
        <el-tabs v-model="activeName1" @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.mapping')" name="mapping" v-if="this.params1.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="showMenuBtn1 || params1.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="showMenuBtn1">{{ $t("btns.clear_data") }}</el-button>
        <el-button type="primary" size="small" @click="handleGenerateView" :disabled="showMenuBtn1">{{ $t("btns.onekey_creview") }}</el-button>
        <el-button type="primary" size="small" @click="saveBtn" :disabled="saveDisabled1"><i class="el-icon-loading" v-if="saveDisabled1"></i>{{ $t("btns.save") }}</el-button>
        <el-button size="small" @click="goback">{{ $t("btns.exit") }}</el-button>
      </div>
    </div>
    </div>
     <FormBasic ref="formBasic1" v-show="activeName1 == 'basic'" :formId="params1.id" :moduleId="params1.moduleId" :showType="params1.showType" :editForm="editFormType" :isEdit="edit" @updateFormType="updateFormType" />
      <FormFormat ref="formFormat1" v-show="activeName1 == 'content'" :showType="params1.showType" :formId="params1.id" :moduleId="params1.moduleId" />
      <FormMapping ref="mapping1" v-show="activeName1 == 'mapping'" :type="params1.type" :formId="params1.id" :isEdit="edit" />
      </el-dialog>
  </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: "formDetail",
  components: {
    viewDetail,
    FormMapping,
    FormSummary,
    CreateMenu,
    FormCleanData,
    FormOperation,
    FormFormat,
    FormBasic,
  },
  props: {
    detailData: Object,
    showLinkBack: {
      // 是否显示有调整链接的按钮
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      activeName: "basic",
      activeName1:"basic",
      tabList: [], // 选项卡的列表数组

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

      params: {},
      params1:{},
      edit: false, // 是否为编辑状态
      editFormType: false, // 编辑表单类型
      openNewFormFlag: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)
    }
    window['openNewForm']=(flag)=>{
      that.params1={
        appId: that.params.appId,
        checkout: false,
        id: "",
        inited: false,
        layoutType: "",
        mappingStr: "",
        moduleId: that.params.moduleId,
        name: "",
        openComment: false,
        orderno: 1,
        permissionType: "",
        showLog: false,
        showType: "new",
        showWaterMark: false,
        type: 1,
        typeName: "",
        version: 3,
        waterMarkScript: ""
      }
      that.openNewFormFlag=true
    }
  },
  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) {
      if(this.openNewFormFlag){
        this.params1.type=val
      this.$emit("updateDetailData", this.params1, val)
      }
      else {this.params.type=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.openNewFormFlag?this.params.id:this.params1.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() {
      if(this.openNewFormFlag){this.openNewFormFlag=false}
      else {
      this.$store.dispatch("rightHelpPageParams", {
        title: this.$t("form.title"),
        url: "application/application_module_form_help.html",
      })
      this.$router.push({ path: "/home/softwaresdetails/formlist", 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() {
      let id=!this.openNewFormFlag?this.params.id:this.params1.id
      if (this.params.id == ""&&this.openNewFormFlag==false||this.params1.id==""&&this.openNewFormFlag==true) {
        this.$message({
          type: "info",
          message: this.$t("msg.save_first"),
        })
        return false
      } else {
        generateView(id, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              this.$message({
                message: this.$t("msg.generate_view"),
                type: "success",
              })
            }
          },
        })
      }
    },

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

      // 接收表单基本的数据
      let basicData;
      if(this.openNewFormFlag) basicData=this.$refs["formBasic1"].save()
      else basicData=this.$refs["formBasic"].save()
      if(this.openNewFormFlag){
        basicData.appId=this.params1.appId;
        basicData.moduleId=this.params1.moduleId;
        basicData.showType='new'
      }
      if (basicData == false) {
        if(this.openNewFormFlag) this.saveDisabled1=false
        else this.saveDisabled = false
        return false
      }

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

      basicData.templatecontext = formatData
      let mapFlag = !this.openNewFormFlag?this.$refs["mapping"].verifyMapping():this.$refs["mapping1"].verifyMapping()
      if (mapFlag) {
        basicData.mappingStr = mapFlag
      } else {
        basicData.mappingStr = ""
      }
      if (this.params.id&&this.openNewFormFlag==false||this.params1.id&&this.openNewFormFlag==true) {
        basicData.id = !this.openNewFormFlag?this.params.id:this.params1.id
        updateForm(basicData, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              this.$message({
                message: this.$t("msg.ss"),
                type: "success",
              })
            }
            if(this.openNewFormFlag) this.saveDisabled1=false
            else this.saveDisabled = false
          },
        })
      } else {
        createForms(basicData, {
          onSucess: (response) => {
            if (response.data.errcode == 0) {
              let params = {
                ...basicData,
                id: response.data.data.id,
              }
              if(this.openNewFormFlag) this.params1=params
              else this.params = params;
              this.$message({
                message: this.$t("msg.ss"),
                type: "success",
              })
            }
            if(this.openNewFormFlag) this.saveDisabled1=false
            else this.saveDisabled = false
          },
        })
      }
    },

    /**
     * 重置所有字段id
     */
    resetAllFieldId() {
      if(this.openNewFormFlag) this.$refs["formFormat1"].resetId()
      else 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,
    },
    "params1.type":{
      handler() {
        if (this.params1.type == "2" || this.params1.type == "256" || this.params1.type == "1048576") {
           this.showMenuBtn1 = true
        } else {
          this.showMenuBtn1 = 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>
