<!-- @desc:新建编辑自定义报表  @auth:周兴  @time:2023/3/26 15:00 -->
<template>
  <div class="main-div" ref="mainDiv">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <div class="tab-fixed-class">
      <!--  选择tab区域  -->
      <DkTabs :options="tabsOptions" @on-click="changeElTabs"></DkTabs>
    </div>
    <DkPageButton :total="editKeys?editKeys.length:0"
                  :current="editIndex"
                  v-if="editKeys && editKeys.length > 1"
                  @pageChange="editPageChange"></DkPageButton>

    <DkCollapse>
      <!--为了补缺tab区域fixed-->
      <div id="name1" style="height: 30px;"></div>
      <!--基本信息-->
      <DkPanel prop="essentialInformation" :show-click="true">
        <!--  下拉区域  -->
        <DkForm slot="content" ref="formInline" v-model="formData" style="width: 100%">
          <!--报表名称-->
          <DkFormItem :required="true" prop="reportName" :span="12">
            <InputPop ref="reportName" v-model="formData.reportName"/>
          </DkFormItem>
          <!--用户-->
          <DkFormItem prop="userIds" :data-type="$config.dataType.number" :label="$t('userName')">
            <SelectMagnifier v-model="formData.userIds" :display-text="formData.userNames"
                             :type="this.$config.MagnifierType.user"
                             :multiple="true"></SelectMagnifier>
          </DkFormItem>
          <!--报表类型-->
          <DkFormItem prop="reportType" :required="true" :data-type="this.$config.dataType.number">
            <SelectPop v-model="formData.reportType" :multiple="false" :options="reportTypeList" ref="reportType"
                       @on-select="onChange"
                       labelKey="reportTypeName"
                       valueKey="reportType">
            </SelectPop>
          </DkFormItem>
          <!--   父级菜单  -->
          <DkFormItem prop="parentUuid" v-if="!flgPageReadonly" :required="!flgPageReadonly">
            <SelectPop v-model="formData.parentUuid" :multiple="false" :options="parentUuidList" ref="parentUuid"
                       labelKey="menuName"
                       valueKey="menuUuid">
            </SelectPop>
          </DkFormItem>
          <!--   显示顺序  -->
          <DkFormItem prop="displayNo" :data-type="$config.dataType.number" :required="true">
            <InputNumberPop v-model="formData.displayNo" :digits=0 :min="0"/>
          </DkFormItem>
          <!--          &lt;!&ndash;是否分页&ndash;&gt;-->
          <!--          <DkFormItem prop="flgPage">-->
          <!--            <DkSwitch ref="flgPage" v-model="formData.flgPage" :disabled="flgPageReadonly"/>-->
          <!--          </DkFormItem>-->
          <!--空行-->
          <DkFormItem prop="" :span="6">
          </DkFormItem>
          <!--报表描述-->
          <DkFormItem prop="describe" :span="12">
            <InputPop ref="describe" v-model="formData.describe" :textarea-flag="true"/>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks" :span="12">
            <InputPop ref="remarks" v-model="formData.remarks" :textarea-flag="true"/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--查询条件设置-->
      <DkPanel id="name2" prop="conditionInformation" :show-click="true">
        <EditTable slot="content" v-if="flgShowConditionTable"
                   ref="conditionTable" :data="conditionData"
                   :columns="formData.reportType == $config.reportType.app ? conditionColumns_app : conditionColumns"
                   :height="conditionTableHeight"
                   :show-setting-flag="false"
                   :freeze="false"
                   :auto-focus="false"
                   control-id="kind"
                   majorField="conditionId"
                   @changeValue="changeValue"
                   @chooseData="chooseType"
                   @clear-select="clearType"
                   @cell-click="handleCellClick"
                   @button-click="handleButtonClick"></EditTable>
      </DkPanel>
      <!--sql文-->
      <DkPanel id="name3" prop="sqlInformation" :show-click="true">
        <div slot="content">
          <div style="display: flex">
            <DkTabs :options="sqlTabsOptions" v-model="sqlTab" :edit-flag="true" :draggable="true" :closable="true"
                    @on-click="handleChangeSqlTab" @on-tab-remove="handleTabRemove"></DkTabs>
            <DkButton style="align-items: center;height: 30px;" size="small" @click="addSqlTab">
              <Icon type="md-add"/>
            </DkButton>
          </div>
          <DkSplit :height="tableHeight + 50" style="margin-top: 5px;">
            <div slot="left">
              <InputPop class="sql-class" v-model="sqlTabsOptions[sqlIndex].sqlScript" textareaFlag
                        :clearable="false"
                        maxlength="100000000"
                        :area-rows="15"/>
            </div>
            <div slot="right">
              <div style="padding-bottom: 5px;display: flex">
                <DkButton style="margin-right: 5px" @click="handleSql">{{ '获取列' }}</DkButton>
                <DkButton @click="addParentColumn">{{ '增加父级' }}</DkButton>
              </div>
              <EditTable ref="tableSetting" :data="sqlTabsOptions[sqlIndex].tableSettingList"
                         :columns="tableColumns"
                         :height="tableHeight + 10"
                         :show-setting-flag="false"
                         :freeze="false"
                         :auto-focus="false"
                         @chooseData="chooseDataType"
                         @clear-select="clearDataType"
                         @addRow="addTableSettingRow"
                         @delRow="delTableSettingRow"
                         @button-click="handleSettingNumber"></EditTable>
            </div>
          </DkSplit>
          <DkForm ref="formInline_change" v-model="sqlTabsOptions[sqlIndex]"
                  style="width: 100%;padding-bottom: 70px" :label-max-words="5">
            <!--跳转条件-->
            <DkFormItem prop="changeScript" :span="12">
              <InputPop ref="changeScript" v-model="sqlTabsOptions[sqlIndex].changeScript" :upper-flag="false"/>
            </DkFormItem>
            <!--跳转页签-->
            <DkFormItem prop="changeTabName" :span="12">
              <SelectPop v-model="sqlTabsOptions[sqlIndex].changeTabName" :multiple="false"
                         :options="sqlTabsOptions.filter((it,index)=>index != sqlIndex)" ref="changeTabName"
                         @on-select="onChange"
                         labelKey="label"
                         valueKey="name">
              </SelectPop>
            </DkFormItem>
            <!--小计列-->
            <DkFormItem prop="subTotals" :span="12">
              <InputPop ref="subTotals" v-model="sqlTabsOptions[sqlIndex].subTotals" :upper-flag="false"/>
            </DkFormItem>
            <!--需要进行小计的列-->
            <DkFormItem prop="subTotalDataKeys" :span="12">
              <InputPop ref="subTotalDataKeys" v-model="sqlTabsOptions[sqlIndex].subTotalDataKeys" :upper-flag="false"/>
            </DkFormItem>
            <!--是否分页-->
            <DkFormItem prop="flgPage">
              <DkSwitch ref="flgPage" v-model="sqlTabsOptions[sqlIndex].flgPage" :disabled="flgPageReadonly"/>
            </DkFormItem>
            <!--是否存储过程-->
            <DkFormItem prop="flgProc">
              <DkSwitch ref="flgProc" v-model="sqlTabsOptions[sqlIndex].flgProc" />
            </DkFormItem>
            <!--是否动态列-->
            <DkFormItem prop="flgDynamicCol">
              <DkSwitch ref="flgDynamicCol" v-model="sqlTabsOptions[sqlIndex].flgDynamicCol" />
            </DkFormItem>
          </DkForm>
        </div>
      </DkPanel>
    </DkCollapse>

    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save" @close="close"></DkSaveButton>

    <!--输入sql文-->
    <DkModal
      :loading="loading"
      v-model="sqlModal"
      ref="modal_sql"
      @on-visible-change="handleVisibleModal"
      @modalOk="modalOk"
      :title="$t('sql')"
    >
      <div style="padding-left: 10px;">
        <InputPop v-model="sqlScriptPop" textareaFlag :area-rows="10"/>
      </div>
    </DkModal>

    <!--设置数值格式-->
    <DkModal
      :loading="loading"
      v-model="settingNumberModal"
      ref="modal_number"
      @on-visible-change="handleVisibleNumberModal"
      @modalOk="settingNumberOk"
      :title="$t('settingType')"
    >
      <DkForm ref="formInline" v-model="formDataNumber" :col-count="2">
        <!--列宽-->
        <DkFormItem prop="width">
          <InputNumberPop v-model="formDataNumber.width" :digits="0" :min="0" :max="300"/>
        </DkFormItem>
        <!--对齐方式-->
        <DkFormItem prop="align">
          <SelectPop v-model="formDataNumber.align" :multiple="false" :options="alignList" ref="align"
                     labelKey="name"
                     valueKey="value">
          </SelectPop>
        </DkFormItem>
        <!--小数位数-->
        <DkFormItem prop="digits">
          <InputNumberPop v-model="formDataNumber.digits" :digits="0" :min="0" :max="6"/>
        </DkFormItem>
        <!--是否千分位-->
        <DkFormItem prop="flgThousandth">
          <DkSwitch v-model="formDataNumber.flgThousandth"/>
        </DkFormItem>
        <!--是否合计-->
        <DkFormItem prop="flgSum">
          <DkSwitch v-model="formDataNumber.flgSum"/>
        </DkFormItem>
        <!--是否显示-->
        <DkFormItem prop="flgVisible">
          <DkSwitch v-model="formDataNumber.flgVisible"/>
        </DkFormItem>
        <!--是否是链接-->
        <DkFormItem prop="flgLink">
          <DkSwitch v-model="formDataNumber.flgLink"/>
        </DkFormItem>
        <!--跳转的页签-->
        <DkFormItem prop="changeTabName" :required="formDataNumber.flgLink" v-if="formDataNumber.flgLink">
          <InputPop v-model="formDataNumber.changeTabName"/>
        </DkFormItem>
      </DkForm>
    </DkModal>

    <!--设置查询树形显示-->
    <DkModal
      :loading="loading"
      v-model="settingSelectModal"
      ref="modal_select"
      @on-visible-change="handleVisibleSelectModal"
      @modalOk="settingSelectOk"
      :title="$t('settingSelectType')"
    >
      <DkForm ref="formInline" v-model="formDataSelect" :col-count="2">
        <!--是否树形-->
        <DkFormItem prop="flgTree">
          <DkSwitch v-model="formDataSelect.flgTree" @on-change="handleFreeChange"/>
        </DkFormItem>
        <!--是否是严格模式-->
        <DkFormItem prop="flgTreeStrict">
          <DkSwitch v-model="formDataSelect.flgTreeStrict"/>
        </DkFormItem>
      </DkForm>
    </DkModal>

    <!--设置日期范围的默认值-->
    <DkModal
      :loading="loading"
      v-model="settingDateRangeDefaultModal"
      ref="modal_select"
      @on-visible-change="handleVisibleDefaultModal"
      @modalOk="settingDefaultOk"
      :title="$t('settingSelectType')"
    >
      <DkForm ref="formInline" v-model="formDataDefault" :col-count="1" :label-max-words="2"
              style="margin: 10px 10px 0 10px " :style="{'margin-bottom':(formDataDefault.rangeSel === -1?'0':'10px')}">
        <!--类型-->
        <DkFormItem prop="rangeSel">
          <SelectPop v-model="formDataDefault.rangeSel" :multiple="false" :options="rangeSelList" ref="rangeSel"
                     labelKey="label"
                     valueKey="value"
                     @on-select-label="handleSelectRange">
          </SelectPop>
        </DkFormItem>
      </DkForm>
      <!--间隔-->
      <div style="display: flex;align-items: center;margin: 5px 10px 10px 10px;width: 100%;"
           v-if="formDataDefault.rangeSel === -1">
        <div style="margin-left: 10px">{{ $t('interval') }}</div>
        <div style="display: flex;justify-content: space-between;width: 404px">
          <div style="display: flex;align-items: center">
            <div style="width: 150px;margin-left: 8px;margin-right: 2px">
              <InputNumberPop v-model="formDataDefault.intervalMonth" :clearable="false"/>
            </div>
            <div>{{ $t('month') }}</div>
          </div>
          <div style="display: flex;align-items: center" v-if="formDataDefault.kind !== $config.reportKind.month">
            <div style="width: 150px;margin-left: 10px;margin-right: 2px">
              <InputNumberPop v-model="formDataDefault.intervalDay" :clearable="false"/>
            </div>
            <div>{{ $t('day') }}</div>
          </div>
        </div>
      </div>
    </DkModal>

    <!--错误信息-->
    <DkModal
      :loading="loading"
      v-model="errorModal"
      ref="modal_error"
      :footerFlag="false"
      :title="$t('errorMsg')"
    >
      <div style="padding-left: 10px;">
        <InputPop v-model="errorMsg" textareaFlag :readonly="true" :area-rows="20"/>
      </div>
    </DkModal>
  </div>
