<template>
  <el-container class="api-edit-sql">
    <el-aside class="fields container" style="margin-right: 20px">
      <div class="container-title">字段查看</div>
      <el-input v-model="fieldsKey" clearable placeholder="字段筛选" size="mini" @input="onFilterFields"></el-input>
      <div class="name">可用维度</div>
      <div class="panel drag-list" style="height: 43%; overflow-y: auto">
        <div v-for="item of rowParamSelected" :key="item.id" class="item">
          <div class="field-box">
            <div class="field">
              <span>{{ item.columnName }}</span>
              <i class="iconfont el-icon-document-copy" style="cursor: pointer" @click="onJoinSql(item.columnName)"></i>
            </div>
            <div v-if="item.columnComments" class="field">
              <span>{{ item.columnComments }}</span>
              <i class="iconfont el-icon-document-copy" style="cursor: pointer" @click="onJoinSql(item.columnComments)"></i>
            </div>
          </div>
          <i class="icon el-icon-bottom-right" style="cursor: pointer" title="添加为参数" @click="onAddFieldParam(item,'string')"></i>
        </div>
      </div>
      <div class="name">可用指标</div>
      <div class="panel drag-list" style="height: 46%; overflow-y: auto">
        <div v-for="item of indexParamSelected" :key="item.id" class="item">
          <div class="field-box">
            <div class="field">
              <span>{{ item.columnName }}</span>
              <i class="iconfont el-icon-document-copy" style="cursor: pointer" @click="onJoinSql(item.columnName)"></i>
            </div>
            <div v-if="item.columnComments" class="field">
              <span>{{ item.columnComments }}</span>
              <i class="iconfont el-icon-document-copy" style="cursor: pointer" @click="onJoinSql(item.columnComments)"></i>
            </div>
          </div>
          <i class="icon el-icon-bottom-right" title="添加为参数" style="cursor: pointer" @click="onAddFieldParam(item,'string')"></i>
        </div>
      </div>
    </el-aside>
    <el-main class="chart-container container p-10">
      <el-container class="h-100">
        <el-header height="auto" style="padding: 0">
          <el-form inline size="mini" style="display: flex;justify-content: space-between">
            <div>
              <el-form-item label="数据库">
                <el-select v-model="form.datasourceId" filterable placeholder="请选择" @change="onSourceChange">
                  <el-option
                    v-for="item in dataSourceList"
                    :key="item.id"
                    :label="`【${item.dsTypeSyl}】 ${item.dsDb}【${item.remark}】`"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="数据表">
                <el-select v-model="form.queryTable" filterable style="width: 150px" @change="onTableChange">
                  <el-option label="请选择" value=""></el-option>
                  <el-option
                    v-for="(table, i) of tableList"
                    :key="i"
                    :label="table.tableComments || '' + ' ' + table.tableViewName || ''"
                    :value="table.tableViewName"
                    style="width: 250px"
                  ></el-option>
                </el-select>
                <i
                  class="iconfont icon-fuzhi"
                  style="cursor: pointer; font-size: 16px; margin-left: 5px"
                  @click="onJoinSql(form.queryTable)"
                ></i>
              </el-form-item>
              <el-form-item label="是否分页">
                <el-switch v-model="form.isPage" :active-value="1" :inactive-value="0"></el-switch>
              </el-form-item>
              <el-form-item label="分页大小">
                <el-input-number v-model="form.pageSize" :max="1000" :min="1" :step="1"></el-input-number>
              </el-form-item>
            </div>

