<template>
  <el-container class="fullheight" style="border: 1px solid #eee">
    <ht-aside-tree
      type-key="FORM_TYPE"
      @node-click="handleNodeClick"
      @check="check"
    />
    <el-container>
      <el-main>
        <ht-table
          @load="loadData"
          :data="data"
          :pageResult="pageResult"
          :selection="true"
          quick-search-props="name,alias"
          :show-export="false"
          :default-sorter="[{direction: 'DESC', property: 'create_time_'}]"
          ref="htTable"
          @row-click="rowClick"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:toolbar>
            <!-- <el-button-group> -->
            <el-button
              size="small"
              @click="handleFormSelectOpen"
              icon="el-icon-plus"
              type="primary"
              >添加</el-button
            >
            <el-button
              size="small"
              @click="
                importDialogVisible = true
                flowTypeSelectorCatId = ''
                flowTypeSelectorCatName = ''
              "
              icon="el-icon-back"
              >导入</el-button
            >
            <el-button
              size="small"
              @click="handExport"
              icon="el-icon-right"
              :disabled="isDisabled"
              >导出</el-button
            >
            <el-button
              @click="openTypeSetDialog()"
              icon="icon-shezhifenlei"
              :disabled="isDisabled"
              >设置分类</el-button
            >
            <el-tooltip
              class="item"
              effect="dark"
              content="可批量更新表单至最新模板效果"
              placement="top-start"
            >
              <el-button
                @click="batchSave()"
                icon="icon-pilianggengxin"
                :disabled="isDisabled"
                >批量更新</el-button
              >
            </el-tooltip>
            <ht-delete-button
              :url="formDeleteUrl"
              :htTable="$refs.htTable"
              style="margin-left: 10px"
              :disabled="isDisabled"
              :checkRight="true"
              >删除</ht-delete-button
            >
            <!-- </el-button-group> -->
          </template>
          <template>
            <ht-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            />
            <ht-table-column
              prop="name"
              label="名称"
              :sortable="true"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <el-link
                  @click="edit(scope.row)"
                  v-if="$checkRight(scope.row, '3')"
                  type="primary"
                  >{{ scope.row.name }}</el-link
                >
                <template v-else>{{ scope.row.name }}</template>
              </template>
            </ht-table-column>
            <ht-table-column prop="formName" label="所属表单">
              <template slot-scope="scope">
                <el-link
                  @click="previewForm(scope.row.formKey, 'front')"
                  type="primary"
                  v-if="scope.row.formName"
                >
                  <i class="el-icon-s-platform"></i>
                  {{ scope.row.formName }}</el-link
                >
                <el-divider
                  direction="vertical"
                  v-if="scope.row.mobileFormName && scope.row.formName"
                ></el-divider>
                <el-link
                  @click="previewForm(scope.row.mobileFormAlias, 'mobile')"
                  type="primary"
                  v-if="scope.row.mobileFormAlias"
                >
                  <i class="el-icon-mobile-phone"></i>
                  {{ scope.row.mobileFormName }}</el-link
                >
              </template>
            </ht-table-column>
            <ht-table-column
              prop="alias"
              label="别名"
              :sortable="true"
              width="150"
            />
            <ht-table-column
              prop="boDefAlias"
              label="业务对象别名"
              :sortable="true"
              width="150"
            />
            <ht-table-column prop="typeName" label="分类" width="150" />
            <ht-table-column prop="subject" label="绑定流程名称" />
            <ht-table-column width="210" label="操作">
              <template v-slot="{row}">
                <el-button
                  type="text"
                  @click="handleCommand({row: row, command: 'preview'})"
                  >预览</el-button
                >
                <el-button type="text" @click="copyFormTable(row)"
                  >复制</el-button
                >
                <el-dropdown
                  size="mini"
                  trigger="click"
                  class="more-operate-btn__dropdown"
                  @command="handleCommand"
                >
                  <span class="more-operate-btn"
                    >更多操作<i class="el-icon-caret-bottom"></i>
                  </span>
                  <el-dropdown-menu
                    slot="dropdown"
                    class="operate-dropdown__button"
                  >
                    <el-dropdown-item
                      :command="{row: row, command: 'addToFront'}"
                      >发布为应用端菜单</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{row: row, command: 'addToManager'}"
                      >发布为管理端菜单</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{row: row, command: 'pcModulePublish'}"
                      >发布到PC应用模块</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="row.mobileFormAlias"
                      :command="{row: row, command: 'mobileModulePublish'}"
                      >发布到移动端</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{row, command: 'showBindRelation'}"
                      >绑定关系
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </ht-table-column>
          </template>
        </ht-table>
      </el-main>
    </el-container>

    <el-dialog
      title="导入数据报表"
      :visible.sync="importDialogVisible"
      width="40%"
      top="30vh"
      :close-on-click-modal="false"
      v-if="importDialogVisible"
    >
      <div style="height: 150px; padding-left: 20px">
        <eip-sys-type-selector
          placeholder="请选择分类"
          type-key="FORM_TYPE"
          v-model="flowTypeSelectorCatName"
          :sys-type-id.sync="flowTypeSelectorCatId"
          :validate="{required: true}"
        />
        <br /><br />
        <el-upload
          style="display: inline-block"
          :action="imporCheckUrl"
          :on-success="hadleUploadResult"
          :on-error="hadleUploadResult"
          :headers="uploadHeaders"
          :on-exceed="onExceed"
          accept=".zip"
          :before-upload="beforeUpload"
          :limit="1"
          :data="{isCheck: true}"
          :auto-upload="false"
          ref="upload"
        >
          <el-button size="small" icon="el-icon-upload">选择表单列表</el-button>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitImport"
          element-loading-text="拼命导入中"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 添加数据报表 开始 -->
    <el-dialog
      width="60%"
      title="选择表单"
      :visible="selectFormVisible"
      :before-close="handleFormSelectClose"
      :close-on-click-modal="false"
      custom-class="form_dialog"
    >
      <template>
        <ht-table
          @load="loadFormData"
          :data="formData"
          :pageResult="formPageResult"
          :selectable="false"
          :show-export="false"
          :show-custom-column="false"
          :default-sorter="[{direction: 'DESC', property: 'updateTime'}]"
          quick-search-props="name,alias"
          v-if="selectFormVisible"
        >
          <template>
            <ht-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            />
            <ht-table-column
              prop="name"
              label="名称"
              :show-overflow-tooltip="true"
              :sortable="true"
            >
              <template slot-scope="scope">
                <el-link
                  type="primary"
                  @click="addFormTemplate(scope.row)"
                  title="选择"
                  >{{ scope.row.name }}</el-link
                >
              </template>
            </ht-table-column>
            <ht-table-column prop="formKey" label="表单key" :sortable="true" />
            <ht-table-column prop="version" label="版本" :sortable="true" />
            <ht-table-column prop="typeName" label="分类" :sortable="true" />
          </template>
        </ht-table>
      </template>
    </el-dialog>
    <!-- 添加数据报表 结束 -->

    <!-- 编辑数据报表  开始-->
    <ht-sidebar-dialog
      width="100%"
      :show-close="false"
      :close-on-click-modal="false"
      :visible="datatemplateEditVisible"
      :before-close="handleClose"
      class="dt-edit__dialog"
    >
      <template v-slot:title>
        <div class="flex" style="justify-content: space-between">
          <el-page-header
            @back="
              datatemplateEditVisible = false
              share = {}
              showShareBtn = ''
              activeName = 'baseSetting'
            "
            :content="dataTemplateName"
          ></el-page-header>
          <div
            v-if="currentDataTemplateData.bpmDataTemplate"
            class="left-type_select"
          >
            展示效果：
            <ht-select
              multiple
              style="width: 320px"
              permission="b"
              v-model="currentDataTemplateData.bpmDataTemplate.showType"
              @change="showTypeChange"
              :options="[
                {key: '1', value: '数据列表'},
                {key: '2', value: '甘特图'},
                {key: '3', value: '思维导图'},
                {key: '4', value: '看板'}
              ]"
            />
            <el-button-group>
              <div style="padding-left: 10px">
                <el-button
                  style="border-radius: 4px"
                  v-if="
                    currentDataTemplateData.bpmDataTemplate &&
                      currentDataTemplateData.bpmDataTemplate.id
                  "
                  @click="handleTemplateDataPreview"
                  icon="el-icon-view"
                  >预览</el-button
                >
                <el-button
                  style="border-radius: 4px"
                  v-if="
                    currentDataTemplateData.bpmDataTemplate &&
                      currentDataTemplateData.bpmDataTemplate.id
                  "
                  @click="handleTemplateEdit"
                  icon="el-icon-edit"
                  >编辑模板</el-button
                >
                <!-- <el-button
                  v-if="
                    currentDataTemplateData.bpmDataTemplate &&
                      currentDataTemplateData.bpmDataTemplate.id
                  "
                  icon="el-icon-plus"
                  @click="addModule"
                >
                  创建流程模块
                </el-button> -->
                <el-button
                  style="border-radius: 4px"
                  v-if="
                    currentDataTemplateData.bpmDataTemplate &&
                      currentDataTemplateData.bpmDataTemplate.id
                  "
                  @click="addToMenu('front')"
                  icon="el-icon-plus"
                  >添加到应用端菜单</el-button
                >
                <el-button
                  style="border-radius: 4px"
                  v-if="
                    currentDataTemplateData.bpmDataTemplate &&
                      currentDataTemplateData.bpmDataTemplate.id
                  "
                  @click="addToMenu('manage')"
                  icon="el-icon-plus"
                  >添加到管理端菜单</el-button
                >
                <el-dropdown
                  split-button
                  @command="handleShareCommand"
                  v-if="
                    currentDataTemplateData.bpmDataTemplate &&
                      currentDataTemplateData.bpmDataTemplate.id &&
                      showShareBtn == 1
                  "
                >
                  <i class="el-icon-share">外链</i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-clipboard:copy="share.frontAddUrl"
                      v-clipboard:success="onCopy"
                      v-clipboard:error="onError"
                      >复制地址</el-dropdown-item
                    >
                    <el-dropdown-item :command="{command: 'qr'}"
                      >二维码</el-dropdown-item
                    >
                    <el-dropdown-item :command="{command: 'set'}"
                      >设置有效期</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button
                  style="border-radius: 4px"
                  @click="handleTemplateDataSave"
                  type="primary"
                  icon="el-icon-check"
                  >保存</el-button
                >
              </div>
            </el-button-group>
          </div>
        </div>
      </template>
      <template>
        <el-tabs
          v-if="datatemplateEditVisible && tabsVisible"
          type="card"
          v-model="activeName"
          class="data-form-tabs"
          @tab-click="handlePaneClick"
        >
          <el-tab-pane label="基本信息" name="baseSetting" class="fullheight">
            <BaseSetting
              ref="BaseSetting"
              :focusAlias="focusAlias"
              :showShareBtn.sync="showShareBtn"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>
          <el-tab-pane
            label="关联表"
            name="joinTable"
            class="fullheight"
            v-if="
              currentDataTemplateData.bpmDataTemplate &&
                currentDataTemplateData.bpmDataTemplate.id
            "
          >
            <join-table-setting
              ref="joinTableSetting"
              :ds-name="currentDataTemplateData.bpmDataTemplate.dsName"
              :form-name="currentDataTemplateData.bpmDataTemplate.formName"
              :formAlias="currentPreviewTemplateAlias"
              :join-tables-sql="
                currentDataTemplateData.bpmDataTemplate.joinTablesSql
              "
              :join-tables-str="
                currentDataTemplateData.bpmDataTemplate.joinTables
              "
              :table-name="currentDataTemplateData.tableName"
              :data="currentDataTemplateData"
            />
          </el-tab-pane>

          <el-tab-pane
            label="显示字段"
            name="displaySetting"
            class="fullheight"
            v-if="
              currentDataTemplateData.bpmDataTemplate &&
                currentDataTemplateData.bpmDataTemplate.showType.indexOf('1') >
                  -1
            "
          >
            <DisplaySetting
              ref="DisplaySetting"
              :data.sync="currentDataTemplateData"
              :operateStatus="operateStatus"
              :dataTemplateName="currentDataTemplateData.bpmDataTemplate.name"
            />
          </el-tab-pane>

          <el-tab-pane label="查询字段" name="conditionSetting">
            <span slot="label">
              <el-tooltip content="流程字段不支持查询" placement="top">
                <i class="el-icon-info"></i>
              </el-tooltip>
              查询字段
            </span>
            <ConditionSetting
              ref="ConditionSetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>

          <el-tab-pane label="排序字段" name="sortSetting">
            <span slot="label">
              <el-tooltip content="流程字段不支持排序" placement="top">
                <i class="el-icon-info"></i>
              </el-tooltip>
              排序字段
            </span>
            <SortSetting
              ref="SortSetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>
          <el-tab-pane
            label="字段过滤"
            name="filterFiledSetting"
            v-if="
              currentDataTemplateData.bpmDataTemplate &&
                currentDataTemplateData.bpmDataTemplate.showType.indexOf('1') >
                  -1
            "
          >
            <span slot="label">
              <el-tooltip
                content="日期类型、大文本类型和流程字段不支持筛选"
                placement="top"
              >
                <i class="el-icon-info"></i>
              </el-tooltip>
              字段过滤
            </span>
            <FilterFiledSetting
              ref="FilterFiledSetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>

          <el-tab-pane label="数据过滤" name="filterSetting">
            <FilterSetting
              ref="FilterSetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>

          <el-tab-pane
            label="功能按钮"
            name="manageSetting"
            class="tab-manage-setting"
          >
            <ManageSetting
              ref="ManageSetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>

          <el-tab-pane label="过滤树" name="filterTreeSetting">
            <filter-tree-setting
              ref="FilterTreeSetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>
          <!-- <el-tab-pane label="提醒设置" name="remindSetting">
            <RemindSetting
              ref="RemindSetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane> -->
          <el-tab-pane label="汇总设置" name="SummarySetting">
            <summary-setting
              ref="SummarySetting"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>
          <el-tab-pane label="子表字段" name="subFields">
            <sub-fields ref="subFields" :data.sync="currentDataTemplateData" />
          </el-tab-pane>

          <el-tab-pane
            label="甘特图配置"
            name="ganttConfig"
            class="fullheight"
            v-if="
              currentDataTemplateData.bpmDataTemplate &&
                currentDataTemplateData.bpmDataTemplate.showType.indexOf('2') >
                  -1
            "
          >
            <GanttConfig
              ref="ganttConfig"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>

          <el-tab-pane
            label="思维导图"
            name="xmindConfig"
            class="fullheight"
            v-if="
              currentDataTemplateData.bpmDataTemplate &&
                currentDataTemplateData.bpmDataTemplate.showType.indexOf('3') >
                  -1
            "
          >
            <XmindConfig
              ref="xmindConfig"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>

          <el-tab-pane
            label="看板配置"
            name="kanbanConfig"
            class="fullheight"
            v-if="
              currentDataTemplateData.bpmDataTemplate &&
                currentDataTemplateData.bpmDataTemplate.showType.indexOf('4') >
                  -1
            "
          >
            <kanban-config
              ref="kanbanConfig"
              :data.sync="currentDataTemplateData"
            />
          </el-tab-pane>
        </el-tabs>
      </template>
    </ht-sidebar-dialog>
    <!-- 编辑数据报表  结束-->

    <!-- 数据报表预览 开始 -->
    <ht-sidebar-dialog
      width="100%"
      title="报表预览"
      :visible="previewDialogVisible"
      :before-close="handlePreviewClose"
    >
      <TemplatePreviewDialog
        ref="TemplatePreviewDialog"
        :alias="currentPreviewTemplateAlias"
      />
    </ht-sidebar-dialog>
    <!-- 数据报表预览 结束 -->
    <el-dialog title="选择显示BO表" :visible.sync="boVisible" width="30%">
      <el-form>
        <ht-form-item label="建模主实体">
          <ht-select
            v-model="boId"
            :options="boData"
            :props="{key: 'id', value: 'desc'}"
          />
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="boVisible = false">取消</el-button>
        <el-button
          @click="addFormTemplateByFormKey(selectFormKey, boId)"
          type="primary"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <template-add-to-menu
      ref="templateAddToMenu"
      name="templateAddToMenu"
      :alias="selectAlias"
      append-to-body
    />
    <el-dialog
      :visible.sync="QRCodeDialog"
      width="340px"
      @opened="foundQRCode"
      :center="true"
    >
      <div id="QRCodeAnddDesc" style="text-align: center">
        <canvas id="QRCode" v-show="QRCodeShow"></canvas>
      </div>
      <span slot="footer" v-show="QRCodeShow">
        <el-button
          type="primary"
          v-clipboard:copy="share.mobileAddUrl"
          v-clipboard:success="onCopy"
          v-clipboard:error="onError"
          >复制URL</el-button
        >
        <el-button type="success" @click="downloadQRCode">下载二维码</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="shareLoseTimeDialog" top="20vh" width="400px">
      <div style="text-align: center">
        <el-date-picker
          v-if="shareLoseTimeDialog"
          v-model="share.tempLoseTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="选择截止时间"
        >
        </el-date-picker>
      </div>
      <span slot="footer">
        <el-button @click="shareLoseTimeDialog = false">取消</el-button>
        <el-button type="primary" @click="saveShareLoseTime">确定</el-button>
      </span>
    </el-dialog>

    <PcModulePublish ref="pcModulePublish" />
    <MobileModulePublish ref="mobileModulePublish" />
    <TemplateModuleCreate ref="templateModuleCreate" />

    <BindRelationDialog ref="bindRelationDialog" />
    <mobile-preview-form-dialog
      :formId="formId"
      ref="mobilePreviewForm"
    ></mobile-preview-form-dialog>

    <el-dialog
      :visible.sync="errorDialog"
      title="批量保存错误提示"
      :close-on-click-modal="false"
      @close="
        () => {
          errorDialog = false
          $refs.htTable.load()
        }
      "
    >
      <ht-table
        :data="errorList"
        ref="errorTable"
        :nopagination="true"
        :selectable="false"
        :showExport="false"
        :showCustomColumn="false"
        @load="
          (param, cb) => {
            cb && cb()
          }
        "
      >
        <template>
          <ht-table-column
            type="index"
            width="50"
            align="center"
            label="序号"
          />
          <ht-table-column prop="name" label="名称">
            <template v-slot="{row}">
              {{ row.name + '[' + row.alias + ']' }}
            </template>
          </ht-table-column>
          <ht-table-column
            prop="error"
            label="错误提示"
            :show-overflow-tooltip="true"
            min-width="200"
          >
          </ht-table-column>
        </template>
      </ht-table>
    </el-dialog>
    <el-dialog
      title="复制表单列表"
      :visible.sync="copyFormTableDialogVisible"
      width="30%"
      :before-close="handleCloseCopyFomDialog"
    >
      <el-form v-form="{inputsDisplay: 'block'}" data-vv-scope="formCopyForm">
        <ht-form-item label="原表单名称">
          <span class="form-value">{{ currentRow.name }}</span>
        </ht-form-item>
        <ht-form-item label="原表单别名">
          <span class="form-value">{{ currentRow.alias }}</span>
        </ht-form-item>
        <ht-form-item label="原表单分类">
          <span class="form-value">{{ currentRow.typeName }}</span>
        </ht-form-item>
        <ht-form-item label="新表单名称">
          <ht-input
            v-model="copyForm.newName"
            validate="required"
            show-word-limit
            :maxlength="50"
            placeholder="请输入新表单名称"
          ></ht-input>
        </ht-form-item>
        <ht-form-item label="新表单别名">
          <ht-input
            v-model="copyForm.newAlias"
            v-pinyin="copyForm.newName"
            show-word-limit
            :maxlength="50"
            :validate="{
              required: true,
              regex: {
                exp: '^[a-zA-Z][a-zA-Z0-9_]*$',
                message: '只能输入字母、数字、下划线，且以字母开头'
              },
              isExist: '${form}/form/form/v1/checkKey?key='
            }"
            placeholder="请输入新表单名称"
          ></ht-input>
        </ht-form-item>
        <ht-form-item label="新表单分类">
          <EipSysTypeSelector
            placeholder="请选择分类"
            cat-id="7"
            v-model="copyForm.newTypeName"
            :sys-type-id.sync="copyForm.newTypeId"
            :validate="{required: true}"
          />
        </ht-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseCopyFomDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <eip-sys-type-dialog
      ref="typeSetDialog"
      name="typeSetDialog"
      :cat-id="'7'"
      @onConfirm="sysTypeDialogOnConfirm"
    />
  </el-container>
