<template>
  <el-dialog
    title="编辑自定义视图"
    :visible="dialogVisible"
    :before-close="beforeClose"
    :show-close="false"
    custom-class="dialog-container"
    fullscreen
  >
    <template v-slot:title>
      <div class="flex" style="justify-content: space-between">
        <el-page-header
          @back="dialogVisible = false"
          content="编辑自定义视图"
        ></el-page-header>
        <el-button-group>
          <ht-submit-button
            :url="saveUrl"
            :model="submitData"
            scope-name="viewEdit"
            @before-save-data="beforeSaveData"
            @after-save-data="afterSaveData"
            :loading="isLoading"
          >
            {{ $t('eip.common.save') }}
          </ht-submit-button>
          <el-button @click="editTemplate" v-if="id">编辑模板</el-button>
          <el-button @click="initDefaultData(true)" v-if="id"
            >重置字段</el-button
          >
          <el-button @click="addToMenu('manage')" v-if="id"
            >添加为管理端菜单</el-button
          >
          <el-button @click="addToMenu('front')" v-if="id"
            >添加为应用端菜单</el-button
          >
          <el-button @click="close">返回</el-button>
        </el-button-group>
      </div>
    </template>
    <el-tabs class="fullheight" @tab-click="tabClick" v-model="activeName">
      <el-tab-pane label="基本信息" class="fullheight" name="baseInfo">
        <el-form data-vv-scope="viewEdit">
          <ht-form-item label="名称" validate="required">
            <ht-input
              v-model="data.name"
              style="width: 80%"
              :validate="{required: true}"
              :maxlength="50"
              :showWordLimit="true"
            />
          </ht-form-item>
          <ht-form-item label="别名" validate="required">
            <ht-input
              v-model="data.alias"
              style="width: 80%"
              v-pinyin="data.name"
              :disabled="data.id ? true : false"
              :validate="{
                required: true,
                regex: {
                  exp: '^[a-zA-Z][a-zA-Z0-9_]*$',
                  message: '只能输入字母、数字、下划线，且以字母开头',
                },
              }"
              :maxlength="50"
              :showWordLimit="true"
            />
          </ht-form-item>
          <ht-form-item v-if="this.interface" label="接口地址">
            <ht-input v-model="this.interface" style="width: 80%" disabled />
            <el-popover
              placement="top-start"
              title="接口提示"
              width="400"
              trigger="hover"
              content='接口类型为POST类型，接口参数示例为：{pageBean: {page: "1", pageSize: 30, showTotal: "true"},querys: [{property: "表名.字段名", value: "参数内容", group: "main", operation: "LIKE", relation: "OR"}}'
            >
              <el-button
                slot="reference"
                class="copy-btn"
                type="text"
                v-clipboard:copy="this.interface"
                v-clipboard:success="onCopy"
                v-clipboard:error="onError"
                >复制地址</el-button
              >
            </el-popover>
          </ht-form-item>
          <ht-form-item label="是否分页" validate="required">
            <el-switch
              v-model="data.needPage"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
            &nbsp;
            <ht-select
              :options="[
                {key: '10', value: 10},
                {key: '20', value: 20},
                {key: '30', value: 30},
                {key: '50', value: 50},
                {key: '100', value: 100},
              ]"
              :props="{key: 'key', value: 'value'}"
              v-model="data.pageSize"
              v-if="data.needPage === 1"
            />
          </ht-form-item>
          <ht-form-item label="是否初始查询" validate="required">
            <el-switch
              v-model="data.initQuery"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </ht-form-item>
          <ht-form-item label="是否显示行号" validate="required">
            <el-switch
              v-model="data.showRowsNum"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </ht-form-item>
          <ht-form-item label="数据模板" validate="required">
            <ht-select
              :options="templateList"
              v-model="data.templateAlias"
              :props="{key: 'alias', value: 'templateName'}"
              :validate="{required: true}"
            />
          </ht-form-item>
          <ht-form-item label="重新生成模板" validate="required">
            <el-switch
              v-model="data.rebuildTemp"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </ht-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="显示字段" class="fullheight" name="showField">
        <el-row class="fullheight">
          <el-col :span="6" class="fullheight">
            <el-card class="box-card fullheight">
              <div slot="header" class="clearfix">
                <div class="tools">
                  <ht-input
                    v-model="headerTitle"
                    placeholder="请输入一级表头"
                  ></ht-input>
                  <el-tooltip placement="top" effect="light">
                    <div slot="content">添加表头</div>

                    <span
                      @click="addMultiTableHeader()"
                      class="iconfont icon-folder"
                    ></span>
                  </el-tooltip>
                </div>
              </div>
              <el-scrollbar
                class="scrollbar-height fullheight"
                v-if="reLoadFlag"
              >
                <ht-tree
                  support-filter
                  :data="data.shows"
                  node-key="fieldDesc"
                  default-expand-all
                  :expand-on-click-node="false"
                  @node-click="nodeClick"
                  @node-contextmenu="rightClick"
                  @node-drag-start="handleDragStart"
                  @node-drag-enter="handleDragEnter"
                  @node-drag-leave="handleDragLeave"
                  @node-drag-over="handleDragOver"
                  @node-drag-end="handleDragEnd"
                  @node-drop="handleDrop"
                  draggable
                  :allow-drop="allowDrop"
                  :allow-drag="allowDrag"
                  :props="{label: 'fieldDesc', children: 'children'}"
                  :class="{'edit-tree': isEditor}"
                >
                  <span class="custom-tree-node" slot-scope="{node, data}">
                    <span class="el-tree-node__label"
                      ><i v-if="data.fieldName" class="icon-draggable"></i
                      ><i v-else class="el-icon-tickets"></i>
                      {{ node.label }}</span
                    >
                  </span>
                </ht-tree>
              </el-scrollbar>
              <!--              <el-form data-vv-scope="editNode" v-form="currentEditData" v-if="currentData">-->
              <!--                <ht-form-item label="">-->
              <!--                  <template slot="label">-->
              <!--                    <el-tooltip content="可以在这里编辑选中节点的表头名称">-->
              <!--                      <i class="property-tip icon-question" />-->
              <!--                    </el-tooltip>-->
              <!--                    选中节点-->
              <!--                  </template>-->
              <!--                  <ht-input-->
              <!--                    v-model="currentEditData.desc"-->
              <!--                    placeholder="请输入字段描述"-->
              <!--                    @change="(value) => changeDesc(value)"-->
              <!--                  ></ht-input>-->
              <!--                </ht-form-item>-->
              <!--              </el-form>-->
            </el-card>
          </el-col>
          <el-col :span="18" class="fullheight">
            <dynamic-table
              :table-data="tableData"
              :table-header="data.shows"
              prop="fieldName"
              label="fieldDesc"
            ></dynamic-table>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="条件字段" name="conditionField">
        <el-table :data="data.conditions" height="400" border>
          <el-table-column prop="fieldName" label="列名" />
          <el-table-column label="描述">
            <template slot-scope="scope">
              <ht-input
                v-model="scope.row.fieldDesc"
                :maxlength="50"
                :showWordLimit="true"
              />
            </template>
          </el-table-column>
          <el-table-column width="80" prop="dataType" label="数据类型" />
          <el-table-column width="100" prop="controlTypeDesc" label="控件类型">
          </el-table-column>
          <el-table-column label="操作符" width="120">
            <template slot-scope="scope">
              <ht-select
                style="width: 109px"
                v-if="detectDataType(scope.row) === 'date'"
                :options="dateOpOption"
                :props="{key: 'key', value: 'value'}"
                v-model="scope.row.operate"
              />
              <ht-select
                style="width: 109px"
                v-else-if="detectDataType(scope.row) === 'char'"
                :options="charOpOption"
                :props="{key: 'key', value: 'value'}"
                v-model="scope.row.operate"
              />
              <ht-select
                style="width: 109px"
                v-else
                :options="operatorOption"
                :props="{key: 'key', value: 'value'}"
                v-model="scope.row.operate"
              />
            </template>
          </el-table-column>
          <el-table-column label="值来源" width="80">
            <template>
              <span>表单输入</span>
            </template>
          </el-table-column>
          <el-table-column label="是否隐藏" width="80">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.hidden"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-table-column>
          <el-table-column label="管理" width="140">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-arrow-up"
                @click="arrayMove('conditions', scope.row, 'up')"
              />
              <el-button
                icon="el-icon-arrow-down"
                @click="arrayMove('conditions', scope.row, 'down')"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="数据过滤" name="filter">
        <el-button @click="addFilter()">添加脚本</el-button>
        <el-table :data="filterFields" height="400" border>
          <el-table-column prop="name" label="名称" />
          <el-table-column label="Key" prop="key"> </el-table-column>
          <el-table-column label="类型">
            <template slot-scope="scope">
              <el-tag type="primary" v-if="scope.row.type === '1'"
                >条件类型</el-tag
              >
              <el-tag type="danger" v-if="scope.row.type === '2'">SQL</el-tag>
              <el-tag type="warning" v-if="scope.row.type === '3'"
                >追加SQL</el-tag
              >
              <el-tag type="success" v-if="scope.row.type === '4'"
                >数据权限</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="controlTypeDesc" label="权限">
            <template slot-scope="scope">
              <el-tag
                type="info"
                v-for="(item, index) in scope.row.right"
                :key="index"
                v-show="item.checked !== false"
                >{{ item.title
                }}<span v-if="item.name">:{{ item.name }}</span></el-tag
              >
              <el-button
                icon="el-icon-edit"
                @click="editAuth(scope.row, scope.$index)"
              />
            </template>
          </el-table-column>
          <el-table-column label="管理" width="240">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-arrow-up"
                @click="arrayMove('filterFields', scope.row, 'up')"
              />
              <el-button
                icon="el-icon-arrow-down"
                @click="arrayMove('filterFields', scope.row, 'down')"
              />
              <el-button
                icon="el-icon-edit"
                @click="addFilter(scope.row, scope.$index)"
              />
              <el-button
                icon="el-icon-delete"
                @click="filterFields.splice(scope.$index, 1)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="功能按钮" name="functionButton">
        <el-table :data="data.buttons" height="400" border>
          <el-table-column prop="name" label="名称" />
          <el-table-column label="类型">
            <template slot-scope="scope">
              <el-tag type="primary" v-if="!scope.row.inRow">页头</el-tag>
              <el-tag type="warning" v-if="scope.row.inRow">行内</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="icon" label="按钮图标">
            <template slot-scope="scope">
              <span :class="scope.row.icon" />
            </template>
          </el-table-column>
          <el-table-column prop="urlPath" label="URL路径"> </el-table-column>
          <el-table-column label="隐藏">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.hidden"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-table-column>
          <el-table-column label="管理" width="140">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-arrow-up"
                @click="arrayMove('buttons', scope.row, 'up')"
              />
              <el-button
                icon="el-icon-arrow-down"
                @click="arrayMove('buttons', scope.row, 'up')"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="汇总设置" name="summarySetting">
        <summary-setting
          ref="SummarySetting"
          :data.sync="summaryData"
          :tabActiveName="activeName"
          isViewList
        />
      </el-tab-pane>
    </el-tabs>
    <template-edit ref="templateEdit" :id="this.id" :sqlAlias="data.sqlAlias" />
    <menus-add
      ref="menusAdd"
      :alias="data.alias"
      :sqlAlias="data.sqlAlias"
      :viewId="id"
    />
    <filter-dialog
      ref="filterDialog"
      :metafields="calAllField"
      :conditionfields="data.conditions"
      :filterData="selectedData"
      :keys="filterFields"
      @after-save="afterSave"
    />
    <auth-edit ref="authEdit" :condition="selectedData" @confirm="afterSave" />

    <div
      id="perTreeMenu"
      v-if="tmDisplay"
      class="tree_menu"
      :style="{...rightMenu}"
    >
      <ul v-if="!currentData.fieldName">
        <li>注释<ht-input v-model="currentData.fieldDesc"></ht-input></li>
        <li @click="removeNode(currentNode, currentData)">删除表头</li>
        <li>
          <ht-input v-model="headerTitle"></ht-input
          ><span @click="addMultiTableHeader(currentNode, currentData)"
            >添加下级表头</span
          >
        </li>
      </ul>
      <el-table v-if="currentData.fieldName" :data="currentDatas" border>
        <el-table-column prop="fieldName" label="列名" />
        <el-table-column label="注释" width="245">
          <template slot-scope="scope">
            <ht-input v-model="scope.row.fieldDesc" :maxlength="50" />
          </template>
        </el-table-column>
        <el-table-column label="支持排序" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.sortable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              v-if="scope.row.isVirtual !== 1"
            />
          </template>
        </el-table-column>
        <el-table-column label="排序方向" width="100">
          <template slot-scope="scope">
            <ht-select
              :options="[{key: 'asc'}, {key: 'desc'}]"
              :props="{key: 'key', value: 'key'}"
              v-model="scope.row.sortSeq"
              clearable
              v-if="scope.row.defaultSort === 1"
            />
          </template>
        </el-table-column>
        <el-table-column label="默认排序" width="80">
          <template slot-scope="scope">
            <el-button
              @click="defaultSortChange(scope.row)"
              :type="scope.row.defaultSort !== 1 ? 'info' : 'success'"
              >{{ scope.row.defaultSort !== 1 ? '否' : '是' }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="是否冻结" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.frozen"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否隐藏" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.hidden"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="对齐方式" width="245">
          <template slot-scope="scope">
            <ht-select
              :options="[
                {key: 'left', value: '居左'},
                {key: 'center', value: '居中'},
                {key: 'right', value: '居右'},
              ]"
              :props="{key: 'key', value: 'value'}"
              v-model="scope.row.align"
            />
          </template>
        </el-table-column>
        <el-table-column label="宽度" width="245">
          <template slot-scope="scope">
            <ht-input v-model="scope.row.width" :maxlength="50" />
          </template>
        </el-table-column>
        <el-table-column label="统计类型" width="245">
          <template slot-scope="scope">
            <ht-select
              :options="[
                {key: '', value: '请选择'},
                {key: 'sum', value: '求和'},
              ]"
              :props="{key: 'key', value: 'value'}"
              v-model="scope.row.summaryType"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