<!--            <el-form-item label="接口类型">-->
<!--              <el-select v-model="form.apiType" placeholder="请选择">-->
<!--                <el-option :value="1" label="select"></el-option>-->
<!--                <el-option :value="3" label="insert"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button class="previewBtn" type="text" @click="preview">预览</el-button>
            </el-form-item>
          </el-form>
        </el-header>
        <el-main class="p-10 h-100">
          <div class="flex-between">
            <span class="container-title">sql编辑区：</span>
            <el-button class="previewBtn" size="small" style="height: 26px;padding: 0 20px;width: 100px;" type="text" @click="onCreateSql">生成sql语句</el-button>
          </div>
          <b-ace-editor
            ref="editor"
            v-model="form.querySql"
            height="300"
            lang="sql"
            snippets
            style="font-size: 14px"
            wrap
          ></b-ace-editor>
          <div class="icons">
            <el-tooltip v-for="(icon, i) of iconList" :key="i" :content="icon.name" effect="dark" placement="top-start">
              <span @click="setIcon(i)">
                <i :class="[icon.type, 'icon']"></i>
              </span>
            </el-tooltip>
          </div>
          <chart-table
            v-if="iconIndex === 0"
            ref="chart"
            :chartData="chartData"
            :columnParamList="columnParamList"
            :indexParamList="indexParamList"
            :rowParamList="rowParamList"
            height="calc(100% - 400px)"
          ></chart-table>
          <chart-json
            v-if="iconIndex === 1"
            ref="chart"
            :chartData="chartData"
            :columnParamList="columnParamList"
            :indexParamList="indexParamList"
            :rowParamList="rowParamList"
            height="calc(100% - 400px)"
          ></chart-json>
        </el-main>
      </el-container>
    </el-main>
    <el-aside class="form container" style="margin-left: 20px; margin-right: 10px">
      <div class="container-title">API设置</div>
      <el-form class="container-item" label-position="right" label-width="70px" size="mini">
        <el-form-item label="API名称">
          <el-input v-model="form.apiName"></el-input>
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="form.apiKey"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="api状态">
          <el-select v-model="form.apiStatus">
            <el-option :value="0" label="下线"></el-option>
            <el-option :value="1" label="上线"></el-option>
            <el-option :value="2" label="故障"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口说明">
          <el-input v-model="form.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div class="params container">
        <div class="container-title" style="margin-bottom: 0">参数设置</div>
        <json-viewer :expand-depth="2" :value="paramObject" sort></json-viewer>
        <el-form v-for="(param, i) of paramsList" :key="i" class="item" style="display:block;padding:10px;" label-width="80px" size="mini">
          <div style="padding-right: 5px">
            <el-form-item label="参数名">
              <el-input v-model="param.name"></el-input>
            </el-form-item>
            <el-form-item label="参数code">
              <el-input v-model="param.key"></el-input>
            </el-form-item>
            <el-form-item label="数据类型">
              <el-select v-model="param.datatype" @change="param.def = ''">
                <el-option label="字符串" value="string"></el-option>
                <el-option label="数字" value="number"></el-option>
                <el-option label="日期" value="date"></el-option>
                <el-option label="月份" value="month"></el-option>
                <el-option label="时间" value="time"></el-option>
                <el-option label="时间戳" value="timestamp"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否必填">
              <el-switch v-model="param.required" active-value="是" inactive-value="否"></el-switch>
            </el-form-item>
            <el-form-item label="默认值">
              <el-input v-if="param.datatype == 'string'" v-model="param.def"></el-input>
              <el-input v-if="param.datatype == 'number'" v-model="param.def" type="number"></el-input>
              <el-date-picker
                v-if="param.datatype == 'date'"
                v-model="param.def"
                placeholder="选择日期"
                type="date"
                value-format="yyyyMMdd"
              ></el-date-picker>
              <el-date-picker
                v-if="param.datatype == 'month'"
                v-model="param.def"
                placeholder="选择月"
                type="month"
                value-format="yyyyMM"
              ></el-date-picker>
              <el-time-picker
                v-if="param.datatype == 'time'"
                v-model="param.def"
                placeholder="选择时间"
                value-format="HH:mm:ss"
              ></el-time-picker>
              <el-date-picker
                v-if="param.datatype == 'timestamp'"
                v-model="param.def"
                placeholder="选择日期"
                type="date"
                value-format="timestamp"
              ></el-date-picker>
              <el-time-picker
                v-if="param.datatype == 'timestamp'"
                v-model="param.def"
                placeholder="选择时间"
                value-format="timestamp"
              ></el-time-picker>
            </el-form-item>
            <div style="display:flex;margin-top:5px;">
              <el-button style="flex:1;" size="mini" type="primary" @click="onInsertParam(param)" plain icon="el-icon-edit">
                插入参数
              </el-button>
              <el-button style="flex:1;" size="mini" type="danger" @click="paramsList.splice(i, 1)" plain icon="el-icon-remove-outline">
                删除
              </el-button>
            </div>
          </div>
