<template>
  <div class="columnDesign-container">
    <div class="main-board flex">
      <!--      <div class="left" style="width: 20%; padding: 0 15px; margin-right: 5px; border-right: 1px solid #dcdfe6">-->
      <!--        <h4 class="cap flex flex-center">-->
      <!--          场景-->
      <!--          <el-button size="mini" icon="el-icon-plus" @click="addScenes">添加场景</el-button>-->
      <!--        </h4>-->
      <!--        <el-divider style="margin: 5px"></el-divider>-->
      <!--        <div><el-button type="info" style="width: 100%" plain @click="selectScenes(columnData.masterScenes)">默认场景</el-button></div>-->
      <!--        <div v-for="item in columnData.scenes">-->
      <!--          <el-button @click="selectScenes(item)" style="width: 100%; margin-top: 10px" plain>-->
      <!--            <div class="flex flex-between">-->
      <!--              <div>-->
      <!--                {{ item.name }}-->
      <!--                <el-popover placement="right" width="200" trigger="click">-->
      <!--                  <el-input v-model="item.name"></el-input>-->
      <!--                  <span slot="reference" type="text"><i class="el-icon-edit"></i></span>-->
      <!--                </el-popover>-->
      <!--              </div>-->

      <!--              <div class="flex gap-10">-->
      <!--                <span>编辑</span>-->
      <!--                <span>删除</span>-->
      <!--              </div>-->
      <!--            </div>-->
      <!--          </el-button>-->
      <!--        </div>-->
      <!--      </div>-->
      <div class="right" style="flex: 1">
        <div class="search-box">
          <h4 class="cap">查询条件</h4>
          <ColumnFilter @onAddSearchChange="SearchFilterChange" ref="ColumnFilter" v-if="setSeachFlag"></ColumnFilter>
          <vxe-table border size="small" :row-config="{ useKey: true }" :scroll-y="{ enabled: false }" :data="columnData.searchList" class="JNPF-common-table" ref="dragTableSearch">
            <vxe-column width="60">
              <template #default>
                <span class="drag-btn">
                  <div class="drag-handler icon-ym" style="cursor: move; font-size: 20px; width: 20px" title="点击拖动">
                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20" viewBox="0 0 20 20" fill="none">
                      <rect x="0" y="0" width="20" height="20" fill="#FFFFFF" fill-opacity="0"></rect>
                      <path
                        d="M8.31335 5.27703C8.31335 6.02222 7.70924 6.62633 6.96405 6.62633C6.21886 6.62633 5.61475 6.02222 5.61475 5.27703C5.61475 4.53184 6.21886 3.92773 6.96405 3.92773C7.70924 3.92773 8.31335 4.53184 8.31335 5.27703ZM6.96405 11.3489C7.70924 11.3489 8.31335 10.7448 8.31335 9.99958C8.31335 9.2544 7.70924 8.65028 6.96405 8.65028C6.21886 8.65028 5.61475 9.2544 5.61475 9.99958C5.61475 10.7448 6.21886 11.3489 6.96405 11.3489ZM6.96405 16.0714C7.70924 16.0714 8.31335 15.4673 8.31335 14.7221C8.31335 13.9769 7.70924 13.3728 6.96405 13.3728C6.21886 13.3728 5.61475 13.9769 5.61475 14.7221C5.61475 15.4673 6.21886 16.0714 6.96405 16.0714Z"
                        fill-rule="evenodd"
                        fill="#333333"
                      ></path>
                      <path
                        d="M14.3851 5.27703C14.3851 6.02222 13.781 6.62633 13.0358 6.62633C12.2906 6.62633 11.6865 6.02222 11.6865 5.27703C11.6865 4.53184 12.2906 3.92773 13.0358 3.92773C13.781 3.92773 14.3851 4.53184 14.3851 5.27703ZM13.0358 11.3489C13.781 11.3489 14.3851 10.7448 14.3851 9.99958C14.3851 9.2544 13.781 8.65028 13.0358 8.65028C12.2906 8.65028 11.6865 9.2544 11.6865 9.99958C11.6865 10.7448 12.2906 11.3489 13.0358 11.3489ZM13.0358 16.0714C13.781 16.0714 14.3851 15.4673 14.3851 14.7221C14.3851 13.9769 13.781 13.3728 13.0358 13.3728C12.2906 13.3728 11.6865 13.9769 11.6865 14.7221C11.6865 15.4673 12.2906 16.0714 13.0358 16.0714Z"
                        fill-rule="evenodd"
                        fill="#333333"
                      ></path>
                    </svg>
                  </div>
                </span>
              </template>
              <template #header>
                <el-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
                  <div @click="showHelpTip1 = !showHelpTip1">拖拽</div>
                </el-tooltip>
              </template>
            </vxe-column>
            <vxe-column field="__config__.label" title="列名" />
            <vxe-column field="__vModelName__" title="字段" />
            <vxe-column field="searchType" title="类型">
              <template slot-scope="scope">
                <!--              {{scope.row.searchType===3?'范围查询':scope.row.searchType===2?'模糊查询':'等于查询'}}-->
                <el-button @click="setSeachClick(scope.row)" plain size="mini"> 搜索设置 </el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <el-divider></el-divider>
        <div class="column-box">
          <h4 class="cap">列表字段</h4>
          <vxe-table
            border
            size="small"
            ref="xTable1"
            :row-config="{ useKey: true }"
            :tree-config="{ children: 'children' }"
            :scroll-y="{ enabled: false }"
            :data="columnData.columnList"
            :row-style="rowStyle"
          >
            <vxe-column width="60" title="拖拽">
              <template #default>
                <span class="drag-btn">
                  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="20" height="20" viewBox="0 0 20 20" fill="none">
                    <rect x="0" y="0" width="20" height="20" fill="#FFFFFF" fill-opacity="0"></rect>
                    <path
                      d="M8.31335 5.27703C8.31335 6.02222 7.70924 6.62633 6.96405 6.62633C6.21886 6.62633 5.61475 6.02222 5.61475 5.27703C5.61475 4.53184 6.21886 3.92773 6.96405 3.92773C7.70924 3.92773 8.31335 4.53184 8.31335 5.27703ZM6.96405 11.3489C7.70924 11.3489 8.31335 10.7448 8.31335 9.99958C8.31335 9.2544 7.70924 8.65028 6.96405 8.65028C6.21886 8.65028 5.61475 9.2544 5.61475 9.99958C5.61475 10.7448 6.21886 11.3489 6.96405 11.3489ZM6.96405 16.0714C7.70924 16.0714 8.31335 15.4673 8.31335 14.7221C8.31335 13.9769 7.70924 13.3728 6.96405 13.3728C6.21886 13.3728 5.61475 13.9769 5.61475 14.7221C5.61475 15.4673 6.21886 16.0714 6.96405 16.0714Z"
                      fill-rule="evenodd"
                      fill="#333333"
                    ></path>
                    <path
                      d="M14.3851 5.27703C14.3851 6.02222 13.781 6.62633 13.0358 6.62633C12.2906 6.62633 11.6865 6.02222 11.6865 5.27703C11.6865 4.53184 12.2906 3.92773 13.0358 3.92773C13.781 3.92773 14.3851 4.53184 14.3851 5.27703ZM13.0358 11.3489C13.781 11.3489 14.3851 10.7448 14.3851 9.99958C14.3851 9.2544 13.781 8.65028 13.0358 8.65028C12.2906 8.65028 11.6865 9.2544 11.6865 9.99958C11.6865 10.7448 12.2906 11.3489 13.0358 11.3489ZM13.0358 16.0714C13.781 16.0714 14.3851 15.4673 14.3851 14.7221C14.3851 13.9769 13.781 13.3728 13.0358 13.3728C12.2906 13.3728 11.6865 13.9769 11.6865 14.7221C11.6865 15.4673 12.2906 16.0714 13.0358 16.0714Z"
                      fill-rule="evenodd"
                      fill="#333333"
                    ></path>
                  </svg>
                </span>
              </template>
              <template #header>
                <el-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
                  <div @click="showHelpTip1 = !showHelpTip1">拖拽</div>
                </el-tooltip>
              </template>
            </vxe-column>
            <vxe-column field="label" title="列名" tree-node />
            <vxe-column field="prop" title="字段" />
            <vxe-column field="visible" title="显示" width="90">
              <template #header> <el-checkbox v-model="visibleCheck" size="mini"></el-checkbox>显示</template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.visible" />
              </template>
            </vxe-column>
            <vxe-column field="sortable" title="排序" width="90">
              <template #header> <el-checkbox v-model="sortCheck" size="mini"></el-checkbox>排序</template>
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.sortable" />
              </template>
            </vxe-column>
            <vxe-column field="showSummary" title="合计" width="60">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.showSummary" />
              </template>
            </vxe-column>
            <vxe-column field="align" title="对齐">
              <template slot-scope="scope">
                <el-select v-model="scope.row.align" placeholder="请选择">
                  <el-option v-for="item in alignOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
              </template>
            </vxe-column>
            <vxe-column field="width" title="宽度" width="100">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.width" placeholder="宽度" :min="0" :precision="0" controls-position="right" style="width: 100%" />
              </template>
            </vxe-column>
            <!--          <vxe-column field="width" title="关联表单">-->
            <!--            <template slot-scope="{ row, rowIndex }">-->
            <!--              <el-input :value="row.config.associatedFrom ? row.config.associatedFrom.fullName : ''" @focus="focusEvent(row, rowIndex)" suffix-icon="vxe-icon-flow-branch" placeholder="请选择"> </el-input>-->
            <!--            </template>-->
            <!--          </vxe-column>-->
          </vxe-table>
        </div>
        <el-scrollbar class="right-board">
          <el-tabs v-model="currentTab" class="top-tabs">
            <el-tab-pane label="查询字段" name="search" />
            <!--        <el-tab-pane label="列表字段" name="field" />-->
            <el-tab-pane label="列表属性" name="column" />
          </el-tabs>
          <div class="field-box">
            <div class="searchList" v-show="currentTab === 'search'">
              <el-table :data="searchOptions" class="JNPF-common-table" @selection-change="searchSelectionChange" ref="searchTable">
                <el-table-column prop="__config__.label" label="查询条件" />
                <el-table-column type="selection" width="55" align="center" />
              </el-table>
            </div>
            <div class="columnList" v-show="currentTab === 'field'">
              <el-table :data="columnOptions" class="JNPF-common-table" @selection-change="columnSelectionChange" ref="columnTable">
                <el-table-column prop="label" label="列表字段" />
                <el-table-column type="selection" width="55" align="center" />
              </el-table>
            </div>
            <div class="setting-box" v-show="currentTab === 'column'">
              <el-form :model="columnData" label-width="100px" size="mini">
                <el-divider>列表布局</el-divider>
                <div class="typeList">
                  <div class="item" v-for="(item, index) in typeList" :key="index" @click="columnData.type = item.value">
                    <div class="item-img" :class="{ checked: columnData.type == item.value }">
                      <img :src="item.url" alt="" />
                      <div class="icon-checked" v-if="columnData.type == item.value">
                        <i class="el-icon-check"></i>
                      </div>
                    </div>
                    <p class="item-name">{{ item.name }}</p>
                  </div>
                </div>
                <template v-if="columnData.type == 2">
                  <el-divider
                    >左侧设置
                    <el-button size="mini" type="text" @click="addTab"> 增加 </el-button>
                  </el-divider>
                  <el-tabs v-model="treeListIndex" closable @tab-remove="removeTab" @tab-click="tabClick">
                    <el-tab-pane v-for="item in columnData.treeList" :key="item.name" :label="item.treeTitle" :name="item.name">
                      <el-form-item label="左侧标题">
                        <el-input v-model="item.treeTitle" placeholder="树形标题"></el-input>
                      </el-form-item>
                      <el-form-item label="数据来源">
                        <el-radio-group v-model="item.treeDataSource">
                          <el-radio label="dictionary">数据字典</el-radio>
                          <el-radio label="api">api接口</el-radio>
                          <!--                  <el-radio label="organize">公司数据</el-radio>-->
                          <!--                  <el-radio label="department">部门数据</el-radio>-->
                        </el-radio-group>
                      </el-form-item>
                      <template v-if="item.treeDataSource === 'dictionary'">
                        <el-form-item label="数据字典">
                          <DicSelect v-model="item.treeDictionary" placeholder="请选择数据字典" />
                        </el-form-item>
                      </template>
                      <template v-if="item.treeDataSource === 'api'">
                        <el-form-item label="数据接口">
                          <div style="display: flex; gap: 5px">
                            <el-cascader
                              :options="dataInterfaceSelector"
                              v-model="item.treePropsUrl"
                              placeholder="请选择API数据"
                              :props="{ expandTrigger: 'hover', emitPath: false }"
                              :show-all-levels="false"
                              clearable
                              filterable
                              @change="propsUrlChange"
                            >
                            </el-cascader>
                            <el-button v-if="item.treePropsUrl" @click="(preview.isShow = !preview.isShow), treePreview()">预览</el-button>
                          </div>
                        </el-form-item>
                        <template v-if="item.treePropsUrl">
                          <el-form-item label="主键字段">
                            <el-select v-model="item.treePropsValue" placeholder="请选择" filterable>
                              <el-option v-for="item in preview.fields" :key="item.columnName" :label="item.columnName" :value="item.columnName"> </el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="显示字段">
                            <el-select v-model="item.treePropsLabel" placeholder="请选择" filterable>
                              <el-option v-for="item in preview.fields" :key="item.columnName" :label="item.columnName" :value="item.columnName"> </el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="父级字段">
                            <el-select v-model="item.treePropsChildren" placeholder="请选择" filterable>
                              <el-option v-for="item in preview.fields" :key="item.columnName" :label="item.columnName" :value="item.columnName"> </el-option>
                            </el-select>
                            <div style="font-size: 12px">这里如果不选择不会生成树形数据结构</div>
                          </el-form-item>
                          <!--                      <el-form-item label="是否能多选">-->
                          <!--                        <el-switch v-model="item.showCheckbox" />-->
                          <!--                      </el-form-item>-->
                        </template>
                      </template>
                      <el-form-item label="查询字段">
                        <div style="display: flex; gap: 5px">
                          <el-select filterable v-model="item.treeSearch" placeholder="请选择查询字段" style="width: 60%">
                            <el-option v-for="item in preview.fields" :key="item.columnName" :label="item.columnName" :value="item.columnName"> </el-option>
                          </el-select>
                          <el-select style="flex: 1" filterable v-model="item.treeSearchType" placeholder="查询类型">
                            <el-option label="模糊查询" value="like"></el-option>
                            <el-option label="精确查询" value="eq"></el-option>
                            <el-option label="范围查询" value="in"></el-option>
                          </el-select>
                        </div>
                      </el-form-item>
                      <el-form-item label="表单查询字段">
                        <el-select filterable v-model="item.treeRelation" placeholder="请选择关联字段">
                          <el-option :label="item.title" :value="item.propId" v-for="(item, index) in columnData.columnList" :key="index"> {{ item.title }} {{ item.field }} </el-option>
                        </el-select>
                        <div style="font-size: 12px">sql类似：{{ item.treeSearch }} {{ item.treeSearchType }} {{ item.treeRelation }}</div>
                      </el-form-item>
                    </el-tab-pane>
                  </el-tabs>
                </template>
                <template v-if="columnData.type == 3">
                  <el-divider>分组设置</el-divider>
                  <el-form-item label="分组字段">
                    <el-select v-model="columnData.groupField" placeholder="请选择分组字段">
                      <el-option :label="item.__config__.label" :value="item.__vModel__" v-for="(item, i) in list" :key="i"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
                <el-divider>排序设置</el-divider>
                <el-form-item label="排序字段">
                  <el-select v-model="columnData.defaultSidx" placeholder="请选择排序字段">
                    <el-option :label="item.__config__.label" :value="item.__vModel__" v-for="(item, i) in list" :key="i"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="排序类型">
                  <el-select v-model="columnData.sort" placeholder="请选择排序类型">
                    <el-option label="升序" value="ascs"></el-option>
                    <el-option label="降序" value="descs"></el-option>
                  </el-select>
                </el-form-item>
                <template v-if="columnData.type !== 3">
                  <el-divider>基础设置</el-divider>
                  <el-form-item label="列表合计">
                    <el-switch v-model="columnData.showSummary"></el-switch>
                  </el-form-item>
                  <!--                  <el-form-item label="开启行内编辑">-->
                  <!--                    <el-switch v-model="columnData.editable"></el-switch>-->
                  <!--                  </el-form-item>-->
                  <el-divider>分页设置</el-divider>
                  <el-form-item label="列表分页">
                    <el-switch v-model="columnData.hasPage"></el-switch>
                  </el-form-item>
                  <el-form-item label="分页条数">
                    <el-radio-group v-model="columnData.pageSize">
                      <el-radio-button :label="20">20条</el-radio-button>
                      <el-radio-button :label="50">50条</el-radio-button>
                      <el-radio-button :label="100">100条</el-radio-button>
                      <el-radio-button :label="500">500条</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </template>
                <!--            <el-divider>按钮配置</el-divider>-->
                <!--            <el-checkbox-group v-model="btnsList" class="btnsList">-->
                <!--              <el-checkbox :label="item.value" v-for="item in btnsOption" :key="item.value">-->
                <!--                <span class="btn-label">{{ item.value | btnText }}</span>-->
                <!--                <el-input v-model="item.label" />-->
                <!--              </el-checkbox>-->
                <!--            </el-checkbox-group>-->
                <!--            <el-checkbox-group v-model="columnBtnsList" class="btnsList columnBtnList">-->
                <!--              <el-checkbox :label="item.value" v-for="item in columnBtnsOption" :key="item.value">-->
                <!--                <span class="btn-label">{{ item.value | btnText }}</span>-->
                <!--                <el-input v-model="item.label" />-->
                <!--              </el-checkbox>-->
                <!--            </el-checkbox-group>-->
                <!--            <el-divider>权限设置</el-divider>-->
                <!--            <el-form-item label="按钮权限">-->
                <!--              <el-button-->
                <!--                v-if="conf.dbLinkId"-->
                <!--                @click="changeShowFilter('Btns')"-->
                <!--                plain-->
                <!--                size="mini"-->
                <!--                >操作设置</el-button-->
                <!--              >-->
                <!--              &lt;!&ndash;              <el-switch v-model="columnData.useBtnPermission"></el-switch>&ndash;&gt;-->
                <!--            </el-form-item>-->
                <!--            &lt;!&ndash;            <el-form-item label="列表权限">&ndash;&gt;-->
                <!--            &lt;!&ndash;              <el-button v-if="conf.dbLinkId" plain size="mini">操作设置</el-button>&ndash;&gt;-->
                <!--            &lt;!&ndash;&lt;!&ndash;                            <el-switch v-model="columnData.useColumnPermission"></el-switch>&ndash;&gt;&ndash;&gt;-->
                <!--            &lt;!&ndash;            </el-form-item>&ndash;&gt;-->
                <!--            <el-form-item label="数据权限">-->
                <!--              <el-button-->
                <!--                v-if="conf.dbLinkId"-->
                <!--                @click="changeShowFilter('data')"-->
                <!--                plain-->
                <!--                size="mini"-->
                <!--                >操作设置</el-button-->
                <!--              >-->
                <!--              &lt;!&ndash;                            <el-switch v-model="columnData.useDataPermission"></el-switch>&ndash;&gt;-->
                <!--            </el-form-item>-->
              </el-form>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <vxe-modal v-model="visualLink.isDiglog" width="70%" height="60%">
      <web-design @getSelect="getSelect"></web-design>
    </vxe-modal>
    <!-- 权限过滤器 -->
    <datasetFilter
      ref="datasetFilter"
      :showFalg="showFalg"
      :modelId="conf.modelId"
      :fields="conf.cubeList"
      :cubeId="conf.dbLinkId"
      :btns="btnsOption"
      :columnBtns="columnBtnsOption"
      v-model="showDatasetFilter"
      @Btnchanged="BtnFilter"
    ></datasetFilter>
    <vxe-modal v-model="preview.isShow" width="60%" :mask="false" :lock-view="false" title="预览数据" resize destroy-on-close height="80%">
      <div style="display: flex; height: 100%; overflow: hidden; justify-content: space-between">
        <div style="width: 40%">
          <div>字段</div>
          <JsonEditor key="field" v-model="preview.fieldsJson" class="json-editor" />
        </div>
        <div style="width: 60%">
          <div>数据</div>
          <JsonEditor key="data" v-model="preview.data" class="json-editor" style="overflow: auto" />
        </div>
      </div>
    </vxe-modal>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import { getDrawingList } from '@/components/Generator/utils/db'