</template>
<script>
import {toCamel} from '@/utils/index.js'
import form from '@/api/form.js'
import {mapState, mapActions} from 'vuex'
const htAsideTree = () => import('@/components/common/HtAsideTree.vue')
const BaseSetting = () =>
  import('@/components/form/dataTemplate/BaseSetting.vue')
const DisplaySetting = () =>
  import('@/components/form/dataTemplate/DisplaySetting.vue')
const ConditionSetting = () =>
  import('@/components/form/dataTemplate/ConditionSetting.vue')
const SortSetting = () =>
  import('@/components/form/dataTemplate/SortSetting.vue')
const FilterSetting = () =>
  import('@/components/form/dataTemplate/FilterSetting.vue')
const ManageSetting = () =>
  import('@/components/form/dataTemplate/ManageSetting.vue')
const TemplatePreviewDialog = () =>
  import('@/components/form/dataTemplate/TemplatePreviewDialog.vue')
const filterTreeSetting = () =>
  import('@/components/form/dataTemplate/FilterTreeSetting.vue')
const EipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
const FilterFiledSetting = () =>
  import('@/components/form/dataTemplate/FilterFiledSetting.vue')
const RemindSetting = () =>
  import('@/components/form/dataTemplate/RemindSetting.vue')
const SummarySetting = () =>
  import('@/components/form/dataTemplate/SummarySetting.vue')