<!--          <i class="el-icon-remove-outline del-btn" @click="paramsList.splice(i, 1)"></i>-->

        </el-form>
        <el-button icon="el-icon-plus" plain size="mini" type="primary" @click="onParamAdd">添加</el-button>
      </div>
      <div class="btns">
        <el-button plain size="small" style="width: 100%" type="primary" @click="onPush">发布到API服务平台</el-button>
        <el-button size="small" style="width: 100%" type="primary" @click="onSave">保存</el-button>
      </div>
    </el-aside>
    <el-dialog
      :visible.sync="showDict"
      append-to-body
      custom-class="newbi-dict-dialog"
      title="保存为字典"
      width="700px"
    >
      <el-form label-width="80px" size="mini">
        <el-form-item label="字典名">
          <el-input v-model="dictForm.keyCode"></el-input>
        </el-form-item>
        <el-form-item label="选项预览">
          <el-tree :data="dictForm.content" default-expand-all expand-on-click-node node-key="key">
            <div slot-scope="{ node, data }" class="tree-node">
              <div class="label">key:</div>
              <div class="value" style="width: 100px">{{ data.key }}</div>
              <div class="label">value:</div>
              <div class="value" style="width: 160px">{{ data.value }}</div>
            </div>
          </el-tree>
        </el-form-item>
      </el-form>
      <div class="dialog-btns">
        <el-button size="mini" @click="showDict = false">取消</el-button>
        <el-button size="mini" type="primary" @click="onSaveDictConfirm">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showPush" append-to-body custom-class="api-list-setting" title="发布" width="900px">
      <el-form label-width="120px" size="mini">
        <el-form-item label="接口名称">
          <el-input v-model="pushFrom.name"></el-input>
        </el-form-item>
        <el-form-item label="接口地址">
          <el-input v-model="pushFrom.url"></el-input>
        </el-form-item>
        <el-form-item label="调用量限制">
          <el-input-number v-model="pushFrom.callLimit"></el-input-number>
        </el-form-item>
        <el-form-item label="QPS限制">
          <el-input-number v-model="pushFrom.qpsLimit"></el-input-number>
        </el-form-item>
        <el-form-item label="接口状态">
          <el-switch v-model="pushFrom.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="接口类型">
          <el-select v-model="pushFrom.apiTypeId" placeholder="请选择">
            <el-option v-for="item in apiTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口版本号">
          <el-input v-model="pushFrom.version"></el-input>
        </el-form-item>
        <el-form-item label="接口描述">
          <el-input v-model="pushFrom.description" type="textarea"></el-input>
        </el-form-item>
        <!--提交-->
        <el-form-item>
          <el-button type="primary" @click="onPushConfirm">提交发布</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-container>