import { noColumnShowList, noSearchList, useDateList, useInputList } from '@/components/Generator/generator/comConfig'
import { dataapiDetail } from '@/api/systemData/dataInterface'
import { globalFunctions } from '@/components/Dataset-filter/dict'
import WebDesign from '@/views/webDesign/index.vue'
import { getAPIList } from '@/components/Dataset-filter/util'
import { openurl } from '@/components/Dataset-filter/report'
import Dataset from '@/views/dataset/edit.vue'
import JsonEditor from '@/components/JsonEditor/index.vue'
import AmisSdk from '@/components/AmisSdk.vue'

const getSearchType = (item) => {
  const jnpfKey = item.__config__.jnpfKey
  // 等于-1  模糊-2  范围-3
  const fuzzyList = [...useInputList]
  const RangeList = [...useDateList, 'time', 'date', 'numInput', 'calculate']
  if (RangeList.includes(jnpfKey)) return 3
  if (fuzzyList.includes(jnpfKey)) return 2
  return 1
}

const defaultColumnData = {
  searchList: [], // 查询条件
  columnList: [], // 字段列表
  type: 1, //列表类型
  defaultSidx: '', // 默认排序字段
  sort: 'descs', // 排序类型
  hasPage: true, // 列表分页
  pageSize: 20, // 分页条数
  showSummary: false, // 开启合计
  masterScenes: {},
  scenes: [],
  treeList: [
    {
      name: '1',
      treeTitle: '左侧标题', // 树形标题
      treeDataSource: 'api', // 树形数据来源
      treeDictionary: '', //数据字典
      treeRelation: '', // 关联字段
      treePropsUrl: '', // 数据选择
      treePropsValue: '', // 主键字段
      treePropsChildren: '', // 子级字段
      treePropsLabel: '', // 显示字段
      treeSearch: '', // 查询字段
      treeSearchType: 1 // 查询类型
    }
  ],
  treeTitle: '左侧标题', // 树形标题
  treeDataSource: 'api', // 树形数据来源
  treeDictionary: '', //数据字典
  treeRelation: '', // 关联字段
  treePropsUrl: '', // 数据选择
  treePropsValue: 'id', // 主键字段
  treePropsChildren: 'children', // 子级字段
  treePropsLabel: 'fullName', // 显示字段
  groupField: '', // 分组字段
  useColumnPermission: false,
  useBtnPermission: false,
  useDataPermission: false,
  btnsList: [{ value: 'add', icon: 'el-icon-plus', label: '新增' }], // 按钮
  columnBtnsList: [
    { value: 'edit', icon: 'el-icon-edit', label: '编辑' },
    { value: 'remove', icon: 'el-icon-delete', label: '删除' }
  ] // 列按钮
}
export default {
  name: 'columnDesign',
  components: { AmisSdk, WebDesign, Dataset, JsonEditor },
  props: {
    conf: {
      type: Object,
      default: () => {}
    },
    modelType: {
      type: Number
    }
  },
  data() {
    return {
      treeListIndex: '1',
      globalFunctions,
      currentTab: 'column',
      alignOptions: [
        {
          value: 'left',
          label: '左对齐'
        },
        {
          value: 'center',
          label: '居中'
        },
        {
          value: 'right',
          label: '右对齐'
        }
      ],
      list: [],
      searchList: [],
      columnList: [],
      columnData: JSON.parse(JSON.stringify(defaultColumnData)),
      btnsOption: [
        { value: 'add', icon: 'el-icon-plus', label: '新增', flowId: '' },
        {
          value: 'download',
          icon: 'el-icon-download',
          label: '导出',
          flowId: ''
        },
        {
          value: 'batchUpload',
          icon: 'el-icon-upload2',
          label: '批量导入',
          flowId: ''
        },
        // {
        //   value: 'batchUpdate',
        //   icon: 'el-icon-edit-outline',
        //   label: '批量编辑',
        //   flowId: ''
        // },
        {
          value: 'batchRemove',
          icon: 'el-icon-delete',
          label: '批量删除',
          flowId: ''
        },
        // {
        //   value: 'journal',
        //   icon: 'el-icon-date',
        //   label: '操作日志',
        //   flowId: ''
        // },
        {
          value: 'recycle',
          icon: 'el-icon-delete',
          label: '回收站',
          flowId: ''
        }
        // {
        //   value: 'uploadRevoke',
        //   icon: 'el-icon-refresh-left',
        //   label: '导入撤销',
        //   flowId: ''
        // }
        // {
        //   value: 'comDelete',
        //   icon: 'el-icon-delete',
        //   label: '彻底删除',
        //   flowId: ''
        // }
      ],
      columnBtnsOption: [
        { value: 'edit', icon: 'el-icon-edit', label: '编辑', flowId: '' },
        { value: 'remove', icon: 'el-icon-delete', label: '删除', flowId: '' },
        { value: 'detail', icon: 'el-icon-tickets', label: '详情', flowId: '' }
        // {
        //   value: 'rowJournal',
        //   icon: 'el-icon-date',
        //   label: '操作记录',
        //   flowId: ''
        // }
      ],
      columnOptions: [],
      searchOptions: [],
      btnsList: [],
      columnBtnsList: [],
      showFalg: 'Btns',
      typeList: [
        {
          url: require('@/assets/images/generator/columnType1.png'),
          value: 1,
          name: '普通表格'
        },
        {
          url: require('@/assets/images/generator/columnType2.png'),
          value: 2,
          name: '左侧树形+普通表格'
        }
        // { url: require('@/assets/images/generator/columnType3.png'), value: 4, name: '快捷录入+普通表格' },
      ],
      dataInterfaceSelector: [],
      showDatasetFilter: false,
      setSeachFlag: false,

      showHelpTip1: false,

      visualLink: {
        isDiglog: false,
        loading: false,
        tableData: [],
        columns: [
          {
            field: 'fullName',
            title: '名称'
          },
          {
            field: 'id',
            title: '表单ID'
          }
        ],
        pagerConfig: {
          total: 0,
          currentPage: 1,
          pageSize: 10
        }
      },

      // 数据预览
      preview: {
        isShow: false,
        fields: [],
        fieldsJson: [],
        data: []
      },

      visibleCheck: false,
      sortCheck: false
    }
  },
  filters: {
    btnText(key) {
      let text = ''
      switch (key) {
        case 'download':
          text = '导出'
          break
        case 'batchRemove':
          text = '批量删除'
          break
        case 'edit':
          text = '编辑'
          break
        case 'remove':
          text = '删除'
          break
        case 'detail':
          text = '详情'
          break
        case 'batchUpload':
          text = '批量导入'
          break
        case 'comDelete':
          text = '彻底删除'
          break
        case 'uploadRevoke':
          text = '导入撤销'
          break
        case 'journal':
          text = '操作日志'
          break
        default:
          text = '新增'
          break
      }
      return text
    }
  },
  watch: {
    visibleCheck(val) {
      if (val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.visible = true
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
      if (!val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.visible = false
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
    },
    sortCheck(val) {
      if (val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.sortable = true
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
      if (!val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.sortable = false
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
    },
    btnsList(val) {
      let list = []
      for (let i = 0; i < this.btnsOption.length; i++) {
        inter: for (let ii = 0; ii < val.length; ii++) {
          if (val[ii] === this.btnsOption[i].value) {
            list.push(this.btnsOption[i])
            break inter
          }
        }
      }
      this.columnData.btnsList = list
    },
    columnBtnsList(val) {
      let list = []
      for (let i = 0; i < this.columnBtnsOption.length; i++) {
        inter: for (let ii = 0; ii < val.length; ii++) {
          if (val[ii] === this.columnBtnsOption[i].value) {
            list.push(this.columnBtnsOption[i])
            break inter
          }
        }
      }
      this.columnData.columnBtnsList = list
    }
  },
  async created() {
    this.getDataInterfaceSelector()
    if (this.modelType == 4) {
      this.columnBtnsOption = this.columnBtnsOption.filter((o) => o.value != 'detail')
      this.typeList = this.typeList.filter((o) => o.value != 3)
    }
    let list = []
    const loop = (data, parent) => {
      if (!data) return
      if (data.__config__ && data.__config__.jnpfKey === 'table' && data.__config__.children && Array.isArray(data.__config__.children)) {
        list.push(data)
      }
      if (data.__config__ && data.__config__.jnpfKey === 'tab' && data.__config__.children && Array.isArray(data.__config__.children)) {
        loop(data.__config__.children, data.__config__.jnpfKey)
      }
      if (Array.isArray(data) && data.length) {
        for (let i = 0; i < data.length; i++) {
          loop(data[i], parent)
        }
      }
      if (Object.prototype.toString.call(data) === '[object Object]' && parent === 'tab' && data.__config__.children && data.__config__.children.length) {
        loop(data.__config__.children, parent)
      }
      if (data.__config__ && data.__config__.jnpfKey) {
        if (data.__config__.layout === 'colFormItem' && data.__vModel__) {
          list.push(data)
        }
      }
    }
    loop(getDrawingList())
    this.list = list
    let columnOptions = list.filter((o) => noColumnShowList.indexOf(o.__config__.jnpfKey) < 0)
    let searchOptions = list.filter((o) => noSearchList.indexOf(o.__config__.jnpfKey) < 0)
    let columnList = []
    if (this.conf.columnList) {
      columnList = g.Copy(this.conf.columnList)
    } else {
      columnList = columnOptions
    }
    // const newcolumnOptions = g.Copy([...columnOptions, ...(this.conf.joinList || [])])
    const newcolumnOptions = g.union(columnOptions, this.conf.joinList, '*0.__vModel__==*1.__vModel__')
    // console.log(this.conf.joinList)
    // console.log(g.union(newcolumnOptions, this.conf.joinList, '*0.__vModel__==*1.__vModel__'))
    this.columnOptions = columnList
      .map((item) => {
        let o = {}
        if (this.conf.columnList) {
          o = newcolumnOptions.find((c) => c.__vModel__ === item.propId)
          try {
            o.__config__.associatedFrom = item.config.associatedFrom ? item.config.associatedFrom : {}
          } catch (e) {}
        } else {
          o = item
        }
        if (item.__config__ && item.__config__.isJoin) {
          o = item
        }
        if (o) {
          const data = {
            label: o.__config__.label,
            title: o.__config__.label,
            prop: o.__vModelName__,
            field: o.__vModelName__,
            propId: o.__vModel__,
            align: 'left',
            jnpfKey: o.__config__.jnpfKey,
            sortable: true,
            showSummary: false,
            width: 0,
            children: [],
            visible: item.visible || true,
            config: o.__config__
          }
          if (o['__config__'].jnpfKey === 'table') {
            data.children = o['__config__'].children.map((c) => {
              let find = {}
              try {
                find = item.children.find((cc) => cc.field === c.__vModelName__)
              } catch (e) {
                console.log(e)
              }
              return {
                label: c.__config__.label,
                title: c.__config__.label,
                prop: c.__vModelName__,
                field: c.__vModelName__,
                propId: c.__vModel__,
                align: 'left',
                jnpfKey: c.__config__.jnpfKey,
                sortable: true,
                showSummary: false,
                width: '',
                visible: find ? find.visible : true,
                config: o.__config__
              }
            })
          }
          return data
        }
      })
      .filter((o) => o)
    columnOptions.forEach((o) => {
      if (!this.columnOptions.find((c) => c.propId === o.__vModel__)) {
        this.columnOptions.push({
          label: o.__config__.label,
          title: o.__config__.label,
          prop: o.__vModelName__,
          field: o.__vModelName__,
          propId: o.__vModel__,
          align: 'left',
          jnpfKey: o.__config__.jnpfKey,
          sortable: true,
          showSummary: false,
          width: '',
          children: [],
          visible: true,
          config: o.__config__
        })
      }
    })
    this.searchOptions = searchOptions.map((o) => ({
      ...o,
      value: '',
      searchType: getSearchType(o)
    }))
    // conf传递过来肯定有值 但是搜索列表和表单列表不一定有值 没值时直接将表单设计组装的数据直接赋值 有值时要进行合并
    if (typeof this.conf === 'object' && this.conf !== null) {
      this.columnData = Object.assign({}, defaultColumnData, this.conf)
      if (!this.columnData.searchList.length) {
        this.$set(this.columnData, 'searchList', this.searchOptions)
      } else {
        this.columnData.searchList = this.conf.searchList.map((aItem) => {
          const correspondingBItem = this.columnData.searchList.find((bItem) => bItem.__vModel__ === aItem.propId)
          return correspondingBItem ? { ...aItem, ...correspondingBItem } : aItem
        })
      }
      if (!this.columnData.columnList.length) {
        this.$set(this.columnData, 'columnList', this.columnOptions)
      } else {
        this.columnData.columnList = this.columnOptions.map((aItem) => {
          const correspondingBItem = this.columnData.columnList.find((bItem) => bItem.propId === aItem.propId)
          return correspondingBItem ? { ...aItem, ...correspondingBItem } : aItem
        })
      }
    }
    this.setBtnValue(this.columnData.btnsList, this.btnsOption)
    this.setBtnValue(this.columnData.columnBtnsList, this.columnBtnsOption)
    this.btnsList = this.columnData.btnsList.map((o) => o.value)
    this.columnBtnsList = this.columnData.columnBtnsList.map((o) => o.value)
    this.conf.columnList = this.columnData.columnList
    console.log(this.columnData.columnList)
    this.columnData.masterScenes = {
      searchList: this.columnData.searchList,
      columnList: this.columnData.columnList
    }
  },
  beforeDestroy() {
    if (this.sortable1) {
      this.sortable1.destroy()
    }
  },
  mounted() {
    this.rowDrop()
    this.filterDrop()
    this.$nextTick(() => {
      this.setListValue(this.columnData.columnList, this.columnOptions, 'column')
      this.setListValue(this.columnData.searchList, this.searchOptions, 'search')
      const list = [...this.columnData.columnList, ...(this.columnData.joinList || [])]
      const searchList = [...this.columnData.searchList, ...(this.columnData.joinList || [])]
      if (this.columnData.joinList) {
        this.columnData.columnList = g.removeRepeatAttr(list, 'field')
        this.columnData.columnList.forEach((item) => {
          const find = this.columnData.joinList.find((o) => o.field === item.field)
          if (find) {
            item.config = { ...item.config, ...find.config }
          }
        })
        // this.searchOptions = g.removeRepeatAttr(searchList, 'field')
      }
    })
    this.treePreview()
  },
  methods: {
    changeShowFilter(value) {
      this.showDatasetFilter = true
      this.showFalg = value
      this.$nextTick(() => {
        this.$refs?.datasetFilter?.getData()
      })
    },
    //按钮权限过滤
    BtnFilter() {},
    setSeachClick(row) {
      this.setSeachFlag = true //

      this.$nextTick(() => {
        this.$refs.ColumnFilter.onFilterEdit(row)
      })
    },
    SearchFilterChange(val) {
      this.searchList.forEach((item) => {
        if (item.__vModel__ === this.selectSearchId) {
          item['value-format'] = val['dateFormat']
          item.format = val.format
          item.type = val.dateType
          item.dateType = val.dateType
          item.value = val.conditions[0].values
          item.function = val.conditions[0].function
        }
      })
    },
    setBtnValue(replacedData, data, key) {
      key = key ? key : 'value'
      for (let i = 0; i < replacedData.length; i++) {
        inter: for (let ii = 0; ii < data.length; ii++) {
          if (replacedData[i][key] === data[ii][key]) {
            data[ii] = replacedData[i]
            break inter
          }
        }
      }
    },
    setListValue(replacedData, data, type) {
      const key = type === 'column' ? 'propId' : '__vModel__'
      let res = []
      for (let i = 0; i < replacedData.length; i++) {
        inter: for (let ii = 0; ii < data.length; ii++) {
          if (replacedData[i][key] === data[ii][key]) {
            if (type === 'column') {
              data[ii].align = replacedData[i].align
              data[ii].width = replacedData[i].width
              data[ii].sortable = replacedData[i].sortable
              data[ii].visible = replacedData[i].visible
              data[ii].showSummary = replacedData[i].showSummary
            }
            if (type === 'search') {
              data[ii].conditions = replacedData[i].conditions ? replacedData[i].conditions : null
              data[ii].count1 = replacedData[i].count1 ? replacedData[i].count1 : null
              data[ii].count2 = replacedData[i].count2 ? replacedData[i].count2 : null
              data[ii].value1 = replacedData[i].value1 ? replacedData[i].value1 : null
              data[ii].value2 = replacedData[i].value2 ? replacedData[i].value2 : null
              data[ii].relativeSize = replacedData[i].relativeSize ? replacedData[i].relativeSize : null
              data[ii].relativeCount = replacedData[i].relativeCount ? replacedData[i].relativeCount : null
              data[ii].timeType = replacedData[i].timeType ? replacedData[i].timeType : null
              data[ii].dateType = replacedData[i].dateType ? replacedData[i].dateType : null
              data[ii].enumSource = replacedData[i].enumSource ? replacedData[i].enumSource : null
              data[ii].enumId = replacedData[i].enumId ? replacedData[i].enumId : null
              data[ii].apiProps = replacedData[i].apiProps ? replacedData[i].apiProps : { label: '', value: '' }
              data[ii].options = replacedData[i].options ? replacedData[i].options : null
              data[ii].cascadeSwitch = replacedData[i].cascadeSwitch ? replacedData[i].cascadeSwitch : false
              data[ii].cascadeSet = replacedData[i].cascadeSet ? replacedData[i].cascadeSet : { idKey: '', pidKey: '', childrenName: 'children' }
            }
            res.push(data[ii])
            break inter
          }
        }
      }
      res.forEach((row) => {
        this.$refs[type + 'Table'].toggleRowSelection(row, true)
      })
    },
    /**
     * 供父组件使用 获取列表JSON
     */
    getData() {
      return new Promise((resolve, reject) => {
        if (!this.columnData.columnList.length) reject({ msg: '列表字段不允许为空', target: 2 })
        if (this.columnData.type == 2) {
          this.columnData.treeList.forEach((item) => {
            if (item.treeDataSource === 'dictionary' && !item.treeDictionary) reject({ msg: '请选择数据字典', target: 2 })
            if (item.treeDataSource === 'api') {
              if (!item.treePropsValue) reject({ msg: '请选择主键字段', target: 2 })
              if (!item.treePropsLabel) reject({ msg: '请选择显示字段', target: 2 })
              if (!item.treePropsLabel) reject({ msg: '请选择显示字段', target: 2 })
              if (!item.treeSearch) reject({ msg: '请选择搜索字段', target: 2 })
            }
            if (!item.treeRelation) reject({ msg: '请选择关联字段', target: 2 })
          })
        }
        if (this.columnData.type == 3) {
          if (!this.columnData.groupField) reject({ msg: '请选择分组字段', target: 2 })
        }
        resolve({ columnData: this.columnData, target: 2 })
      })
    },
    setSort() {
      const el = this.$refs.dragTableSearch.$el.querySelectorAll('.vxe-table--render-wrapper > .vxe-table--main-wrapper > .vxe-table--body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function (dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.columnData.columnList.splice(evt.oldIndex, 1)[0]
          this.columnData.columnList.splice(evt.newIndex, 0, targetRow)
        },
        handle: '.drag-handler'
      })
      const el2 = this.$refs.xTable1.$el.querySelectorAll('.vxe-table--render-wrapper > .vxe-table--main-wrapper > .vxe-table--body-wrapper > table > tbody')[0]
      Sortable.create(el2, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function (dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.columnData.searchList.splice(evt.oldIndex, 1)[0]
          this.columnData.searchList.splice(evt.newIndex, 0, targetRow)
        },
        handle: '.drag-handler'
      })
    },
    searchSelectionChange(val) {
      this.$set(this.columnData, 'searchList', val)
    },
    columnSelectionChange(val) {
      this.$set(this.columnData, 'columnList', val)
    },
    getDataInterfaceSelector() {
      getAPIList().then((res) => {
        this.dataInterfaceSelector = res
      })
    },
    dataTypeChange() {
      this.columnData.treePropsValue = 'id'
      this.columnData.treePropsChildren = 'children'
      this.columnData.treePropsLabel = 'fullName'
    },
    filterDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.dragTableSearch
        this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({ newIndex, oldIndex }) => {
            const currRow = this.columnData.searchList.splice(oldIndex, 1)[0]
            this.columnData.searchList.splice(newIndex, 0, currRow)
          }
        })
      })
    },
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable1
        this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({ item, oldIndex }) => {
            const options = { children: 'children' }
            const targetTrElem = item
            const wrapperElem = targetTrElem.parentNode
            const prevTrElem = targetTrElem.previousElementSibling
            const tableTreeData = this.columnData.columnList
            const selfRow = xTable.getRowNode(targetTrElem).item
            const selfNode = XEUtils.findTree(tableTreeData, (row) => row === selfRow, options)
            if (prevTrElem) {
              // 移动到节点
              const prevRow = xTable.getRowNode(prevTrElem).item
              const prevNode = XEUtils.findTree(tableTreeData, (row) => row === prevRow, options)
              if (XEUtils.findTree(selfRow[options.children], (row) => prevRow === row, options)) {
                // 错误的移动
                const oldTrElem = wrapperElem.children[oldIndex]
                wrapperElem.insertBefore(targetTrElem, oldTrElem)
                return this.message({ content: '不允许自己给自己拖动！', status: 'error' })
              }
              const currRow = selfNode.items.splice(selfNode.index, 1)[0]
              if (xTable.isTreeExpandByRow(prevRow)) {
                // 移动到当前的子节点
                prevRow[options.children].splice(0, 0, currRow)
              } else {
                // 移动到相邻节点
                prevNode.items.splice(prevNode.index + (selfNode.index < prevNode.index ? 0 : 1), 0, currRow)
              }
            } else {
              // 移动到第一行
              const currRow = selfNode.items.splice(selfNode.index, 1)[0]
              tableTreeData.unshift(currRow)
            }
            // 如果变动了树层级，需要刷新数据
            this.columnData.columnList = [...tableTreeData]
          }
        })
      })
    },

    focusEvent(row, rowIndex) {
      this.visualLink.isDiglog = true
      this.rowIndex = rowIndex
    },
    getSelect(row) {
      this.visualLink.isDiglog = false
      this.columnData.columnList[this.rowIndex].config.associatedFrom = row
      this.columnData.columnList.splice(this.rowIndex, 1, this.columnData.columnList[this.rowIndex])
    },
    tabClick() {
      this.treePreview()
    },
    propsUrlChange(val) {
      if (!val) {
        return
      }
      //获取api信息
      dataapiDetail(val).then((res) => {
        let resJson = JSON.parse(res.data.data.note || '{}')
        this.preview.fields = resJson.showFields || []
      })
    },
    treePreview() {
      this.treeListIndex = this.columnData.treeList[this.columnData.treeList.length - 1].name
      const data = this.columnData.treeList.find((v) => v.name === this.treeListIndex)
      if (!data.treePropsUrl) return
      dataapiDetail(data.treePropsUrl).then((res) => {
        let { apiKey, note } = res.data.data
        let resJson = JSON.parse(note || '{}')
        this.preview.fields = resJson.showFields || []
        this.preview.fieldsJson = JSON.parse(JSON.stringify(resJson.showFields || []))
        openurl(apiKey).then((ress) => {
          // 取前10条
          this.preview.data = ress.data.data.slice(0, 10)
        })
      })
    },
    addTab() {
      const data = JSON.parse(JSON.stringify(defaultColumnData.treeList[0]))
      data.name = (this.columnData.treeList[this.columnData.treeList.length - 1].name + 1).toString()
      this.treeListIndex = data.name
      this.columnData.treeList.push(data)
    },
    removeTab(index) {
      if (this.columnData.treeList.length === 1) {
        this.$message.error('至少保留一个tab页')
        return
      }
      this.columnData.treeList = this.columnData.treeList.filter((v) => v.name !== index)
      this.treeListIndex = this.columnData.treeList[this.columnData.treeList.length - 1].name
    },
    rowStyle({ row }) {
      const colorList = ['#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1', '#1e90ff', '#c71585']
      if (this?.columnData?.joinList) {
        const tableList = g.removeRepeatAttr(this.columnData.joinList.map((v) => v.config.tableName))
        const obj = {}
        tableList.forEach((v, index) => {
          obj[v] = colorList[index]
        })
        if (row?.config?.tableName && obj[row?.config?.tableName]) {
          return {
            // backgroundColor: obj[row?.config?.tableName],
            color: obj[row?.config?.tableName]
          }
        }
      }
    },
    addScenes() {
      this.columnData.scenes.push({
        name: '场景' + (this.columnData.scenes.length + 1),
        searchList: g.Copy(this.columnData.searchList),
        columnList: g.Copy(this.columnData.columnList)
      })
    },
    selectScenes(item) {
      this.columnData.searchList = item.searchList
      this.columnData.columnList = item.columnList
    }
  }
}
</script>
<style lang="scss" scoped>
@import './index.scss';
.sortable-row-demo .drag-btn {
  cursor: move;
  font-size: 12px;
}
.sortable-row-demo .vxe-body--row.sortable-ghost,
.sortable-row-demo .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
</style>