const SubFields = () => import('@/components/form/dataTemplate/SubFields.vue')
const TemplateAddToMenu = () =>
  import('@/components/form/dataTemplate/TemplateAddToMenu.vue')
const PcModulePublish = () => import('@/components/common/PcModulePublish.vue')
const MobileModulePublish = () =>
  import('@/components/common/MobileModulePublish.vue')
const TemplateModuleCreate = () =>
  import('@/components/common/TemplateModuleCreate.vue')
const JoinTableSetting = () =>
  import('@/components/form/dataTemplate/JoinTableSetting.vue')
const BindRelationDialog = () =>
  import('@/components/form/dataTemplate/BindRelationDialog.vue')
const MobilePreviewFormDialog = () =>
  import('@/components/form/MobilePreviewFormDialog.vue')
import req from '@/request.js'
import QRCode from 'qrcode'
const eipSysTypeDialog = () =>
  import('@/components/dialog/EipSysTypeDialog.vue')
const GanttConfig = () =>
  import('@/components/form/dataTemplate/GanttConfig.vue')
const XmindConfig = () =>
  import('@/components/form/dataTemplate/XmindConfig.vue')
const KanbanConfig = () =>
  import('@/components/form/dataTemplate/KanbanConfig.vue')

import utils from '@/hotent-ui-util.js'