</template>
<script>
import * as reportApis from '@/api/report/report';
import { Base64 } from 'js-base64';
import { param } from './config';
import vuedraggable from 'vuedraggable';
import chartTable from './comp/chart-table.vue';
import chartBar from './comp/chart-bar.vue';
import chartLine from './comp/chart-line.vue';
import chartPie from './comp/chart-pie.vue';
import chartJson from './comp/chart-json.vue';
import { clearChildren } from './util';
import { dictSave } from './dict';
import {dataapiRelease} from '@/api/report/report';
import {typeList} from "@/api/apimngr";
const dataMapApi = 'http://10.10.15.26:8080/gateway-api/'
export default {
  components: { vuedraggable, chartTable, chartBar, chartLine, chartPie, chartJson },
  data() {
    return {
      dataSourceList: [],
      categoryList: [],
      form: {
        chartType: 0,
        apiType: 1,
        apiMethod: 'get',
        apiParamType: 0,
        apiJsFunction: 'function(res){return res.data}',
        apiFormal: 1,
        apiStatus: 1,
        remark: '',
        categoryId: 0,
        querySql: '',
        pageSize: 20,
        isPage:1,
      },
      headerList: [],
      paramsList: [],
      tableList: [],
      rowParam: [],
      rowParamSelected: [],
      indexParam: [],
      indexParamSelected: [],
      fieldsKey: '',
      rowParamList: [],
      columnParamList: [],
      indexParamList: [],
      availableParamList: [],
      iconList: [
        { name: '表格', type: 'el-icon-s-grid', disable: false },
        { name: 'json', type: 'el-icon-document', disable: false },
      ],
      iconIndex: 0,
      chartData: [],
      editType: 'add',
      fullData: [],
      previewFlag: false,
      dictForm: { content: [] },
      showDict: false,

      // API发布
      showPush: false,
      //接口类型列表
      apiTypeList: [],
      pushFrom: {
        name: '', //接口名称
        url: '', //接口地址
        callLimit: 10000, //调用次数
        qpsLimit: 2, //qps限制
        status: 1, //状态
        apiTypeId: 0, //接口类型
        description: '', //描述
        version: '', //版本
        extJson: '', //扩展json
      },
    };
  },
  computed: {
    paramObject() {
      return this.paramsList.reduce((r, i) => (i.key ? { ...r, [i.key]: i.def } : r), {});
    },
    headerObject() {
      return this.headerList.reduce((r, i) => (i.k ? { ...r, [i.k]: i.v } : r), {});
    },
    selectedFields() {
      return this.rowParamList.concat(this.columnParamList).concat(this.indexParamList);
    },
  },
  async created() {
    await this.init();
    // 获取数据源列表
    await reportApis.reportdatasourceList().then(res => (this.dataSourceList = res.data));
    // 获取接口分类列表
    await reportApis.dataapicategoryList().then(res => {
      this.categoryList = res.data;
      if (!this.$route.query.id && !this.$route.query.apiKey) {
        this.form.categoryId = this.categoryList[0].id;
      }
    });
  },
  methods: {
    // 字段添加为参数
    onAddFieldParam(field, datatype) {
      if (!this.paramsList.find(i => i.key === field.columnName)) {
        this.paramsList.push({
          name: field.columnComments || field.columnName,
          def: '',
          key: field.columnName,
          datatype,
        })
      }
    },
    // 插入参数
    onInsertParam(param) {
      let str = `(${param.key} = CASE
  WHEN @${param.key}@ IS NULL
  OR @${param.key}@ = ''
  THEN ${param.key} ELSE @${param.key}@
  END)`
      this.$refs.editor.editor.insert(str);
    },
    // 自动配置展示字段
    onAutoSetFields() {
      if (!this.previewFlag) {
        return this.$message({ type: 'warning', message: '请先预览' });
      }
      let pastFields = this.rowParam.concat(this.indexParam);
      this.availableParamList.forEach(item => {
        let now = pastFields.find(i => i.columnName == item.columnName);
        if (!now) return;
        item.columnComments = now.columnTitle;
        item.dataType = now.dimensionType == 'WEIDU' ? 0 : 1;
      });
      this.rowParamList = this.availableParamList.filter(i => i.dataType == 0);
      this.columnParamList = [];
      this.indexParamList = this.availableParamList.filter(i => i.dataType == 1);
    },
    onSaveDictConfirm() {
      let { keyCode, content } = this.dictForm;
      if (!keyCode) {
        return this.$message({ type: 'warning', message: '请输入字典名' });
      }
      let data = { keyCode, content: JSON.stringify(content) };
      dictSave(data).then(res => {
        this.$message({ type: 'success', message: '已提交' });
        this.showDict = false;
      });
    },
    clearItem(node) {
      let { KEY, VALUE, children } = node;
      if (children && children.length) {
        return { key: KEY, value: VALUE, children: children.map(this.clearItem) };
      } else {
        return { key: KEY, value: VALUE };
      }
    },
    // 保存为枚举字典
    onSaveDict() {
      if (!this.previewFlag) {
        return this.$message({ type: 'warning', message: '请先预览' });
      }
      let data = JSON.parse(JSON.stringify(this.fullData));
      let content = [];
      if (this.fullData[0].ID) {
        let tree = this.countTreeOptions(data);
        tree.forEach(clearChildren);
        content = tree;
      } else {
        content = data.map(i => ({ KEY: i.ID || i.VALUE, VALUE: i.VALUE }));
      }
      content = content.map(this.clearItem);
      this.dictForm = { keyCode: '', content };
      this.showDict = true;
    },
    countTreeOptions(originData) {
      originData.forEach(i => {
        i.children = [];
        i.KEY = i.ID || i.VALUE;
      });
      let parents = [...originData];
      let res = [],
        childrens = [];
      originData.forEach(i => (!i.PID || i.PID == '0' ? res.push(i) : childrens.push(i)));
      childrens.forEach(i => {
        let parent = parents.find(j => j.ID == i.PID);
        if (parent) {
          parent.children.push(i);
        }
      });
      return res;
    },
    onJoinSql(str) {
      this.$refs.editor.editor.insert(str);
    },
    onFieldDel(key, i) {
      this[key].splice(i, 1);
    },
    countCanSelect(field) {
      return !!this.selectedFields.find(i => i.columnName == field.columnName);
    },
    onFieldAdd(key, field) {
      if (!this.selectedFields.find(i => i.columnName == field.columnName)) {
        this[key].push(field);
      }
    },
    // 图表展示
    onChartShow() {
      let indexLength = this.indexParamList.length;
      this.iconList[0].disable = indexLength > 1;
      if (this.iconList[this.iconIndex].disable) {
        this.iconIndex = this.iconList.findIndex(i => !i.disable);
      }
      this.$refs.chart.flush();
    },
    // 选择展示图表类型时
    setIcon(index) {
      if (this.iconList[index].disable) return;
      this.iconIndex = index;
    },
    preview() {
      reportApis.openurl(this.form.apiKey, { ...this.paramObject, ...param }).then(res => {
        if (res.code != 200) {
          this.$message.error('必须保存才能预览');
        } else {
          this.returenData = res;
          this.rowParamList = [];
          this.columnParamList = [];
          this.indexParamList = [];
          this.availableParamList = [];
          this.fullData = res.data.records;
          this.chartData = res.data.records.slice(0, 100);
          if (!this.chartData.length) return;
          let keys = Object.keys(this.chartData[0]);
          let previous = JSON.parse(this.form.note || '{}').showFields || [];
          this.availableParamList = keys.map(i => {
            return previous.find(j => j.columnName == i) || { columnName: i, columnComments: i, dataType: 0 };
          });
          this.availableParamList.forEach(field => {
            if (field.dataType === 0) {
              this.rowParamList.push(field);
            } else {
              this.indexParamList.push(field);
            }
          });
          this.previewFlag = true;
          setTimeout(this.onChartShow, 500);
        }
      });
    },
    onSave() {
      let data = { ...this.form };
      let showFields = [...this.availableParamList];
      let params = this.paramsList;
      data.note = JSON.stringify({ showFields, params });
      data.apiHeaders = JSON.stringify({ ...this.headerObject });
      reportApis.dataapiSubmit(Base64.encode(JSON.stringify(data))).then(res => {
        this.$message({ type: 'success', message: '保存成功' });
        if (this.editType == 'add') {
          this.editType = 'update';
          this.$router.replace('/apimngr/apisql?id=' + res.data.id);
        } else {
          setTimeout(this.init, 500);
        }
      });
    },
    onParamAdd() {
      this.paramsList.push({ key: '', datatype: 'string', def: '', name: '' });
    },
    // 过滤可用字段
    onFilterFields(key) {
      console.log(this.rowParam)
      this.rowParamSelected = this.rowParam.filter(i => i.columnTitle.includes(key) || i.columnName.includes(key));
      this.indexParamSelected = this.indexParam.filter(i => i.columnTitle.includes(key) || i.columnName.includes(key));
    },
    // 选择数据表时
    onTableChange(tableName) {
      reportApis.listColumnsByDatasource({ datasourceId: this.form.datasourceId, tableViewName:tableName }).then(res => {
        let data = res.data;
        this.rowParam = data.filter(item => item.columnType !== 'NUMBER');
        this.rowParamSelected = [...this.rowParam];
        this.indexParam = data.filter(item => item.columnType === 'NUMBER');
        this.indexParamSelected = [...this.indexParam];
        this.fields = data.map(item => {
          return {
            columnName: item.columnName,
            columnComments: item.columnTitle,
            dataType: item.columnType !== 'NUMBER' ? 0 : 1,
          };
        });
        if (!this.form.querySql || (this.oldtableName && tableName != this.oldtableName)) {
          this.onCreateSql();
        }
        this.oldtableName = JSON.parse(JSON.stringify(tableName));
      });
    },
    // 创建sql
    onCreateSql() {
      if (!this.form.queryTable) {
        return this.$message({ type: 'warning', message: '请选择数据表' });
      }
      this.form.querySql = `select ${this.fields.map(v => v.columnName).toString()} from ${this.form.queryTable}`;
      this.paramsList = this.rowParam.map(item => {
        return {
          name: item.columnComments ? item.columnComments : item.columnName,
          key: item.columnName,
          datatype: 'string',
        };
      });
      // 拼接where条件
      let where = this.rowParam.map((item,index) => {
        if (index === 0){
          return `${item.columnName} = @${item.columnName}@`;
        }else{
          return ` and ${item.columnName} = @${item.columnName}@`;
        }
      });
      this.form.querySql = this.form.querySql + ' where ' + where.join(' ');
    },
    // 选择数据源时
    onSourceChange(id) {
      reportApis.listViewsByDataSource({ datasourceId: id, current: 1, size: 10000 }).then(res => {
        this.tableList = res.data.records;
        this.form.queryTable = '';
      });
    },
    async init() {
      let { id } = this.$route.query;
      if (!id) return;
      this.editType = 'update';
      await reportApis.dataapiDetail(id).then(res => {
        this.form = res.data;
        if (!this.form.apiJsFunction) {
          this.form.apiJsFunction = 'function(res){return res.data}';
        }
        let paramsList = JSON.parse(this.form.note || '{}').params || [];
        paramsList.forEach(item => (item.name = item.name || item.key));
        let headers = JSON.parse(this.form.apiHeaders || '{}');
        this.headerList = Object.entries(headers).map(([k, v]) => ({ k, v }));
        this.paramsList = paramsList;
        // 获取数据表列表
        let id = this.form.datasourceId;
        reportApis.listViewsByDataSource({ datasourceId: id, current: 1, size: 10000 }).then(res => {
          this.tableList = res.data.records;
        });
        if (this.form.queryTable) this.onTableChange(this.form.queryTable);
        this.preview();
      });
    },

    onPush() {
      this.showPush = true;
      typeList().then(res => {
          this.apiTypeList = res.data;
          this.showPush = true;
          this.pushFrom = {
            name: this.form.apiName, //接口名称
            url: location.protocol + '//' + location.host  + '/etl-api' + this.form.apiUrl, //接口地址
            callLimit: 10000, //调用次数
            qpsLimit: 2, //qps限制
            status: this.form.apiStatus, //状态
            apiTypeId: this.apiTypeList[0].id, //接口类型
            description: this.form.remark, //描述
            version: '1.0.0', //版本
          };
          let params = this.paramsList.map(item => {
            return {
              name: item.key,
              type: item.datatype,
              required: item.required,
              description: item.name,
              default: item.def,
            };
          });
          let returnParams = Object.keys(this.fullData[0]).map(item => {
            return {
              name: item,
              type: 'string',
              description: item,
            };
          });
          let response = {
            code: '200',
            message: '成功',
            data: this.fullData,
          };
          this.pushFrom.extJson = {
            method: 'GET',
            type:'select',
            params,
            returnParams: returnParams,
            response,
          };
        })
        .catch(err => {
          console.log(err);
        });
    },
    onPushConfirm() {
      if (!this.pushFrom.name) {
        return this.$message({ message: '请输入接口名称', type: 'warning' });
      }
      if (!this.pushFrom.url) {
        return this.$message({ message: '请输入接口地址', type: 'warning' });
      }
      if (!this.pushFrom.callLimit) {
        return this.$message({ message: '请输入调用次数', type: 'warning' });
      }
      if (!this.pushFrom.qpsLimit) {
        return this.$message({ message: '请输入qps限制', type: 'warning' });
      }
      if (!this.pushFrom.apiTypeId) {
        return this.$message({ message: '请选择接口类型', type: 'warning' });
      }
      if (!this.pushFrom.description) {
        return this.$message({ message: '请输入描述', type: 'warning' });
      }
      if (!this.pushFrom.version) {
        return this.$message({ message: '请输入版本', type: 'warning' });
      }
      // 拷贝一下 pushFrom
      let pushFrom = JSON.parse(JSON.stringify(this.pushFrom));
      if (this.form.isPage){
        const params = [
          {
            name: 'pageNum',
            type: 'number',
            required: '是',
            description: '页码',
            default: 1,
          },
          {
            name: 'pageSize',
            type: 'number',
            required: '是',
            description: '每页条数',
            default: this.form.pageSize,
          }
        ];
        // 确保 this.pushFrom.extJson 存在并且 params 是一个数组
        if (!pushFrom.extJson) {
          pushFrom.extJson = {};
        }
        if (!Array.isArray(pushFrom.extJson.params)) {
          pushFrom.extJson.params = [];
        }
        pushFrom.extJson.params = params.concat(pushFrom.extJson.params);
      }
      pushFrom.extJson = JSON.stringify(pushFrom.extJson);
      dataapiRelease(pushFrom).then(res => {
        this.$message({ message: '已提交', type: 'success' });
        this.showPush = false;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.api-edit-sql {
  display: flex;
  background: #eee;
  padding: 0 !important;
  height: calc(100vh - 130px) !important;
  justify-content: space-between;

  .previewBtn {
    background: #409eff;
    width: 50px;
    border-radius: 5px;
    text-align: center;
    font-size: 12px;
    color: #fff;
  }

  .icon-fuzhi {
    color: #666;
  }

  .icons {
    display: flex;
    align-items: center;
    height: 30px;
    gap: 20px;

    .el-tooltip {
      svg {
        cursor: pointer;
      }
    }

    .icon {
      cursor: pointer;
    }
  }

  .container {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border-radius: 5px;
    background-color: #fff;

    &:last-of-type {
      margin-right: 0;
    }

    .container-title {
      text-indent: 10px;
      font-size: 14px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #777;
      border-left: 3px solid #409eff;
    }

    .drag-list {
      min-height: 80px;
      border: 1px dashed #ccc;
      padding: 0 5px 5px;
      background-color: #f5f6fa;

      .item {
        font-size: 12px;
        line-height: 18px;
        text-align: left;
        margin-top: 5px;
        border-radius: 2px;
        border: 1px solid #ccc;
        padding: 3px 10px;
        display: flex;
        align-items: center;
        padding-right: 5px !important;
        .field-box {
          flex: 1;
        }
        &.WEIDU {
          border: 1px solid #1d54d5;
        }

        &.ZHIBIAO {
          border: 1px solid #00b375;
        }
      }
    }
  }

  .chart-container {
    overflow: scroll;
    flex: 1;
    padding: 20px !important;

    #map {
      height: 100%;
    }
  }

  .preview {
    width: 220px;
    overflow-y: scroll;

    .name {
      line-height: 30px;
      text-indent: 1em;
      font-size: 14px;
      font-weight: 600;

      &.edit {
        font-weight: 500;
        color: #409eff;
      }

      opacity: 1;
    }

    .panel {
      .item {
        line-height: 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .el-form {
          .el-form-item {
            margin-bottom: 0;

            .el-form-item__label {
              padding-right: 5px;
            }
          }
        }
      }

      .field-setting {
        margin-left: 10px;
        border-radius: 3px;
        line-height: 20px;
        font-size: 14px;
        cursor: pointer;
        border: 1px solid #777;
        color: #777;
        text-align: center;
        width: 45px;
      }
    }
  }

  .fields {
    width: 260px;
    overflow-y: scroll;
    flex-direction: column;
    padding: 5px;

    .name {
      line-height: 30px;
      text-indent: 1em;
      font-size: 14px;
      font-weight: 600;
    }

    .item {
      .field {
        line-height: 20px;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }

  .params {
    width: 100%;
    overflow-y: scroll;
    padding: 10px 0;
    height: calc(100% - 362px);
    display: flex;
    flex-direction: column;
    gap: 5px;

    .header-item {
      display: flex;
      padding: 5px 0;
      align-items: center;
    }

    .jv-container {
      border: 1px solid #ccc;
      height: 120px;
      margin-bottom: 10px;

      .jv-code {
        height: 100%;
        padding: 5px;
      }
    }

    .item {
      position: relative;
      padding: 10px 0;
      border: 1px solid #ccc;
      border-radius: 5px;
      display: flex;
      align-items: flex-start;
      gap: 3px;

      .el-form-item {
        margin-bottom: 0;
      }

      .el-date-editor {
        width: auto;
      }

      .del-btn {
        position: relative;
        right: 0;
        top: 0;
        color: rgba(234, 9, 9, 0.85);
        font-size:16px;
        cursor: pointer;
      }
    }

    .add-btn {
      display: block;
      width: 200px;
      margin: 20px auto 10px;
    }
  }

  .form {
    width: 300px;
    overflow-y: scroll;
    padding: 10px 0 0 10px;
    margin: 0 auto;

    .el-form {
      margin-right: 0;
    }

    .btns {
      padding: 20px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

.newbi-dict-dialog {
  .el-tree {
    max-height: 400px;
    overflow-y: auto;
    margin-top: 10px;
  }

  .tree-node {
    display: flex;
    align-items: center;

    .label {
      color: #999;
      font-size: 12px;
    }

    .value {
      font-weight: 600;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 0 20px 0 10px;
    }
  }
}
</style>