</template>

<script>
import {formMixin} from "@/mixins/form";

export default {
  name: "report-form",
  mixins: [formMixin],
  data() {
    let self = this
    return {
      handleSqlFlag: false,
      sqlModal: false,
      errorModal: false,
      settingNumberModal: false,
      settingSelectModal: false,
      settingDateRangeDefaultModal: false,
      settingLinkModal: false,
      errorMsg: null,  // 错误提示信息
      formData: {
        flgPage: false,// 是否分页
        userIds: null,// 用户
        userNames: '',// 用户名称
        reportName: '',// 报表名称
        reportType: self.$config.reportType.pc,
        parentUuid: '',
        displayNo: 0,
        sqlScript: '',// 报表sql
        describe: '',// 报表描述
        remarks: '',  // 备注
      },
      formDataNumber: {
        index: 0,    // 记录是有那行点击过来的
        digits: 0,   // 小数位数
        flgThousandth: false,  // 千分位
        flgSum: false,  // 合计
        align: self.$config.align.left, // 对齐方式，默认居左
        width: 120,// 列宽
        flgLink: false, // 是否是链接
        changeTabName: null, // 跳转页签
        flgVisible: true, // 是否显示
      },
      formDataSelect: {
        flgTree: false,  // 是否是树形
        flgTreeStrict: false,  // 是否是严格模式
      },
      formDataDefault: {
        kind: null,// 类型
        index: 0,    // 记录是有那行点击过来的
        rangeSel: self.$config.rangeSel.today.value,
        rangeSelLabel: self.$config.rangeSel.today.label,
        intervalMonth: null,
        intervalDay: null,
      },
      tableHeight: 300,
      conditionTableHeight: 300,
      unitList: [],    // 单位
      rangeSelList: self.$config.rangeSelList, // 查询条件（日期范围）类型
      sqlScriptPop: '',// 下拉的sql文
      kindList: [],  // 种类
      parentUuidList: [],//
      // 报表类型
      reportTypeList: [
        {reportType: self.$config.reportType.pc, reportTypeName: self.$config.reportTypeName.pc},
        {reportType: self.$config.reportType.app, reportTypeName: self.$config.reportTypeName.app}
      ],
      flgPageReadonly: false, // 分页是否只读
      positionList: [
        {position: self.$config.position.mainSearch, positionName: self.$config.positionName.mainSearch},
        {position: self.$config.position.secondarySearch, positionName: self.$config.positionName.secondarySearch}
      ], // 所在位置数据源
      alignList: self.$config.alignList,  // 对齐方式数据源
      dataTypeList: self.$config.dataTypeList,// 数据类型数据源
      pIndex: 0,// 父级列的序号
      sqlTab: 'sql0',
      sqlTabsOptions: [
        {
          visible: true,
          label: 'Sql设置',
          name: 'sql0',
          changeScript: '',
          changeTabName: '',
          sqlScript: '',
          tableSettingList: [],
          flgVisible: true,
          flgPage:true,
          flgProc:false,
          flgDynamicCol:false,
          subTotals: '',
          subTotalDataKeys: ''
        }
      ],
      sqlScript: '',  // sql文
      sqlIndex: 0,// sql序号
      //画面模式选项
      tabsOptions: [
        {label: '基本信息', name: 'name1'},
        {label: '查询条件设置', name: 'name2'},
        {label: 'SQL设置', name: 'name3'},
      ],
      flgShowConditionTable: true, // 查询条件列表展示顺序
      // 查询条件列
      conditionColumns: [
        // 类型
        {
          field: 'kind',
          type: 'select',
          controlId: 'kind',
          options: () => self.kindList,
          labelKey: 'kindLabel',
          valueKey: 'kindName',
          title: self.$t('reportKind'),
          width: '90px'
        },
        // 编码
        {field: 'code', type: 'text', width: '150px', upperFlag: false},
        // 名称
        {field: 'name', type: 'text', width: '150px', upperFlag: false},
        // 必须输入性
        {field: 'flgRequired', type: 'switch', width: '100px', value: false},
        // 默认值
        {field: 'defaultValue', type: 'text', width: '100px'},
        // 其他条件
        {field: 'otherCondition', type: 'text', width: '100px', upperFlag: false},
        // sql文
        {field: 'sqlScript', type: 'button', width: '200px'},
        // 树形
        {field: 'settingSelectType', type: 'button', width: '100px'},
        // 备注
        {field: 'remarks', type: 'text', width: 'auto'},
      ],
      conditionColumns_app: [
        // 类型
        {
          field: 'kind',
          type: 'select',
          controlId: 'kind',
          options: () => self.kindList,
          labelKey: 'kindLabel',
          valueKey: 'kindName',
          title: self.$t('reportKind'),
          width: '90px'
        },
        // 编码
        {field: 'code', type: 'text', width: '150px', upperFlag: false},
        // 名称
        {field: 'name', type: 'text', width: '150px', upperFlag: false},
        // 必须输入性
        {field: 'flgRequired', type: 'switch', width: '100px', value: false},
        // 默认值
        {field: 'defaultValue', type: 'text', width: '100px'},
        // 其他条件
        {field: 'otherCondition', type: 'text', width: '100px', upperFlag: false},
        // 位置
        {
          field: 'position',
          type: 'select',
          options: () => self.positionList,
          labelKey: 'positionName',
          valueKey: 'position',
          title: self.$t('position'),
          width: '200px'
        },
        // sql文
        {field: 'sqlScript', type: 'button', width: '200px'},
        // 备注
        {field: 'remarks', type: 'text', width: 'auto'},
      ],
      // 表格设置
      tableColumns: [
        // 编码
        {field: 'code', type: 'text', width: '150px', upperFlag: false},
        // 名称
        {field: 'name', type: 'text', width: '150px', upperFlag: false},
        // 是否显示
        // {field: 'flgVisible', type: 'switch', width: '80px', default: true},
        // 数据类型
        {
          field: 'dataType',
          type: 'select',
          options: () => self.dataTypeList,
          labelKey: 'name',
          valueKey: 'value',
          value: self.$config.dataType.str,
          width: '90px'
        },
        // // 列宽
        // {field: 'width', type: 'number', width: '90px', value: '150'},
        // // 对齐方式
        // {
        //   field: 'align',
        //   type: 'select',
        //   options: () => self.alignList,
        //   labelKey: 'name',
        //   valueKey: 'value',
        //   value: self.$config.align.left,
        //   width: '90px'
        // },
        // 设置格式
        {field: 'settingType', type: 'button', width: '120px'},
        // // 小数位数
        // {field: 'digits', type: 'number', width: '100px', max: 6},
        // // 是否千分位显示
        // {field: 'flgThousandth', type: 'switch', width: '100px', value: false},
      ],
      conditionData: [],
      currentRow: null,
      tab0: true,
      tab1: true,
      tab2: true
    }
  },
  methods: {
    // region 表格处理
    /**
     * @desc   : 数值设置界面关闭时清理下form表单
     * @author : 周兴
     * @date   : 2023/4/26 14:20
     */
    handleVisibleNumberModal(e) {
      if (!e) {
        this.formDataNumber = {
          index: 0,    // 记录是有那行点击过来的
          digits: 0,   // 小数位数
          flgThousandth: false,  // 千分位
          flgSum: false,  // 合计
          flgVisible: true,// 显示
          flgLink: false,// 链接
          changeTabName: null,// 跳转页签
          width: 120,
          align: this.$config.align.left,
        }
      }
    },
    /**
     * @desc   : 链接设置界面关闭后清理form表单
     * @author : 周兴
     * @date   : 2023/4/28 9:48
     */
    handleVisibleLinkModal(e) {
      if (!e) {
        this.formDataLink = {
          changeTabName: null
        }
      }
    },
    /**
     * @desc   : 下拉设置界面关闭时清理下form表单
     * @author : 周兴
     * @date   : 2023/4/26 14:20
     */
    handleVisibleSelectModal(e) {
      if (!e) {
        this.formDataSelect = {
          flgTree: false,  // 是否是树形
          flgTreeStrict: false,  // 是否是严格模式
        }
      }
    },
    /**
     * @desc   : 日期范围设置后关闭清理下form表单
     * @author : 周兴
     * @date   : 2023/5/16 16:43
     */
    handleVisibleDefaultModal(e) {
      if (!e) {
        this.formDataDefault = {
          index: 0,    // 记录是有那行点击过来的
          rangeSel: 1,
          intervalMonth: null,
          intervalDay: null,
        }
      }
    },
    /**
     * @desc   : 开启树形结构
     * @author : 周兴
     * @date   : 2023/4/24 12:58
     */
    handleFreeChange(e) {
      if (e) {
        // 开启树形，默认为严格模式
        this.formDataSelect.flgTreeStrict = true;
      }
    },
    /**
     * @desc   : 切换后记录sqlTab的序号
     * @author : 周兴
     * @date   : 2023/3/30 8:48
     */
    handleChangeSqlTab(val) {
      this.$nextTick(() => {
        this.sqlIndex = this.sqlTabsOptions.findIndex(it => it.name == val)
        console.log('bb', this.sqlIndex)
      })
    },
    /**
     * @desc   : 删除页签
     * @author : 周兴
     * @date   : 2023/4/26 10:24
     */
    handleTabRemove(e) {
      let tabIndex = this.sqlTabsOptions.findIndex(it => it.name === e.tab.name);
      if (tabIndex || tabIndex === 0) {
        this.sqlTabsOptions = this.sqlTabsOptions.filter((it, index) => index !== tabIndex);
        console.log('bbb', e.tab.name, tabIndex, this.sqlTabsOptions.length, this.sqlIndex)
        if (tabIndex >= this.sqlTabsOptions.length) {
          this.sqlIndex = this.sqlTabsOptions.length - 1;
        }
        if (this.sqlTabsOptions && this.sqlTabsOptions.length > 0 && this.sqlTabsOptions[this.sqlIndex]) {
          this.sqlTab = this.sqlTabsOptions[this.sqlIndex].name;
        }
      }
    },
    /**
     * @desc   : 添加sql Tab
     * @author : 周兴
     * @date   : 2023/3/29 20:19
     */
    addSqlTab() {
      let tab = this.sqlTabsOptions.filter(it => it.name).max();
      let max = tab.name.replace('sql', '')
      let name = 'sql' + (parseFloat(max) + 1);
      this.sqlTabsOptions.push({label: name, name: name, sqlScript: '', tableSettingList: []})
      this.sqlTab = name;
      this.handleChangeSqlTab(name); // 切换序号
    },
    /**
     * @desc   : 选择类型，控制sql按钮是否可用
     * @author : 周兴
     * @date   : 2023/3/27 14:49
     */
    chooseType(row) {
      this.setConditionRowReadOnly(row);  // 设置行的只读
    },
    /**
     * @desc   : 值改变
     * @author : 姜宁
     * @date   : 2023/4/6 15:42
     */
    changeValue(field, row, rowIndex, val) {
      // 如果必输，则所在位置必field须为主查询
      if (field === 'flgRequired') {
        if (row[field]) {
          row['position'] = this.$config.position.mainSearch
          row['position_Name'] = this.$config.positionName.mainSearch
        }
      }
      this.setConditionRowReadOnly(row);  // 设置行的只读
    },
    /**
     * @desc   : 清空类型
     * @author : 周兴
     * @date   : 2023/3/27 16:34
     */
    clearType(e) {
      this.setConditionRowReadOnly(e.row);  // 设置行的只读
    },
    /**
     * @desc   : 单击单元格
     * @author : 周兴
     * @date   : 2023/5/16 9:34
     */
    handleCellClick(e) {
      // 如果是日期多选打开设置界面
      if (e.$event.pointerType === 'mouse' && e.column.field === 'defaultValue' && e.row
        && (e.row.kind === this.$config.reportKind.dateRange
          || e.row.kind === this.$config.reportKind.dateTimeRange
          || e.row.kind === this.$config.reportKind.month
          || e.row.kind === this.$config.reportKind.monthRange)) {
        // 月份用月份的数据源
        if (e.row.kind === this.$config.reportKind.month || e.row.kind === this.$config.reportKind.monthRange) {
          this.rangeSelList = this.$config.rangeSelMonthList;
        }
        this.settingDateRangeDefaultModal = true;
        if (e.row['defaultValue_Info']) {
          this.formDataDefault = {...e.row['defaultValue_Info']}
        }
        this.formDataDefault.kind = e.row.kind;
        this.formDataDefault.index = e.rowIndex;
      }
    },
    /**
     * @desc   : 设置行只读
     * @author : 周兴
     * @date   : 2023/3/27 16:34
     */
    setConditionRowReadOnly(row) {
      if (row['kind'] !== this.$config.reportKind.single &&
        row['kind'] !== this.$config.reportKind.multiple) {
        if (row['flgRequired']) {
          this.$set(row, 'readOnly', ['sqlScript', 'position'])
        } else {
          this.$set(row, 'readOnly', ['sqlScript'])
        }
        // 清空数据
        this.$set(row, 'sqlScript', null)
      } else {
        if (row['flgRequired']) {
          this.$set(row, 'readOnly', ['position'])
        } else {
          this.$set(row, 'readOnly', null)
        }
      }
    },
    /**
     * @desc   : 选择数据类型，控制千分位和小数位数是否可用
     * @author : 周兴
     * @date   : 2023/3/27 14:49
     */
    chooseDataType(row) {
      this.setTableSettingRowReadOnly(row);  // 设置行的只读
    },
    /**
     * @desc   : 清空数据类型
     * @author : 周兴
     * @date   : 2023/3/27 16:34
     */
    clearDataType(e) {
      this.setTableSettingRowReadOnly(e.row);  // 设置行的只读
    },
    /**
     * @desc   : desc
     * @author : 周兴
     * @date   : 2023/3/27 16:23
     */
    addTableSettingRow(rowIndex) {
      this.$nextTick(() => {
        let row = this.$refs['tableSetting'].tableData[rowIndex ? rowIndex : 0];
        if (row) {
          this.setTableSettingRowReadOnly(row);  // 设置行的只读
        }
      })
    },
    /**
     * @desc   : 删除行
     * @author : 周兴
     * @date   : 2023/3/30 15:48
     */
    delTableSettingRow(row, rowIndex) {
      if (this.sqlTabsOptions[this.sqlIndex]) {
        let list = this.sqlTabsOptions[this.sqlIndex].tableSettingList;
        this.sqlTabsOptions[this.sqlIndex].tableSettingList = list.filter((it, index) => index != rowIndex);
      }
    },
    /**
     * @desc   : 设置行只读
     * @author : 周兴
     * @date   : 2023/3/27 16:34
     */
    setTableSettingRowReadOnly(row) {
      // if (row['dataType'] !== this.$config.dataType.number) {
      //   this.$set(row, 'readOnly', ['digits', 'flgThousandth'])
      //   // 清空数据
      //   this.$set(row, 'digits', null)
      //   this.$set(row, 'flgThousandth', false)
      // } else {
      //   // 小数位数默认为0，千分位默认开启
      //   this.$set(row, 'digits', 0)
      //   this.$set(row, 'flgThousandth', true)
      //   this.$set(row, 'readOnly', null)
      // }
      this.$set(row, 'settingType', this.$t('searchSet'))
    },
    /**
     * @desc   : 点击按钮
     * @author : 周兴
     * @date   : 2023/3/26 16:26
     */
    handleButtonClick(row, rowIndex, colItem) {
      this.currentRow = row;
      // sql
      if (colItem.field === 'sqlScript') {
        this.sqlScriptPop = row[colItem.field]
        this.sqlModal = true;
      } else if (colItem.field === 'settingSelectType') {
        // 只有下拉才会有树形
        if (row.kind && (row.kind === this.$config.reportKind.single
          || row.kind === this.$config.reportKind.multiple)) {
          // 如果已经存在 说明已经保存了
          if (row['settingSelectType_info']) {
            this.formDataSelect = {...row['settingSelectType_info']}
          }
          this.formDataSelect.index = rowIndex;
          this.settingSelectModal = true;
        }
      }
    },
    /**
     * @desc   : 输入完后确认
     * @author : 周兴
     * @date   : 2023/3/26 16:42
     */
    modalOk() {
      if (this.currentRow) {
        let sqlScript = this.sqlScriptPop.trim();
        if (sqlScript) {
          // 不允许有 update、insert、delete、create、alter、GRANT、REVOKE
          let sqlScriptTemp = sqlScript.toLowerCase();
          if (sqlScriptTemp.indexOf('update') >= 0 || sqlScriptTemp.indexOf('insert') >= 0 ||
            sqlScriptTemp.indexOf('delete') >= 0 || sqlScriptTemp.indexOf('create') >= 0 ||
            sqlScriptTemp.indexOf('alter') >= 0 || sqlScriptTemp.indexOf('GRANT') >= 0 ||
            sqlScriptTemp.indexOf('REVOKE') >= 0) {
            this.$Message.warning(this.$t('sqlErr'))
            return
          }
          this.$set(this.currentRow, 'sqlScript', sqlScript)
          // 校验sql是否合法
          this.excuteSql(sqlScript).then(t => {
            if (t.code != this.$config.SUCCESS_CODE) {
              // 如果不成功就提示错误信息
              this.errorMsg = t.exception;
              this.errorModal = true;
            } else {
              this.sqlScriptPop = null;
              this.sqlModal = false;
            }
          });
        } else {
          this.$set(this.currentRow, 'sqlScript', null)
          this.sqlScriptPop = null;
          this.sqlModal = false;
        }
      }
    },
    /**
     * @desc   : 设置下拉格式
     * @author : 周兴
     * @date   : 2023/3/31 8:57
     */
    settingSelectOk() {
      let table = this.$refs['conditionTable'].tableData;
      let index = this.formDataSelect.index;
      if (table && table[index]) {
        let row = table[index]
        let keys = Object.keys(this.formDataSelect)
        let info = []
        keys.forEach(it => {
          if (it != 'index') {
            let item = this.$t(it) + ':' + this.formDataSelect[it];
            info.push(item)
          }
        })
        // 用于显示
        this.$set(row, 'settingSelectType', info.join(','))
        // 用于记录实体，便于来回编辑使用
        this.$set(row, 'settingSelectType_info', {...this.formDataSelect})
        // 用于后台保存
        this.$set(row, 'flgTree', this.formDataSelect.flgTree)
        this.$set(row, 'flgTreeStrict', this.formDataSelect.flgTreeStrict)
      }
      this.settingSelectModal = false;
    },
    /**
     * @desc   : 赋值
     * @author : 周兴
     * @date   : 2023/5/16 17:02
     */
    handleSelectRange(row) {
      if (row) {
        this.formDataDefault.rangeSelLabel = row.label
      } else {
        this.formDataDefault.rangeSelLabel = null
      }
    },
    /**
     * @desc   : 设置日期范围的默认值
     * @author : 周兴
     * @date   : 2023/5/16 16:45
     */
    settingDefaultOk() {
      let table = this.$refs['conditionTable'].tableData;
      let index = this.formDataDefault.index;
      if (table && table[index]) {
        let row = table[index]
        // 用于显示
        this.$set(row, 'defaultValue', this.formDataDefault.rangeSelLabel)
        this.$set(row, 'defaultValue_Info', this.formDataDefault)
      }
      this.settingDateRangeDefaultModal = false;
    },
    /**
     * @desc   : 设置数值格式
     * @author : 周兴
     * @date   : 2023/4/24 13:00
     */
    settingNumberOk() {
      let table = this.$refs['tableSetting'].tableData;
      let index = this.formDataNumber.index;
      if (table && table[index]) {
        let row = table[index]
        // let keys = Object.keys(this.formDataNumber)
        // let info = []
        // keys.forEach(it => {
        //   if (it != 'index') {
        //     let item = this.$t(it) + ':' + this.formDataNumber[it];
        //     info.push(item)
        //   }
        // })
        // // 用于显示
        // this.$set(row, 'settingNumberType', info.join(','))
        // 用于记录实体，便于来回编辑使用
        this.$set(row, 'settingType_info', {...this.formDataNumber})
        // 用于后台保存
        this.$set(row, 'digits', this.formDataNumber.digits)
        this.$set(row, 'flgThousandth', this.formDataNumber.flgThousandth)
        this.$set(row, 'flgSum', this.formDataNumber.flgSum)
        this.$set(row, 'width', this.formDataNumber.width)
        this.$set(row, 'align', this.formDataNumber.align)
        this.$set(row, 'flgVisible', this.formDataNumber.flgVisible)
        this.$set(row, 'flgLink', this.formDataNumber.flgLink)
        this.$set(row, 'changeTabName', this.formDataNumber.changeTabName)
      }
      this.settingNumberModal = false;
    },
    /**
     * @desc   : 设置链接格式
     * @author : 周兴
     * @date   : 2023/4/28 10:13
     */
    settingLinkOk() {
      let table = this.$refs['tableSetting'].tableData;
      let index = this.formDataLink.index;
      if (table && table[index]) {
        let row = table[index]
        let keys = Object.keys(this.formDataLink)
        let info = []
        keys.forEach(it => {
          if (it != 'index') {
            let item = this.$t(it) + ':' + this.formDataLink[it];
            info.push(item)
          }
        })
        // 用于显示
        this.$set(row, 'settingLinkType', info.join(','))
        // 用于记录实体，便于来回编辑使用
        this.$set(row, 'settingLinkType_info', {...this.formDataLink})
        // 用于后台保存
        this.$set(row, 'changeTabName', this.formDataLink.changeTabName)
      }
      this.settingLinkModal = false;
    },
    /**
     * @desc   : 设置数值格式
     * @author : 周兴
     * @date   : 2023/3/31 9:01
     */
    handleSettingNumber(row, rowIndex) {
      // 查看是否是数值类型 (不控制了)
      // if (row.dataType && row.dataType === this.$config.dataType.number) {
      //   // 如果已经存在 说明已经保存了
      //   if (row['settingNumberType_info']) {
      //     this.formDataNumber = {...row['settingNumberType_info']}
      //   }
      //   this.formDataNumber.index = rowIndex;
      //   this.settingNumberModal = true;
      // }
      // 如果已经存在 说明已经保存了
      if (row['settingType_info']) {
        this.formDataNumber = {...row['settingType_info']}
      }
      this.formDataNumber.index = rowIndex;
      this.settingNumberModal = true;
    },
    /**
     * @desc   : 增加父级列
     * @author : 周兴
     * @date   : 2023/3/26 17:25
     */
    addParentColumn() {
      const tableColumns = this.$refs['tableSetting'].$refs['xTable'].getTableColumn()
      if (tableColumns) {
        let columns = tableColumns.fullColumn
        // let col = {...columns[2]}
        let col = JSON.parse(JSON.stringify(columns[2]))
        this.pIndex++;
        col.field = 'parentCol_' + this.pIndex
        col.property = 'parentCol_' + this.pIndex
        col.title = '父列' + this.pIndex
        columns.push(col);
        console.log(columns)
        this.tableColumns.push({field: 'parentCol_' + this.pIndex, title: '父列' + this.pIndex, type: 'text', width: '150px', upperFlag: false})
        this.$refs['tableSetting'].initColumn();
        // 加载列
        // this.$refs['tableSetting'].$refs['xTable'].loadColumn(columns);
      }
    },
    /**
     * @desc   : 执行SQL
     * @author : 周兴
     * @date   : 2023/3/27 20:03
     */
    async handleSql() {
      // 校验
      let flag = await this.validDataItem();
      if (flag) {
        let sqlScript = this.handleSqlScript(this.sqlTabsOptions[this.sqlIndex]);
        let params = {
          sql: sqlScript
        }
        this.excute(this.$service.customReportService, this.$service.customReportService.excuteSql, params).then(res => {
          if (res.code === this.$config.SUCCESS_CODE) {
            this.$Message.success('SQL通过验证')
            // 获取列
            let data = this.getSqlField();
            // 如果有需要提示
            if (this.sqlTabsOptions[this.sqlIndex].tableSettingList
              && this.sqlTabsOptions[this.sqlIndex].tableSettingList.length > 0) {
              this.$IBMessage({
                  content: this.$t('Q_002', {'param': '刷新表格'}),
                  title: this.$t('systemQuestion')
                },
                {
                  ok: () => {
                    this.sqlTabsOptions[this.sqlIndex].tableSettingList = data;
                  },
                }
              )
            } else {
              this.sqlTabsOptions[this.sqlIndex].tableSettingList = data;
            }
          } else {
            // 如果不成功就提示错误信息
            this.errorMsg = res.exception;
            this.errorModal = true;
          }
        })
      }
    },
    /**
     * @desc   : 校验
     * @author : 周兴
     * @date   : 2023/3/28 8:29
     */
    validDataItem() {
      if (!this.sqlTabsOptions[this.sqlIndex].sqlScript) {
        this.$Message.warning(this.$t('W_042', {'param': this.$t('sqlScript')}))
        return false;
      }
      // 校验sql中是否有工厂Id作为条件
      if (this.sqlTabsOptions[this.sqlIndex].sqlScript.indexOf('#{ftyId}') < 0) {
        this.$Message.warning('SQL中不包括工厂Id')
        return false;
      }
      return true;
    },
    /**
     * @desc   : 获取sql中列
     * @author : 周兴
     * @date   : 2023/3/28 9:35
     */
    getSqlField() {
      if (!this.sqlTabsOptions[this.sqlIndex]) return [];
      let fieldList = []
      let sqlScript = this.sqlTabsOptions[this.sqlIndex].sqlScript;
      let sql = sqlScript.toLowerCase();
      let startIndex = sql.indexOf('select');
      let endIndex = sql.indexOf('from');
      if (startIndex >= 0 && endIndex >= 0) {
        let str = sqlScript.substring(startIndex + 6, endIndex);
        let fields = str.split(',')
        fields.forEach(it => {
          let tIt = it.toLowerCase(); // 转小写用于判断
          let item;
          if (tIt.indexOf('as') >= 0) {
            let index = tIt.indexOf('as');
            item = it.substring(index + 2).trim()
          } else if (tIt.indexOf(' ') >= 0) {
            item = it.trim().substring(it.trim().indexOf(' ')).trim()
          } else {
            item = it.trim();
          }
          // 去掉单引号、双引号
          item = item.replaceAll('\'', '').replaceAll('"', '')
          // 默认为文本格式，居左
          fieldList.push({
            flgVisible: true,
            code: item, dataType: this.$config.dataType.str,
            align: this.$config.align.left, width: 150, readOnly: ['digits', 'flgThousandth'],
            settingType: this.$t('searchSet')
          })
        })
      }
      return fieldList;
    },
    /**
     * @desc   : tabs切换事件
     * @author : 周兴
     * @date   : 2023/3/26 15:49
     */
    changeElTabs(e) {
      let name = e
      this.bottomList = ['1', '2', '3']
      window.location.href = '#' + name
    },
    /**
     * @desc   : 改变事件
     * @author : 姜宁
     * @date   : 2023/4/6 11:13
     */
    onChange(val) {
      this.flgShowConditionTable = false;
      if (val === this.$config.reportType.app) {
        this.flgPageReadonly = true;
        this.formData.flgPage = true;
      } else {
        this.flgPageReadonly = false;
        //this.formData.flgPage = false;
      }
      this.$nextTick(() => {
        this.flgShowConditionTable = true;
      })
    },
    // endregion

    // region 获取数据
    /**
     * @desc   : 获取基础数据
     * @author : 周兴
     * @date   : 2023/3/27 14:36
     */
    initData() {
      // 获取系统字典中的类型
      this.getKindList();
      // 获取菜单
      this.getMenuUuidList();
      if (this.type === this.$config.formMode.add) {
        // 加载最大序号
        this.getMaxDisplayNo(this.$config.displayNoTable.customReport);
      }
    },
    /**
     * @desc   : 获取菜单Id
     * @author : 周兴
     * @date   : 2023/4/20 17:58
     */
    getMenuUuidList() {
      this.excute(this.$service.commonService, this.$service.commonService.getMenuNavigation,
        {parentUuid: this.$config.reportMenuUUid}).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.parentUuidList = res.data
          // 新建才增加
          if (this.type === this.$config.formMode.add) {
            this.$nextTick(() => {
              this.formData.parentUuid = this.$config.customReportUuid
            })
          }
        }
      })
    },
    /**
     * @desc   : 获取种类
     * @author : 周兴
     * @date   : 2023/3/27 14:37
     */
    getKindList() {
      this.excute(this.$service.commonService, this.$service.commonService.getValueKind,
        {used: this.$config.customCondition}).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.kindList = res.data
        }
      })
    },
    /**
     * @desc   : 获取最大顺序号
     * @author : 姜宁
     * @date   : 2023/4/6 10:58
     */
    getMaxDisplayNo(displayNoTable, formDataName = null) {
      let params = {
        table: displayNoTable.model + "." + displayNoTable.table,
        ftyId: this.$store.state.user.ftyId
      }
      this.excute(this.$service.commonService, this.$service.commonService.getMaxDisplayNo, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          if (!formDataName) {
            this.formData.displayNo = res.data;
          } else {
            this[formDataName].displayNo = res.data;
          }
        }
      })
    },
    /**
     * @desc   : 通过id查询
     * @author : 周兴
     * @date   : 2023/3/29 17:01
     */
    detail(id) {
      let params = {
        reportId: id,
        ftyId: this.$store.state.user.ftyId,
        scriptFlag: true
      }
      return this.excute(this.$service.customReportService, this.$service.customReportService.selectByReport, params);
    },
    /**
     * @desc   : 编辑时给参数赋值
     * @author : 周兴
     * @date   : 2023/3/29 17:03
     */
    setValuesByEdit(data) {
      this.formData.reportId = data.reportId
      // 报表名称
      this.formData.reportName = data.reportName;
      // 用户
      this.formData.userIds = data.userIds;
      this.formData.userNames = data.userNames;
      // 报表类型
      this.formData.reportType = data.reportType;
      // 父级菜单
      this.formData.parentUuid = data.parentUuid;
      // 显示顺产
      this.formData.displayNo = data.displayNo;
      // 是否分页
      this.formData.flgPage = data.flgPage;
      // 描述
      this.formData.describe = data.describe
      this.formData.remarks = data.remarks;
      // 查询条件
      this.conditionData = data.conditionList;
      this.conditionData.forEach(it => {
        this.$set(it, 'kind_Name', it['kind'])
        this.$set(it, 'position_Name', it['positionName'])
        if (it.otherCondition) {
          this.$set(it, 'otherCondition', JSON.stringify(it.otherCondition))
        }
        // 设置默认值
        if (it.kind === this.$config.reportKind.dateRange
          || it.kind === this.$config.reportKind.dateTimeRange
          || it.kind === this.$config.reportKind.month
          || it.kind === this.$config.reportKind.monthRange) {
          if (it.defaultValue) {
            let defaultValue = it.defaultValue
            this.$set(it, 'defaultValue_Info', {...defaultValue})
            this.$set(it, 'defaultValue', defaultValue.rangeSelLabel)
          }
        } else {
          if (it.defaultValue && it.defaultValue.default) {
            it.defaultValue = it.defaultValue.default
          } else {
            it.defaultValue = ''
          }
        }
        //设置只读列
        this.setConditionRowReadOnly(it);
        // 下拉处理格式
        if (it.kind === this.$config.reportKind.single ||
          it.kind === this.$config.reportKind.multiple) {
          if (it.flgTree != null && it.flgTree != undefined) {
            let text = this.$t('flgTree') + ':' + it.flgTree + ',' +
              this.$t('flgTreeStrict') + ':' + it.flgTreeStrict;
            let formDataSelect = {
              flgTree: it.flgTree,
              flgTreeStrict: it.flgTreeStrict
            }
            // 用于显示
            this.$set(it, 'settingSelectType', text)
            // 用于数据处理
            this.$set(it, 'settingSelectType_info', formDataSelect)
          }
        }
      })
      // sql
      this.sqlTabsOptions = data.sqlList;
      // 设置数值格式
      this.sqlTabsOptions.forEach((it, index) => {
        if (index == 0) {
          this.sqlTab = it.name;
        }
        if (it.tableSettingList) {
          it.tableSettingList.forEach(item => {
            // if (item.dataType === this.$config.dataType.number) {
            // 显示数值类型格式（小数位数+千分位+合计
            // let text = this.$t('digits') + ':' + item.digits + ',' +
            //   this.$t('flgThousandth') + ':' + item.flgThousandth + ',' +
            //   this.$t('width') + ':' + item.width + ',' +
            //   this.$t('align') + ':' + item.align + ',' +
            //   this.$t('flgLink') + ':' + item.flgLink + ',' +
            //   this.$t('changeTabName') + ':' + item.changeTabName ;
            let formDataNumber = {
              digits: item.digits,
              flgThousandth: item.flgThousandth,
              flgSum: item.flgSum,
              flgLink: item.flgLink,
              width: item.width,
              align: item.align,
              changeTabName: item.changeTabName,
              flgVisible: item.flgVisible
            }
            // 用于显示
            this.$set(item, 'settingType', this.$t('searchSet'))
            // 用于数据处理
            this.$set(item, 'settingType_info', formDataNumber)
            // } else if (item.dataType === 'link') {  // 链接
            //   let text = this.$t('changeTabName') + ':' + item.changeTabName;
            //   // 用于显示
            //   this.$set(item, 'settingLinkType', text)
            //   // 用于数据处理
            //   this.$set(item, 'settingNumberType_info', {
            //     changeTabName: item.changeTabName
            //   })
            // }
          })
        }
      })
    },
    // endregion

    // region 校验、保存
    /**
     * @desc   : 校验
     * @author : 周兴
     * @date   : 2023/3/28 11:07
     */
    async validData() {
      // region 1、验证查询条件设置
      let conditionData = this.$refs['conditionTable'].getTableData();
      if (conditionData && conditionData.length > 0) {
        for (let i = 0; i < conditionData.length; i++) {
          let it = conditionData[i]
          // 先清空错误信息
          this.clearRowErr(it);
          // 类型必须输入
          if (!it.kind) {
            this.$Message.warning(this.$t('W_089', {'param1': (i + 1), 'param2': this.$t('reportType')}))
            this.setErrToRow(it, this.$t('W_042', {'param': this.$t('reportType')}))
            return false;
          }
          // 编码必须输入
          if (!it.code) {
            this.$Message.warning(this.$t('W_089', {'param1': (i + 1), 'param2': this.$t('code')}))
            this.setErrToRow(it, this.$t('W_042', {'param': this.$t('code')}))
            return false;
          }
          // 名称必须输入
          if (!it.name) {
            this.$Message.warning(this.$t('W_089', {'param1': (i + 1), 'param2': this.$t('name')}))
            this.setErrToRow(it, this.$t('W_042', {'param': this.$t('name')}))
            return false;
          }
          // 其他条件需要是JSON格式
          try {
            if (it.otherCondition) {
              JSON.parse(it.otherCondition);
            }
          } catch (e) {
            this.$Message.warning(this.$t('W_005', {'param': this.$t('otherCondition')}))
            return false;
          }
          // 下拉类型，数据源必须要设置
          if (it.kind === this.$config.reportKind.single ||
            it.kind === this.$config.reportKind.multiple) {
            // 如果数据源为空提示
            if (!it.sqlScript) {
              this.$Message.warning(this.$t('W_089', {'param1': (i + 1), 'param2': this.$t('sqlScript')}))
              this.setErrToRow(it, this.$t('W_042', {'param': this.$t('sqlScript')}))
              return false;
            } else {
              // 如果有sql，需要验证
              // 不允许有 update、insert、delete、create、alter、GRANT、REVOKE
              let sqlScript = it.sqlScript.toLowerCase();
              if (sqlScript.indexOf('update') >= 0 || sqlScript.indexOf('insert') >= 0 ||
                sqlScript.indexOf('delete') >= 0 || sqlScript.indexOf('create') >= 0 ||
                sqlScript.indexOf('alter') >= 0 || sqlScript.indexOf('grant') >= 0 ||
                sqlScript.indexOf('revoke') >= 0) {
                this.$Message.warning(this.$t('sqlErr'))
                return false;
              }
              await this.excuteSql(it.sqlScript).then(t => {
                if (t.code != this.$config.SUCCESS_CODE) {
                  // 如果不成功就提示错误信息
                  this.errorMsg = t.exception;
                  this.errorModal = true;
                  return false;
                }
              });
            }
          }
        }
      }
      // endregion
      // for (let i in this.sqlTabsOptions){
      let flag = true;
      let name = '';
      for (let i = 0; i < this.sqlTabsOptions.length; i++) {
        let sqlItem = this.sqlTabsOptions[i];
        name = sqlItem.name;
        // region 2、验证sql
        if (!sqlItem.sqlScript) {
          // 表格设置不能为空
          this.$Message.warning(this.$t('W_042', {'param': this.$t('sqlScript')}))
          flag = false;
          return false;
        }
        // 校验sql中是否有工厂Id作为条件
        if (sqlItem.sqlScript.indexOf('#{ftyId}') < 0) {
          this.$Message.warning('SQL中不包括工厂Id')
          flag = false;
          return false;
        }
        // 替换条件
        let sqlScript = this.handleSqlScript(sqlItem);
        // 验证sql
        await this.excuteSql(sqlScript).then(t => {
          if (t.code != this.$config.SUCCESS_CODE) {
            // 如果不成功就提示错误信息
            this.errorMsg = t.exception;
            this.errorModal = true;
            flag = false;
            return false;
          }
        });
        // endregion

        // region 3、验证表格设置
        let tableSettingData = sqlItem.tableSettingList;
        if (!tableSettingData || tableSettingData.length === 0) {
          tableSettingData = this.$refs['tableSetting'].getTableData();
          sqlItem.tableSettingList = tableSettingData;
        }
        if (!tableSettingData || tableSettingData.length === 0) {
          // 表格设置不能为空
          this.$Message.warning(this.$t('W_042', {'param': this.$t('tableSetting')}))
          flag = false;
          return false;
        }
        for (let i = 0; i < tableSettingData.length; i++) {
          let it = tableSettingData[i]
          // 先清空错误信息i
          this.clearRowErr(it);
          // 编码必须输入
          if (!it.code) {
            this.$Message.warning(this.$t('W_089', {'param1': (i + 1), 'param2': this.$t('code')}))
            this.setErrToRow(it, this.$t('W_042', {'param': this.$t('code')}))
            flag = false;
            return false;
          }
          // 名称必须输入
          if (!it.name) {
            this.$Message.warning(this.$t('W_089', {'param1': (i + 1), 'param2': this.$t('name')}))
            this.setErrToRow(it, this.$t('W_042', {'param': this.$t('name')}))
            flag = false;
            return false;
          }
        }
        // endregion
      }
      if (!flag) {
        this.sqlTab = name;
        return false;
      }
      return true;
    },
    /**
     * @desc   : 处理sql
     * @author : 周兴
     * @date   : 2023/3/30 13:20
     */
    handleSqlScript(sqlItem) {
      let sqlScript = sqlItem.sqlScript
      let conditionData = this.$refs['conditionTable'].getTableDataFilter();
      // 不用控制严格，只要有跳转条件，其他页签的都处理下的（兼容link模式）
      this.sqlTabsOptions.forEach((t, index) => {
        if (t.changeScript) {
          let changeScripts = t.changeScript.trim().split(',');
          this.sqlTabsOptions.forEach((item, itemNo) => {
            if (index != itemNo) {
              sqlScript = item.sqlScript
              sqlScript = sqlScript.replaceAll('#{ftyId}', -1)
              conditionData.forEach(t => {
                // 日期范围 月份范围 日时范围
                if (t.kind === this.$config.reportKind.dateRange
                  || t.kind === this.$config.reportKind.dateTimeRange
                  || t.kind === this.$config.reportKind.monthRange) {
                  sqlScript = sqlScript.replaceAll('#{' + t.code?.trim() + 'Start' + '}', null)
                  sqlScript = sqlScript.replaceAll('#{' + t.code?.trim() + 'End' + '}', null)
                } else {
                  sqlScript = sqlScript.replaceAll('#{' + t.code?.trim() + '}', null)
                }
              })
              changeScripts.forEach(it => {
                sqlScript = sqlScript.replaceAll('#{' + it + '}', null)
              })
            }
          })
        } else {
          conditionData.forEach(t => {
            // 日期范围 月份范围 日时范围
            if (t.kind === this.$config.reportKind.dateRange
              || t.kind === this.$config.reportKind.dateTimeRange
              || t.kind === this.$config.reportKind.monthRange) {
              sqlScript = sqlScript.replaceAll('#{' + t.code?.trim() + 'Start' + '}', null)
              sqlScript = sqlScript.replaceAll('#{' + t.code?.trim() + 'End' + '}', null)
            } else {
              sqlScript = sqlScript.replaceAll('#{' + t.code?.trim() + '}', null)
            }
          })
        }
      })
      // let filters = this.sqlTabsOptions.filter(it => it.changeTabName == sqlItem.name)
      // if (filters && filters.length > 0) {
      //   let changeScript = filters[0].changeScript.trim();
      //   // 说明是多个
      //   if (changeScript && changeScript.indexOf(',') >= 0) {
      //     let changeScripts = changeScript.split(',');
      //     changeScripts.forEach(it => {
      //       sqlScript = sqlScript.replaceAll('#{' + it + '}', null)
      //     })
      //   } else {
      //     sqlScript = sqlScript.replaceAll('#{' + changeScript + '}', null)
      //   }
      // }
      return sqlScript;
    },
    /**
     * @desc   : 给参数赋值
     * @author : 周兴
     * @date   : 2023/3/28 13:04
     */
    setParams() {
      let params = {...this.formData}
      params.displayNo = this.formData.displayNo;
      params.reportId = this.formData.reportId;
      params.reportType = this.formData.reportType;
      params.ftyId = this.$store.state.user.ftyId;
      // 移动端不需要设置父级菜单
      if (params.reportType === this.$config.reportType.app) {
        params.parentUuid = null;
      }
      if (this.type === this.$config.formMode.add) {
        // 新建才会赋值暂存
        params.reportStatus = this.$config.reportStatus.temp;
      }
      // 查询条件设置
      params.conditionList = this.$refs['conditionTable'].getTableDataFilter();
      params.conditionList.forEach((it, index) => {
        it.displayNo = index + 1;
        if (it.otherCondition) {
          it.otherCondition = JSON.parse(it.otherCondition)
        } else {
          it.otherCondition = null;
        }
        if (it.kind === this.$config.reportKind.dateRange
          || it.kind === this.$config.reportKind.dateTimeRange
          || it.kind === this.$config.reportKind.month
          || it.kind === this.$config.reportKind.monthRange) {
          if (it['defaultValue_Info'] && it['defaultValue_Info'].rangeSel) {
            it.defaultValue = {...it['defaultValue_Info']}
            delete it['defaultValue_Info']
          } else {
            it.defaultValue = null
          }
        } else {
          let value = it.defaultValue
          if (value) {
            it.defaultValue = {
              default: value
            }
          } else {
            it.defaultValue = null
          }
        }
      })
      // 记录查询条件删除掉的设置信息
      params.conditionDeleteList = this.$refs['conditionTable'].getDeleteData();
      if (params.conditionDeleteList && params.conditionDeleteList.length > 0) {
        params.conditionDeleteList.forEach(it => {
          // 默认值都置空
          it.defaultValue = null
        })
      }
      // sql
      params.sqlList = this.sqlTabsOptions.copy();
      let filters = null;
      params.sqlList.forEach((item, i) => {
        item.displayNo = i + 1;
        filters = this.sqlTabsOptions.filter(it => it.changeTabName === item.label);
        if (filters && filters.length > 0) {
          filters.forEach(it => {
            if (it.changeScript) {
              if (!item.changeScriptOthers) {
                item.changeScriptOthers = []
              }
              item.changeScriptOthers.pushNoRepeat(it.changeScript)
            }
          })
        }
        // 处理表格
        item.tableSettingList.forEach((it, index) => {
          // 统计在列表中的跳转页签
          if (it.changeTabName) {
            filters = params.sqlList.filter(t => t.label === it.changeTabName);
            if (filters && filters.length > 0) {
              if (!filters[0].changeScriptOthers) {
                filters[0].changeScriptOthers = []
              }
              filters[0].changeScriptOthers.pushNoRepeat(item.changeScript)
            }
          }
          // 宽度为空默认150
          it.width = it.width ? it.width : '150';
          // 数据类型如果为空默认是字符串
          it.dataType = it.dataType ? it.dataType : this.$config.dataType.str;
          // 对齐方式为空，默认为居左
          it.align = it.align ? it.align : this.$config.align.left;
          // 如果是数值类型，小数位数为空，默认为0，千分位为空，默认是true
          if (it.dataType === this.$config.dataType.number) {
            it.digits = it.digits ? it.digits : 0;
            it.flgThousandth = it.flgThousandth ? it.flgThousandth : true
          }
          it.displayNo = index + 1;

          // 处理父级表头
          if (Object.keys(it).some(s => s.indexOf('parentCol_') >= 0)) {
            it.headers = []
            for (let key of Object.keys(it).filter(f => f.indexOf('parentCol_') >= 0)){
              it.headers.push(it[key])
            }
          }
        })
      })
      this.params = params;
    }
    ,
    /**
     * @desc   : 保存
     * @author : 周兴
     * @date   : 2023/3/28 13:19
     */
    saveData() {
      if (this.type === this.$config.formMode.add) {
        delete this.params.reportId
        return this.excute(this.$service.customReportService, this.$service.customReportService.insert, this.params)
      } else {
        return this.excute(this.$service.customReportService, this.$service.customReportService.update, this.params)
      }
    }
    ,
    /**
     * @desc   : 清空
     * @author : 姜宁
     * @date   : 2023/4/6 17:23
     */
    clear() {
      this.formData = {
        flgPage: false,// 是否分页
        userIds: null,// 用户
        userNames: '',// 用户名称
        reportName: '',// 报表名称
        reportType: this.$config.reportType.pc,
        displayNo: 0,
        sqlScript: '',// 报表sql
        describe: '',// 报表描述
        remarks: '',  // 备注
      }
      // 加载最大序号
      this.getMaxDisplayNo(this.$config.displayNoTable.customReport);
      this.$refs['conditionTable'].clearTable();
      this.$refs['tableSetting'].clearTable();
      this.sqlTabsOptions = [
        {
          label: 'Sql设置',
          name: 'sql0',
          changeScript: '',
          changeTabName: '',
          sqlScript: '',
          tableSettingList: [],
          flgVisible: true,
          subTotals: '',
          subTotalDataKeys: '',// 需要进行小计的列
          flgPage:true,
          flgProc:false,// 是否为存储过程
          flgDynamicCol:false,// 是否显示动态列
        }
      ]
    },
    /**
     * @desc   : 执行查询台条件下拉数据源的sql
     * @author : 周兴
     * @date   : 2023/3/28 11:21
     */
    excuteSql(sql) {
      let params = {
        sql: sql
      }
      return this.excute(this.$service.customReportService, this.$service.customReportService.excuteSql, params)
    }
    // endregion
  },
  mounted() {
  }
  ,
  created() {
  }
}
</script>

<style scoped>
.sql-class /deep/ .ivu-input {
  font-size: 15px !important;
}

.sql-class /deep/ .ivu-input-wrapper {
  width: 100% !important;
}
</style>