export default {
  components: {
    KanbanConfig,
    MobilePreviewFormDialog,
    htAsideTree,
    BaseSetting,
    DisplaySetting,
    ConditionSetting,
    SortSetting,
    FilterSetting,
    ManageSetting,
    TemplatePreviewDialog,
    filterTreeSetting,
    RemindSetting,
    EipSysTypeSelector,
    FilterFiledSetting,
    SummarySetting,
    SubFields,
    TemplateAddToMenu,
    PcModulePublish,
    MobileModulePublish,
    TemplateModuleCreate,
    JoinTableSetting,
    BindRelationDialog,
    eipSysTypeDialog,
    GanttConfig,
    XmindConfig
  },
  data() {
    return {
      copyFormTableDialogVisible: false,
      uploadHeaders: {
        Authorization: 'Bearer ' + this.$store.state.login.currentUser.token
      },
      asideShow: true,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      data: [],
      selectTypeIds: '',
      fullscreenLoading: false,
      importDialogVisible: false,
      flowTypeSelectorCatId: '', //数据报表分类ID
      flowTypeSelectorCatName: '', //数据报表分类名称
      datatemplateEditVisible: false,
      selectFormVisible: false,
      formEditorDialogVisible: false,
      previewDialogVisible: false,
      templateId: null,
      selectFormKey: null,
      formData: [],
      formPageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      currentDataTemplateData: {},
      activeName: 'baseSetting',
      currentPreviewTemplateAlias: '',
      focusAlias: false,
      boVisible: false,
      boData: [],
      boId: '',
      selectAlias: '',
      QRCodeShow: false,
      QRCodeDialog: false,
      showShareBtn: '',
      tabsVisible: true,
      share: {
        loseTime: '',
        frontAddUrl: '',
        mobileAddUrl: '',
        tempLoseTime: ''
      },
      shareLoseTimeDialog: false,
      errorDialog: false,
      errorList: [],
      formId: null,
      isDisabled: true,
      selectedList: [],
      currentRow: {},
      copyForm: {
        newName: '',
        newAlias: '',
        newTypeId: '',
        newTypeName: ''
      },
      classifyOptions: [],
      operateStatus: ''
    }
  },
  watch: {
  
    showShareBtn: function(newVal, oldVal) {
      this.share.enabled = newVal
      if (newVal == 1 && !this.share.id) {
        this.getShareManage()
      }
    },
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  computed: mapState({
    imporCheckUrl: function(mapState) {
      return (
        window.context.form +
        '/form/dataTemplate/v1/importCheck?typeId=' +
        this.flowTypeSelectorCatId
      )
    },
    frontUrl: function(state) {
      return `${window.context.front}/statement/template/preview/${this.currentPreviewTemplateAlias}/true?token=${state.login.currentUser.token}`
      // window.context.front +
      // '/statement/template/preview/' +
      // this.currentPreviewTemplateAlias +
      // '/true' +
      // '?token=' +
      // state.login.currentUser.token
      // Base64.encode(state.login.currentUser.account)
    },
    formDeleteUrl: function() {
      return `${window.context.form}/form/dataTemplate/v1/remove`
    },
    dataTemplateName: function() {
      return this.currentDataTemplateData.bpmDataTemplate &&
        this.currentDataTemplateData.bpmDataTemplate.name
        ? this.currentDataTemplateData.bpmDataTemplate.name
        : ''
    }
  }),
  mounted() {},
  methods: {
    showTypeChange() {
      let map = {
        ganttConfig: '2',
        kanbanConfig: '4',
        xmindConfig: '3',
        displaySetting: '1'
      }
      let index = map[this.activeName]
      if (
        index &&
        !this.currentDataTemplateData.bpmDataTemplate.showType.includes(index)
      ) {
        this.activeName = 'baseSetting'
      }
    },
    xmindFn() {
      this.$refs.xmind.openShow()
    },
    //设置分类
    openTypeSetDialog() {
      if (this.selectedList.length < 1) {
        this.$message({
          message: '请先选择需要设置分类的数据',
          type: 'warning'
        })
        return
      }
      let ids = this.getHasRightIds(false)
      if (!ids || ids.length == 0) {
        return
      }
      this.$refs.typeSetDialog.showDialog({})
    },
    sysTypeDialogOnConfirm(data) {
      var id = this.getHasRightIds()
      let this_ = this
      this.$http
        .get(
          '${portal}/sys/sysType/v1/updateEntitySysType?typeID=' +
            data.id +
            '&entityIds=' +
            id.join(',')
        )
        .then(function(resp) {
          if (resp.data && resp.data.state) {
            this_.$message({message: resp.data.message, type: 'success'})
            this_.selectedList = []
            setTimeout(function() {
              this_.dialogVisible = false
              this_.$refs.htTable.load()
            }, 100)

            return
          }
          this_.$message.error(resp.data.message)
        })
    },
    copyFormTable(row) {
      this.currentRow = row
      this.copyFormTableDialogVisible = true
      this.copyForm = {
        newName: '',
        newAlias: '',
        newTypeId: '',
        newTypeName: ''
      }
    },
    handleCloseCopyFomDialog() {
      this.copyFormTableDialogVisible = false
    },
    //复制表单按钮确认
    handleSubmit() {
      this.$root.$validator.validateAll('formCopyForm').then(result => {
        if (result) {
          const params = {
            ...this.copyForm,
            id: this.currentRow.id
          }
          form.savaCopyFormTable(params).then(({data}) => {
            if (data.state) {
              this.$message.success(data.message)
              this.copyFormTableDialogVisible = false
              this.$refs.htTable.load()
            }
          })
        }
      })
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    handleShareCommand(params) {
      if (!params) {
        return
      }
      switch (params.command) {
        case 'qr':
          const this_ = this
          if (
            !this.currentDataTemplateData.bpmDataTemplate ||
            !this.currentDataTemplateData.bpmDataTemplate.mobileFormAlias
          ) {
            this_.$message.warning('请先绑定手机表单并保存!')
            return
          } else if (
            this.currentDataTemplateData.bpmDataTemplate ||
            this.currentDataTemplateData.bpmDataTemplate.mobileFormAlias
          ) {
            req
              .get(
                window.context.form +
                  '/form/form/v1/checkKey?key=' +
                  this_.currentDataTemplateData.bpmDataTemplate.mobileFormAlias
              )
              .then(res => {
                if (!res.data) {
                  this_.$message.warning('绑定手机表单的不存在')
                  return
                } else {
                  this_.QRCodeDialog = true
                }
              })
          }
          break
        case 'set':
          this.$set(this.share, 'tempLoseTime', this.share.loseTime)
          this.shareLoseTimeDialog = true
          break
        default:
          break
      }
    },
    downloadQRCode() {
      let canvas = document.getElementById('QRCode')
      let a = document.createElement('a')
      a.download =
        this.currentDataTemplateData.bpmDataTemplate.name + '_二维码.jpg'
      a.href = canvas.toDataURL()
      a.dispatchEvent(new MouseEvent('click'))
    },
    foundQRCode() {
      let msg = document.getElementById('QRCode')
      QRCode.toCanvas(msg, this.share.mobileAddUrl, function(error) {
        console.log(error)
      })
      this.QRCodeShow = true
    },
    onCopy(e) {
      this.$message.success('内容已复制到剪切板！')
    },
    onError(e) {
      this.$message.error('抱歉，复制失败！')
    },
    rowClick(row, column, event) {
      this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
    },
    //导出
    handExport() {
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      let ids = []

      for (let item of elTable.selection) {
        ids.push(item['id'])
      }

      if (ids.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let url = `${window.context.form}/form/dataTemplate/v1/exportXml?ids=${ids}`
      req.download(url)
    },
    submitImport() {
      if (
        !this.$refs.upload.uploadFiles ||
        this.$refs.upload.uploadFiles.length == 0
      ) {
        this.$message.warning('请选择要导入的表单列表')
        return false
      }
      if (!this.flowTypeSelectorCatId) {
        this.$message.warning('请选择要导入的分类')
        return false
      }
      this.$refs.upload.submit()
    },
    hadleUploadResult(response, file, fileList) {
      var height =
        (document.documentElement.clientHeight || document.body.clientHeight) *
          0.85 +
        'px'
      this.fullscreenLoading = false
      let this_ = this
      if (response.state) {
        this_.handleImportSuccess()
      } else {
        if (response.message && response.message.indexOf('是否覆盖') > 0) {
          this.$confirm(
            '<div style="overflow-x:hidden;overflow-y:auto ;max-height:' +
              height +
              '">' +
              response.message +
              '</div>',
            '提示',
            {
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'warning',
              closeOnClickModal: false
            }
          )
            .then(() => {
              this_.fullscreenLoading = true
              req
                .post(
                  window.context.form +
                    '/form/dataTemplate/v1/importSave?cacheFileId=' +
                    response.value +
                    '&confirmImport=' +
                    true +
                    '&typeId=' +
                    this.flowTypeSelectorCatId
                )
                .then(function(resp) {
                  this_.fullscreenLoading = false
                  let data = resp.data
                  if (data.state) {
                    this_.handleImportSuccess(data.message)
                  } else {
                    this_.$message.error(data.message)
                  }
                })
            })
            .catch(action => {
              req.post(
                window.context.form +
                  '/form/dataTemplate/v1/importSave?cacheFileId=' +
                  response.value +
                  '&confirmImport=' +
                  false
              )
              this_.importDialogVisible = false
              this.$refs.upload.clearFiles()
            })
        } else {
          this.$message.error(response.message || '表单列表导入失败')
          //上传失败则清除当前文件，让用户重新选择
          this.$refs.upload.clearFiles()
        }
      }
    },
    handleImportSuccess(msg) {
      this.$alert(
        (msg ? msg + '。' : '') +
          '如果报表对应表单不存在请先导入表单，报表才能正常使用',
        '表单列表导入成功',
        {
          confirmButtonText: '关闭',
          type: 'success'
        }
      ).then(() => {
        this.importDialogVisible = false
        this.$refs.htTable.load()
        this.$refs.upload.clearFiles()
      })
    },
    onExceed(file) {
      this.$message.warning('只能选择一个zip文件!')
    },
    beforeUpload(file) {
      if (!file.name.endsWith('.zip')) {
        this.$message.warning('只能导入zip文件!')
        return false
      }
      this.imporActionUrl = this.imporCheckUrl
      this.fullscreenLoading = true
    },
    handleNodeClick(node) {
      if (node.id == '7') {
        this.selectTypeIds = ''
      } else {
        this.selectTypeIds = node.id
      }
      this.$refs.htTable.load()
    },
    check(data, checkObj) {
      this.selectTypeIds = checkObj.checkedKeys.join(',')
      this.$refs.htTable.load()
    },
    loadData(param, cb) {
      if (this.selectTypeIds) {
        param.querys = param.querys || []
        let hasTypeQuery = false
        for (const query of param.querys) {
          if (query.property == 'typeId') {
            query.value = this.selectTypeIds
            hasTypeQuery = true
            break
          }
        }
        if (!hasTypeQuery) {
          param.querys.push({
            group: 'main',
            operation: 'IN',
            property: 'typeId',
            relation: 'AND',
            value: this.selectTypeIds
          })
        }
      }
      if (!param.sorter) {
        param.sorter = [
          {
            direction: 'DESC',
            property: 'UPDATE_TIME_'
          }
        ]
      } else {
        param.sorter.push({
          direction: 'DESC',
          property: 'UPDATE_TIME_'
        })
      }
      this.$addRightMarkIntoFilter(param)
      form
        .getDataTemplateData(param)
        .then(response => {
          this.data = response.rows

          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb())
    },
    loadFormData(param, cb) {
      form
        .getFormData(param)
        .then(response => {
          this.formData = response.rows

          this.formPageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => cb())
    },
    handleCommand(params) {
      switch (params.command) {
        case 'edit':
          this.templateId = params.row.id
          this.editFormTemplate(this.templateId)
          break
        case 'delete':
          break
        case 'preview':
          this.preview(params.row)
          break
        case 'assignMenu':
          break
        case 'addToFront':
          // 发布为前端菜单
          this.selectAlias = params.row.alias
          this.$refs.templateAddToMenu.showDialog('front', 'addReport')
          break
        case 'addToManager':
          // 发布为管理端菜单
          this.selectAlias = params.row.alias
          this.$refs.templateAddToMenu.showDialog('manage', 'addReport')
          break
        case 'pcModulePublish':
          this.selectAlias = params.row.alias
          console.log(params.row, 'params.row')
          this.handlePcModulePublish(params.row)
          break
        case 'mobileModulePublish':
          this.handleMobileModulePublish(params.row)
          break
        case 'showBindRelation':
          this.showBindRelation(params.row)
          break
        default:
          break
      }
    },
    edit(params) {
      this.templateId = params.id
      this.editFormTemplate(this.templateId, params.boDefId)
    },
    preview(params) {
      this.currentPreviewTemplateAlias = params.alias
      this.handleTemplateDataPreview(params)
    },
    //报表预览
    handleTemplateDataPreview(row) {
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      window.open(
        `${window.context.manage}/templatePreview/${this.currentPreviewTemplateAlias}/${key}`,
        '_blank'
      )
    },
    //编辑报表模板
    handleTemplateEdit() {
      this.$refs.BaseSetting.showHtmlEditDialog()
    },
    //数据报表添加到菜单
    addToMenu(type) {
      this.$refs.BaseSetting.showAddToMenuDialog(type)
    },
    handlePreviewClose() {
      this.previewDialogVisible = false
      this.currentPreviewTemplateId = ''
    },
    handleClose() {
      this.activeName = 'baseSetting'
      this.dialogVisible = false
    },
    handleFormSelectOpen() {
      this.selectFormVisible = true
      this.selectFormKey = null
    },
    handleFormSelectClose() {
      this.selectFormVisible = false
    },
    addFormTemplate(row) {
      this.selectFormKey = row.formKey
      this.boData = []
      form
        .getBODefByFormId(row.defId)
        .then(data => {
          if (data.length > 1) {
            this.boVisible = true
            this.boData = data
          }
        })
        .then(() => {
          if (this.boData.length <= 1) {
            this.addFormTemplateByFormKey(row.formKey, '')
          }
        })
    },
    addFormTemplateByFormKey(formKey, boId) {
      this.selectFormVisible = false
      form.getBpmDataTemplate(formKey, boId).then(response => {
        if (response.status != 1) {
          this.$message.error(response.msg)
          return
        }
        this.formatFields(response.fields)
        this.currentDataTemplateData = {
          ...response,
          bpmDataTemplate: {
            ...response.bpmDataTemplate,
            typeName: '',
            typeId: ''
          }
        }
        this.currentPreviewTemplateAlias = response.data.alias
        this.boVisible = false
        this.datatemplateEditVisible = true
        this.operateStatus = 'add'
        // 获取显示字段中通用下拉选项变量
        this.getCommonVarList()
      })
    },
    editFormTemplate: function(templateId, boId) {
      form.getBpmDataTemplateById(templateId, boId).then(response => {
        if (response.status == 0) {
          setTimeout(() => {
            this.$message.error(response.msg)
          }, 4)
        }
        this.formatFields(response.fields)
        this.currentDataTemplateData = _.cloneDeep(response)
        this.currentPreviewTemplateAlias = response.data.alias
        this.datatemplateEditVisible = true
        this.operateStatus = 'edit'
        //重新执行Setting组件内的mounted，加载初始数据
        this.tabsVisible = false
        this.$nextTick(() => {
          this.tabsVisible = true
        })

        // 获取显示字段中通用下拉选项变量，在BaseSetting.vue中监听dataTemplate.defId已调用方法this.getCommonVarList()获取，这里不在执行
        this.getCommonVarList()
      })
    },
    // 将显示字段中name转成 驼峰
    formatFields(arr) {
      arr.forEach((item, index) => {
        if (index > 0) {
          item.fields.forEach(subItem => {
            let str = item.name + '_' + subItem.name
            subItem.name = toCamel(str.toLowerCase())
          })
        }
      })
    },
    getCommonVarList() {
      let sql = ''
      if (
        this.currentDataTemplateData.bpmDataTemplate.joinTablesSql &&
        this.currentDataTemplateData.bpmDataTemplate.joinTablesSql.trim() !== ''
      ) {
        sql = this.currentDataTemplateData.bpmDataTemplate.joinTablesSql
      } else {
        sql = `select * from ${this.currentDataTemplateData.fields[0].name}`
      }
      let params = {
        sql: sql,
        dsName: this.currentDataTemplateData.bpmDataTemplate.dsName,
        formKey: this.currentDataTemplateData.bpmDataTemplate.formKey,
        instKey: !!this.currentDataTemplateData.bpmDataTemplate.defId
      }
      this.$store.dispatch('form/setFormListCommonVar', params)
    },
    getShareManage: function() {
      if (this.showShareBtn == 1 && !this.share.id) {
        let me_ = this
        this.share.url =
          '/templateForm/' +
          this.currentPreviewTemplateAlias +
          '/add?startFlow=false'

        let share = _.cloneDeep(this.share)
        delete share.frontAddUrl
        delete share.mobileAddUrl
        delete share.tempLoseTime
        this.$http
          .post('${portal}/portal/shorturlManage/v1/getShortUrlByLong', share)
          .then(function(resp) {
            if (resp.data && resp.data.state) {
              resp.data.value.loseTime = resp.data.value.loseTime || ''
              resp.data.value.frontAddUrl =
                window.context.front + '/' + resp.data.value.shortUrl
              resp.data.value.mobileAddUrl =
                window.context.mobile + '/' + resp.data.value.shortUrl
              me_.share = resp.data.value
            } else {
              me_.$message.error('获取表单外链短链接失败：' + resp.data.message)
            }
          })
      }
    },
    saveShareLoseTime() {
      let me_ = this
      this.share.loseTime = this.share.tempLoseTime

      let share = _.cloneDeep(this.share)
      delete share.tempLoseTime
      delete share.frontAddUrl
      delete share.mobileAddUrl

      this.$http
        .post('${portal}/portal/shorturlManage/v1/updateShorturlManage', share)
        .then(function(resp) {
          if (resp.data && resp.data.state) {
            me_.$message.success('设置成功')
            me_.shareLoseTimeDialog = false
          }
        })
    },
    handlePaneClick: function(data) {
      if (data.name == 'manageSetting') {
        this.currentDataTemplateData.displaySettingFields = JSON.stringify(
          this.$refs.DisplaySetting.displayFields
        )
      }
      if (data.alias) {
        this.currentTabComponent = data.alias
      }
      if (data.name == 'defConfig') {
        this.flowConfigShouldRefresh = false
      }
    },
    //保存数据视图
    handleTemplateDataSave: function() {
      let this_ = this
      this.$refs.BaseSetting.validateForm(function() {
        this_.saveTemolate()
      })
    },
    async saveTemolate() {
      if (this.$refs.DisplaySetting) {
        this.$refs.DisplaySetting.saveDisplayField() //保存显示列数据
        if (!this.$refs.DisplaySetting.validateTree) {
          this.$message.error(`显示字段不能为空！`)
          return false
        }
        if (!this.$refs.DisplaySetting.validateDisplayField()) {
          return
        }
      }

      let result = this.$refs.ConditionSetting.saveConditionField() //保存查询条件数据
      if ('false' == result) {
        return
      }
      if (!this.$refs.FilterTreeSetting.validateFilterTree()) {
        return
      }
      this.$refs.SortSetting.saveSortField() //保存排序数据
      this.$refs.subFields.saveSubField() //保存子表数据
      if (!this.$refs.ManageSetting.validateManageField()) {
        return
      }
      //保存甘特图配置
      if (this.$refs.ganttConfig && !this.$refs.ganttConfig.saveGanttConfig()) {
        return
      }
      //保存看板配置
      if (this.$refs.kanbanConfig && !this.$refs.kanbanConfig.saveConfig()) {
        return
      }

      //保存思维导图配置
      if (this.$refs.xmindConfig && !this.$refs.xmindConfig.saveXmindConfig()) {
        return
      }

      this.$refs.FilterSetting.saveFilterField() //保存按钮数据
      this.$refs.ManageSetting.saveManageField() //保存按钮数据
      if (this.$refs.FilterFiledSetting) {
        this.$refs.FilterFiledSetting.saveFilteringField()
      } else {
        this.currentDataTemplateData.bpmDataTemplate.filteringField = JSON.stringify(
          []
        )
      }

      this.$refs.FilterTreeSetting.saveFilterTreeField()
      this.$refs.SummarySetting.saveSummaryField()
      let templateData = JSON.parse(
        JSON.stringify(this.currentDataTemplateData.bpmDataTemplate)
      )
      //校验关联表、获取关联表数据
      if (this.currentDataTemplateData.bpmDataTemplate.id) {
        let {
          joinTables,
          isCheckSql
        } = this.$refs.joinTableSetting.getSubmitData()
        if ('false' === joinTables) {
          return
        }
        const joinTableSql = this.$refs.joinTableSetting.getCurrentSql()
        const defaultSql = `select * from ${this.currentDataTemplateData.fields[0].name}`
        // 旧的关联表sql数据
        const oldJoinTableSql = templateData.joinTablesSql || ''
        // 如果关联表发生改变，保存是添加提示信息
        if (
          (joinTables != templateData.joinTables &&
            !(joinTables == '[]' && !templateData.joinTables)) ||
          joinTableSql.replace(/[\r\n]/g, '').replace(/\ +/g, '') !=
            oldJoinTableSql.replace(/[\r\n]/g, '').replace(/\ +/g, '')
        ) {
          let isConfirm = await this.confirmSqlSave()
          if (!isConfirm) {
            return
          }
        }
        templateData.joinTables = joinTables
        templateData.joinTablesSql = utils.isEmpty(joinTableSql.trim())
          ? defaultSql
          : joinTableSql
        if (joinTables && !isCheckSql) {
          this.$message.warning('请先验证SQL')
          localStorage.setItem(this.currentPreviewTemplateAlias, false)
          return
        }
      } else {
        templateData.joinTablesSql = `select * from ${this.currentDataTemplateData.fields[0].name}`
      }

      let sortArr = JSON.parse(templateData.sortField)
      for (let s = 0; s < sortArr.length; s++) {
        if (!sortArr[s].sort) {
          this.$message({type: 'error', message: '请选择排序方式'})
          return false
        }
      }
      if (!templateData.alias) {
        this.$message.error('报表别名不能为空，请输入报表别名！')
        return
      }
      if (!templateData.name) {
        this.$message.error('报表名称不能为空，请输入报表名称！')
        return
      }
      if (templateData.resetTemp == 1 && !templateData.templateAlias) {
        this.$message.error('请选择数据模板！')
        return
      }
      //判断是否添加模糊查询
      let isIndistinct = 'hide'
      let conditionAllName = ''
      let conditionAllDesc = ''
      let conditionFields = this.$refs.ConditionSetting.conditionFields
      if (this.currentDataTemplateData.displaySettingFields) {
        let formField = JSON.parse(
          this.currentDataTemplateData.displaySettingFields
        ).filter(item => {
          return item.isFlowField != true
        })
        templateData.formField = JSON.stringify(formField)
      }

      for (var i = 0; i < conditionFields.length; i++) {
        if (conditionFields[i].mg) {
          isIndistinct = 'show'
          conditionAllName += conditionFields[i].na.replace('F_', '') + ','
          conditionAllDesc += conditionFields[i].cm + '/'
        }
      }
      if (conditionAllName != '') {
        conditionAllName = conditionAllName.substring(
          0,
          conditionAllName.length - 1
        )
      }
      if (conditionAllDesc != '') {
        conditionAllDesc = conditionAllDesc.substring(
          0,
          conditionAllDesc.length - 1
        )
      }
      templateData.isIndistinct = isIndistinct
      templateData.conditionAllName = conditionAllName
      templateData.conditionAllDesc = conditionAllDesc
      const sortList = JSON.parse(templateData.sortField)
      templateData.mobileDisplayField = JSON.stringify(
        this.getMobileDisplayField(templateData, sortList)
      )
      delete templateData.mobileListTitle
      delete templateData.mobileShowStatus
      if (
        this.$refs.DisplaySetting &&
        this.getMobileDisplayField(templateData, sortList).length &&
        !this.$refs.DisplaySetting.mobileListTitle
      ) {
        return this.$message.warning('请设置标题')
      }
      templateData.mobileOtherJson = JSON.stringify(
        [this.getTitleAndStatusMapByKey(templateData,'isTitle'),
        this.getTitleAndStatusMapByKey(templateData,'isStatus')
      ]
        )
      //添加表单字段
      if (this.currentDataTemplateData.formField) {
        templateData.formField = JSON.stringify(
          this.currentDataTemplateData.formField
        )
      }
      //移动端顶部按钮
      const allButtons = JSON.parse(templateData.manageField)
      if (allButtons && allButtons.length) {
        const addBtn = allButtons.filter(item => item.name === 'add')
        const mobileTopButtons = allButtons.filter(
          item =>
            item.mpDisplay == '1' && item.topPosition && item.name !== 'add'
        )
        templateData.mobileManageField = JSON.stringify([
          ...mobileTopButtons,
          ...addBtn
        ])
      } else {
        templateData.mobileManageField = JSON.stringify([])
      }
      if (this.share.id) {
        
        let share = _.cloneDeep(this.share)
         
      delete share.frontAddUrl
      delete share.mobileAddUrl
        this.$http.post(
          '${portal}/portal/shorturlManage/v1/updateShorturlManage',
        share
        )
      }
      let _this = this
      this.$refs.SummarySetting.getValidateSummaryResult()
        .then(() => {
          let templateHtml = templateData.templateHtml 
          templateData.templateHtml = ''
          let mobileTemplateHtml =  templateData.mobileTemplateHtml
          templateData.mobileTemplateHtml = ''
          form.saveTemplateData(JSON.stringify(templateData)).then(response => {
            templateData.templateHtml = templateHtml
            templateData.mobileTemplateHtml = mobileTemplateHtml
            if (response.state) {
              this.$message.success(response.message)
              this.edit(response.value)
              if (!templateData.id) {
                _this.$refs.htTable.load(true)
              }
              this.focusAlias = false
            } else {
              this.focusAlias = true
            }
          })
        })
        .catch(err => {
          this.$message.warning('汇总设置有必填项未填写')
          return
        })
    },
    getTitleAndStatusMapByKey(templateData,key) {
      const displayFieldList =
        templateData.displayField && JSON.parse(templateData.displayField)
      return utils.nest2tile(displayFieldList).find((item) => item[key]) || {}
    },
    getMobileDisplayField(templateData, sortList) {
      const displayFieldList =
        templateData.displayField && JSON.parse(templateData.displayField)
      const sortMap = sortList.reduce((pre, cur) => {
        const newName = `${cur.tableName}${cur.oldTableField}`
          .toLowerCase()
          .replaceAll('_', '')
        pre[newName] = cur
        return pre
      }, {})

      const mobileData = utils.nest2tile(displayFieldList).filter(item => {
        if (item.mpDisplay === '1') {
          this.$set(item, 'sortField', sortMap[item.name])
          this.$set(
            item,
            'isTitle',
            item.name === templateData.mobileListTitle ? true : false
          )
          this.$set(
            item,
            'isStatus',
            item.name === templateData.mobileShowStatus ? true : false
          )
        }
        return item.mpDisplay === '1' && !item.isTitle && !item.isStatus
      })
      return mobileData || []
    },
    async confirmSqlSave() {
      return new Promise(resolve => {
        this.$confirm(
          '关联表已经发生变化，关联表相关配置失效将会引起报错，是否确定继续保存？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(() => {
            resolve(true)
          })
          .catch(() => {
            resolve(false)
          })
      })
    },
    //表单预览
    previewForm(formKey, type) {
      let token = this.$store.state.login.currentUser.token
      this.$http
        .get(
          `${window.context.form}/form/form/v1/getMainByAlias?alias=${formKey}`
        )
        .then(resp => {
          if (resp && resp.data) {
            let formId = resp.data.id
            if (type === 'mobile') {
              this.formId = formId
              window.open(
                window.context.manage +
                  `/formPreview/${this.formId}?mobile=true`,
                '_blank'
              )
            } else {
              window.open(
                window.context.manage +
                  `/formPreview/${formId}?mobile=${
                    type === 'mobile' ? true : false
                  }`,
                'blank'
              )
            }
          }
        })
    },
    //发布到PC应用端模块
    handlePcModulePublish(row) {
      if (row.status === 'draft') {
        this.$message.warning('请先发布表单')
        return
      }
      let data = {
        id: row.id,
        name: row.name,
        key: row.alias,
        alias: row.alias
      }
      this.$refs.pcModulePublish.showDialog(JSON.stringify(data), 2)
    },
    handleMobileModulePublish(row) {
      let {alias, name} = row
      let data = {
        alias,
        name
      }
      this.$refs.mobileModulePublish.showDialog(JSON.stringify(data), 3)
    },
    addModule() {
      this.$refs.templateModuleCreate.showDialog(
        this.currentDataTemplateData.bpmDataTemplate
      )
    },
    batchSave() {
      let elTable = this.$refs.htTable
      if (this.$refs.htTable.$refs && this.$refs.htTable.$refs.htTable) {
        elTable = this.$refs.htTable.$refs.htTable
      }
      if (elTable && elTable.selection && elTable.selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }

      let ids1 = this.getHasRightIds(false)
      if (!ids1 || ids1.length == 0) {
        return
      }

      this.$confirm('将重新保存选中的表单列表，确定继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: '正在批量保存表单列表。。。',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          let ids = this.getHasRightIds()
          if (!ids || ids.length == 0) {
            return
          }
          this.$http
            .post(`${window.context.form}/form/dataTemplate/v1/batchSave`, {
              ids: ids
            })
            .then(resp => {
              if (resp.data && resp.data.state) {
                if (typeof resp.data.value === 'string') {
                  this.$message.success(resp.data.value)
                  this.$refs.htTable.load()
                } else {
                  this.errorList = resp.data.value
                  this.errorDialog = true
                  setTimeout(() => {
                    this.$message.warning(
                      '部分表单列表保存失败，详情请查看列表。'
                    )
                  }, 800)
                }
              }
            })
            .finally(() => {
              loading.close()
            })
        })
        .catch(() => {})
    },
    showBindRelation(row) {
      this.$refs['bindRelationDialog'].showDialog(row)
    },
    getHasRightIds(alertMessage = true, right = '3') {
      let selection = this.$refs.htTable.$refs.htTable.selection
      if (selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let ids = []
      let notRightNames = []
      for (let item of selection) {
        if (this.$checkRight(item, right)) {
          ids.push(item['id'])
        } else {
          notRightNames.push(item.name)
        }
      }
      if (notRightNames.length > 0) {
        if (alertMessage || notRightNames.length == selection.length) {
          this.$message.error(
            '以下数据无权限' +
              (right == '3' ? '更新' : '删除') +
              ',已跳过：[' +
              notRightNames.join(',') +
              ']'
          )
        }

        if (notRightNames.length == selection.length) {
          return null
        }
      }
      return ids
    }
  }
}
</script>

<style lang="scss" scoped>
.data-form-tabs {
  ::v-deep {
    .el-tabs__header {
      border-color: #ebebeb;
    }

    .el-tabs__header .el-tabs__nav {
      border-radius: 2px 2px 0 0;
      border-color: #ebebeb;
      background-color: #f6f6f6;
    }

    .el-tabs__item {
      color: #666;
      border-bottom: 1px solid #ebebeb;
    }
  }
}

.form-editor-dialog >>> .el-dialog__header {
  display: none;
}

.form-editor-dialog >>> .el-dialog__body {
  padding: 0;
  height: 100%;
}

.dt-edit__dialog {
  ::v-deep {
    .el-dialog__body {
      padding: 32px;
      height: calc(100% - 100px);

      .el-tabs--card {
        padding: 0;
        height: calc(100% - 32px);
      }

      .el-tabs__content {
        height: calc(100% - 70px);
        overflow-y: auto;

        // 隐藏滚动条
        &::-webkit-scrollbar {
          width: 0;
          background-color: transparent;
        }
      }
    }
  }
}

@media (max-width: 1280px) {
  /deep/ .search-container__col {
    flex-wrap: wrap;

    .el-button-group {
      margin-top: 10px;
    }
  }
}

/deep/.el-dialog__wrapper {
  overflow: unset !important;
}

/deep/.form_dialog .el-dialog__body {
  padding: 10px;
  height: calc(100% - 100px);
  // overflow-y: auto;
}

/deep/.form_dialog .el-dialog {
  height: 90%;
  min-height: 400px;
  margin-top: 6vh !important;
}

/deep/.form_dialog .el-dialog__body .selector-table {
  height: 100% !important;
}

/deep/.form_dialog .el-dialog .el-dialog__body .select-tree-div {
  height: calc(100% - 60px);
  min-height: unset;
}

@media (max-height: 960px) {
  /deep/.form_dialog .el-dialog__body .el-container {
    height: 100% !important;
  }
}

.tab-manage-setting {
  height: 100%;
}

::v-deep {
  .custom-set {
    position: relative;
  }

  .dropdown-wrap {
    z-index: 2;
    display: block;
    position: absolute;
    min-width: 108px;
    top: 60px;
    padding: 8px 0;
    background: #fff;
    box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.15);

    .dropdown-item {
      height: 32px;
      line-height: 32px;
      color: #333333;
      padding-left: 16px;

      &:hover {
        background: #f8f8f8;
        color: #409eff;
      }
    }
  }

  .custom-set:hover + .dropdown-wrap {
    display: block;
  }
}

::v-deep .inputs.ht-form-inputs__inline {
  position: relative;
}

.left-type_select {
  float: left;
  margin-right: 10px;
}
</style>
<style lang="scss">
.el-tooltip__popper {
  max-width: 50%;
}

#tab-joinTable {
  padding-left: 20px !important;
}
</style>