</template>

<script>
import form from '@/api/form.js'
import flow from '@/api/flow.js'
import utils from 'hotent-ui/src/utils'
// import SummarySetting from '../dataTemplate/SummarySetting'
const templateEdit = () =>
  import('@/components/form/customView/TemplateEdit.vue')
const menusAdd = () => import('@/components/form/customView/MenusAdd.vue')
const filterDialog = () =>
  import('@/components/form/customView/FilterDialog.vue')
const authEdit = () => import('@/components/form/customView/AuthEdit.vue')
const summarySetting = () =>
  import('@/components/form/dataTemplate/SummarySetting.vue')
const dynamicTable = () =>
  import('@/components/form/multiTableHeader/DynamicTable.vue')
export default {
  components: {
    templateEdit,
    menusAdd,
    filterDialog,
    authEdit,
    summarySetting,
    dynamicTable,
  },
  props: {
    id: String,
    sqlAlias: String,
  },
  data() {
    return {
      dialogVisible: false,
      activeName: 'baseInfo',
      data: {
        templateAlias: '',
        rebuildTemp: 1,
        sqlAlias: this.sqlAlias,
        filterType: '1',
        needPage: 1,
        pageSize: '30',
        initQuery: 1,
        showRowsNum: 0,
        supportGroup: 0,
        shows: [],
        conditions: [],
        alias: '',
      },
      interface: '',
      templateList: [],
      sqlDef: {},
      fields: [],
      filterFields: [],
      permissionList: [],
      permissionMap: {none: '无'},
      saveUrl: window.context.form + '/form/query/queryView/save',
      submitData: {},
      selectedData: {},
      selectedIndex: 0,
      summaryData: {bpmDataTemplate: {}, displaySettingFields: ''},
      tableData: [],
      headerTitle: '',
      isEditor: true,
      tmDisplay: false,
      rightMenu: null,
      currentNode: null,
      currentData: {},
      currentDatas: [],
      currentEditData: {desc: ''},
      allField: [],
      charOpOption: [
        {key: 'EQ', value: '等于'},
        {key: 'NE', value: '不等于'},
        {key: 'LK', value: '相似'},
        {key: 'LFK', value: '右相似'},
        {key: 'RHK', value: '左相似'},
      ],
      dateOpOption: [
        {key: 'EQ', value: '等于'},
        {key: 'NE', value: '不等于'},
        {key: 'BETWEEN', value: '在...之间'},
      ],
      operatorOption: [
        {key: 'EQ', value: '等于'},
        {key: 'NE', value: '不等于'},
      ],
      charTypes: new Map([
        ['char', 'char'],
        ['varchar', 'varchar'],
        ['binary', 'binary'],
        ['varbinary', 'varbinary'],
        ['blob', 'blob'],
        ['text', 'text'],
        ['enum', 'enum'],
        ['set', 'set'],
        ['nchar', 'nchar'],
        ['nvarchar2', 'nvarchar2'],
        ['varchar2', 'varchar2'],
        ['long', 'long'],
        ['raw', 'raw'],
        ['long raw', 'long raw'],
        ['bpchar', 'bpchar'],
      ]),
      dateTypes: new Map([
        ['date', 'date'],
        ['datetime', 'datetime'],
        // ['timestamp','timestamp'],
        // ['year','year'],
        // ['time','time'],
      ]),
      reLoadFlag: true,
      isLoading: false,
    }
  },
  watch: {
    data: {
      handler(newValue, oldValue) {
        if (newValue.alias != '') {
          this.interface =
            window.context.form +
            '/form/query/queryView/data_' +
            this.sqlAlias +
            '/' +
            newValue.alias
          this.convertData()
        }
      },
    },
    deep: true,
    immediate: true,
  },
  computed: {
    calAllField: function () {
      if (this.data && this.data.shows) {
        this.allField = []
        this.getAllField(this.data.shows)
        return this.allField
      }
      return []
    },
  },
  mounted() {},
  methods: {
    detectDataType(fieldConfig) {
      const type = fieldConfig.dataType.toLowerCase()
      const controlType = fieldConfig.controlType.toLowerCase()
      if (this.charTypes.get(type)) {
        return 'char'
      } else if (this.dateTypes.get(type) && controlType === 'date') {
        return 'date'
      } else {
        return 'normal'
      }
    },
    getAllField(shows, cb) {
      shows.forEach((element) => {
        if (element.children && element.children.length > 0) {
          this.getAllField(element.children)
        } else {
          let tmp = element
          this.allField.push(tmp)
        }
      })
    },
    forEachShowsWithCallback(shows, cb) {
      shows.forEach((element) => {
        if (element.children && element.children.length > 0) {
          this.forEachShowsWithCallback(element.children, cb)
        } else {
          if (cb) {
            cb(element)
          }
        }
      })
    },
    // 复制成功时的回调函数
    onCopy(e) {
      this.$message.success('内容已复制到剪切板！')
    },
    // 复制失败时的回调函数
    onError(e) {
      this.$message.error('抱歉，复制失败！')
    },
    beforeClose() {
      this.dialogVisible = false
      this.tmDisplay = false
    },
    handleOpen() {
      const this_ = this
      this_.dialogVisible = true
      this.activeName = 'baseInfo'
      this_.$nextTick(() => {
        // 获取模板列表
        form.getTemplateList().then((response) => {
          this_.templateList = response
          this_.data.templateAlias = response[0].alias
        })
        // 获取权限列表
        flow.getPermissionList().then((result) => {
          if (result) {
            this_.permissionList = result
            for (let i = 0; i < result.length; i++) {
              this_.permissionMap[result[i].type] = result[i].title
            }
          }
        })
        if (this_.id) {
          form.getViewById(this_.id).then((response) => {
            this_.data = response
            this_.afterLoadEvent()
            this_.getSqlDef(this_.sqlAlias)
          })
        } else {
          this_.initData()
          this_.initGroup()
          this_.getSqlDef(this_.sqlAlias)
        }
      })
    },
    initData() {
      this.data = {
        templateAlias: '',
        rebuildTemp: 1,
        sqlAlias: this.sqlAlias,
        filterType: 1,
        needPage: 1,
        pageSize: '30',
        initQuery: 1,
        showRowsNum: 0,
        supportGroup: 0,
        shows: [],
        conditions: [],
        alias: '',
      }
      this.filterFields = []
      this.summaryData.displaySettingFields = ''
      this.summaryData.bpmDataTemplate = {}
    },
    afterLoadEvent() {
      this.data.shows = JSON.parse(this.data.shows)
      this.data.conditions = JSON.parse(this.data.conditions)
      this.data.buttons = JSON.parse(this.data.buttons)
      this.data.groupSetting = JSON.parse(this.data.groupSetting)
      this.$set(this.data, 'rebuildTemp', 1)
      this.filterFields = this.data.filter ? JSON.parse(this.data.filter) : []
    },
    getSqlDef(sqlAlias) {
      form.getQuerySqlDef(sqlAlias).then((response) => {
        this.sqldef = response
        //新增时需要加载初始化默认的显示字段和条件字段的
        if (!this.id) {
          this.initDefaultData(false)
          this.initFields()
        } else {
          this.initFields()
        }
      })
    },
    initFields() {
      if (this.fields.length < 1) {
        this.forEachShowsWithCallback(this.data.shows, (field) => {
          field.name = field.name
          field.type = field.controlType
          field.desc = field.fieldDesc
          this.fields.push(field)
        })
      }
    },
    defaultSortChange(obj) {
      this.forEachShowsWithCallback(this.data.shows, (field) => {
        if (field.id === obj.id) {
          field.defaultSort = 1 - field.defaultSort
        } else {
          field.defaultSort = 0
        }
      })
    },
    close() {
      this.beforeClose()
    },
    editTemplate() {
      this.$refs.templateEdit.handleOpen()
    },
    initDefaultData(isTip) {
      this.data.shows = []
      this.data.conditions = []
      for (let i = 0; i < this.sqldef.metafields.length; i++) {
        if (this.sqldef.metafields[i].isShow === 1) {
          let json = {...this.sqldef.metafields[i]}
          json.sortable = 0
          json.sortSeq = 'asc'
          json.defaultSort = 0
          json.frozen = 0
          json.hidden = 0
          json.align = 'center'
          json.group = 0
          this.data.shows.push(json)
        }
        if (this.sqldef.metafields[i].isSearch === 1) {
          // 条件字段
          let json1 = {...this.sqldef.metafields[i]}
          json1.hidden = 0
          json1.operate = 'EQ'
          json1.valueFrom = '1'
          this.data.conditions.push(json1)
        }
      }
      // 默认的按钮
      this.data.buttons = JSON.parse(this.sqldef.buttonDef)
      this.reLoadFlag = false
      this.$nextTick(() => {
        this.reLoadFlag = true
      })
      if (isTip) {
        this.$message({type: 'success', message: '已重置字段'})
      }
    },
    //显示自定义视图添加到菜单dialog
    addToMenu(type) {
      this.$refs.menusAdd.showDialog(type, 'addReport')
    },
    addFilter(data, index) {
      let isAdd = false
      if (data) {
        this.selectedData = data
        this.selectedIndex = index
      } else {
        this.selectedData = {}
        this.selectedIndex = -1
        isAdd = true
      }

      this.$refs.filterDialog.handleOpen(isAdd)
    },
    initGroup() {
      let groupSetting = {}
      groupSetting.groupField = []
      groupSetting.groupColumnShow = []
      groupSetting.groupText = []
      groupSetting.groupOrder = []
      groupSetting.groupSummary = []
      this.data.groupSetting = groupSetting
    },
    arrayMove(group, item, direct) {
      if (group === 'filterFields') {
        this[group] = utils.arrayMove(this.data[group], item, direct)
      } else {
        this.data[group] = utils.arrayMove(this.data[group], item, direct)
      }
    },
    beforeSaveData() {
      this.isLoading = true
      this.submitData = {...this.data}
      //处理合并查询
      let isIndistinct = 'hide'
      let conditionAllName = ''
      let conditionAllDesc = ''
      for (let i = 0; i < this.submitData.conditions.length; i++) {
        this.submitData.conditions[i].na =
          this.submitData.conditions[i].fieldName
        if (
          this.submitData.conditions[i].isCombine === 1 &&
          this.submitData.conditions[i].isSearch === 1 &&
          this.submitData.conditions[i].hidden === 0
        ) {
          isIndistinct = 'show'
          conditionAllName += this.submitData.conditions[i].name + ','
          conditionAllDesc += this.submitData.conditions[i].fieldDesc + '/'
        }
      }
      if (conditionAllName !== '') {
        conditionAllName = conditionAllName.substring(
          0,
          conditionAllName.length - 1
        )
      }
      if (conditionAllDesc !== '') {
        conditionAllDesc = conditionAllDesc.substring(
          0,
          conditionAllDesc.length - 1
        )
      }

      this.submitData.groupSetting = JSON.stringify(
        this.submitData.groupSetting
      )
      this.submitData.conditions = JSON.stringify(this.submitData.conditions)
      this.submitData.buttons = JSON.stringify(this.submitData.buttons)
      this.submitData.shows = JSON.stringify(this.submitData.shows)
      this.submitData.filter = JSON.stringify(this.filterFields)
      this.submitData.isIndistinct = isIndistinct
      this.submitData.conditionAllName = conditionAllName
      this.submitData.conditionAllDesc = conditionAllDesc
      this.$refs.SummarySetting.saveSummaryField()
      this.submitData.summarySetting =
        this.summaryData.bpmDataTemplate.summaryField
      this.submitData.summaryRegionHtml =
        this.summaryData.bpmDataTemplate.summaryRegionHtml
    },
    afterSaveData() {
      this.isLoading = false
      this.close()
      this.$emit('after-save', {})
    },
    afterSave(data) {
      if (this.selectedIndex >= 0) {
        this.filterFields.splice(this.selectedIndex, 1)
        this.filterFields.splice(this.selectedIndex, 0, data)
      } else {
        this.filterFields.push(data)
      }
    },
    editAuth(data, index) {
      if (data) {
        this.selectedData = data
        this.selectedIndex = index
      }
      this.$refs.authEdit.handleOpen()
    },
    convertData() {
      let list = this.data.shows.filter((item) => item.isShow === 1)
      this.summaryData.displaySettingFields = JSON.stringify(list)
      this.summaryData.bpmDataTemplate.summaryField = this.data.summarySetting
      this.summaryData.bpmDataTemplate.summaryRegionHtml =
        this.data.summaryRegionHtml
    },
    handleDragStart(node, ev) {},
    handleDragEnter(draggingNode, dropNode, ev) {},
    handleDragLeave(draggingNode, dropNode, ev) {},
    handleDragOver(draggingNode, dropNode, ev) {},
    handleDragEnd(draggingNode, dropNode, dropType, ev) {},
    handleDrop(draggingNode, dropNode, dropType, ev) {},
    allowDrop(draggingNode, dropNode, type) {
      // 是否允许放下
      // 字段不能移动到字段下
      if (dropNode.data.name && type == 'inner') {
        return false
      }
      return true
    },
    allowDrag(draggingNode) {
      // 字段 和 合并字段的表头都允许拖拽
      return true
    },
    nodeClick(data, node, comp) {
      this.currentData = data
      this.currentEditData.desc = data.desc
      this.currentNode = node
      this.tmDisplay = false
      this.currentDatas = []
      this.currentDatas.push(this.currentData)
    },
    rightClick(e, data, node, comp) {
      this.currentData = data
      this.currentDatas = []
      this.currentDatas.push(this.currentData)
      this.currentNode = node
      let topPosition = e.pageY
      let tempHeight = document.body.clientHeight - topPosition
      if (tempHeight < 150) {
        topPosition = topPosition - 100
      }
      this.rightMenu = {top: topPosition + 'px', left: e.pageX + 'px'}
      this.tmDisplay = true
      const self = this
    },
    tabClick(tab) {
      this.activeName = tab.name
      this.tmDisplay = false
    },
    addMultiTableHeader(node, data) {
      if (!this.headerTitle) {
        this.$message.warning('请先输入表头名')
        return
      }
      const newChild = {fieldDesc: this.headerTitle, children: []}
      if (data) {
        if (!data.children) {
          this.$set(data, 'children', [])
        }
        data.children.push(newChild)
      } else {
        this.data.shows.unshift({fieldDesc: this.headerTitle, children: []})
      }
      this.headerTitle = ''
      this.tmDisplay = false
    },
    //删除显示字段
    removeNode(node, data) {
      if (!data) {
        this.$message({
          message: '请先选择操作节点',
          type: 'warning',
        })
        return
      }
      if (data.children && data.children.length > 0) {
        this.$message.warning('有下级不能删除,下级有字段则先移动')
        return
      }
      if (data.fieldName) {
        this.$message.warning('只能删除多级表头')
        return
      }
      this.$confirm(`是否删除${this.currentData.fieldDesc}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const parent = node.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(
            (d) => d.fieldDesc === data.fieldDesc
          )
          children.splice(index, 1)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    /**
     * 改变树状数据时
     * @param value
     */
    changeDesc(value) {
      this.$set(this.currentData, 'desc', value)
    },
  },
}
</script>

<style lang="scss" scoped>
/deep/ .dialog-container {
  overflow-y: hidden;

  .el-dialog__header {
    border-bottom: 1px solid #a9a9a9;
  }

  .el-dialog__body {
    padding-top: 0px;
    height: calc(100% - 63px);
  }
  .el-tabs {
    .el-tabs__content {
      height: calc(100% - 54px);
      overflow-y: auto;
      .el-card__body {
        height: calc(100% - 154px);
      }
      &::-webkit-scrollbar {
        width: 0;
        background-color: transparent;
      }
    }
  }

  .tree_menu {
    position: fixed;
    display: block;
    z-index: 20000;
    background-color: #fff;
    padding: 5px 0;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    ul {
      margin: 0;
      padding: 0;
    }
    ul li {
      list-style: none;
      margin: 0;
      padding: 0 15px;
      font-size: 14px;
      line-height: 30px;
      cursor: pointer;
    }
    ul li:hover {
      background-color: #ebeef5;
    }
  }
}
</style>
