<template>
  <div class="fullheight">
    <el-dialog
      width="55%"
      top="6vh"
      title="接口管理"
      class="sp-manager__dialog"
      :visible="dialogVisible"
      v-if="dialogVisible"
      :before-close="beforeCloseDialog"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <el-form
        :model="formData"
        style="width: 100%; height: 500px"
        v-form
        data-vv-scope="PortalInterfaceManagerForm"
      >
        <el-row :gutter="0" justify="start" align="top" type="flex">
          <el-col :span="12" style="">
            <ht-form-item label="接口名称" label-width="140px">
              <ht-input
                v-model="formData.name"
                class="ht"
                placeholder="请输入名称"
                autocomplete="off"
                validate="required"
                :maxlength="50"
                :showWordLimit="true"
              ></ht-input>
            </ht-form-item>
          </el-col>
          <el-col :span="12" style="">
            <ht-form-item label="接口别名" label-width="140px">
              <ht-input
                v-model="formData.alias"
                class="ht"
                v-pinyin="formData.name"
                placeholder="请输入别名"
                autocomplete="off"
                :validate="{
                  required: true,
                  regex: {
                    exp: '^[a-zA-Z][a-zA-Z0-9_]*$',
                    message: '只能输入字母、数字、下划线，且以字母开头'
                  }
                }"
                :disabled="!!formData.id"
                :maxlength="50"
                :showWordLimit="true"
              ></ht-input>
            </ht-form-item>
          </el-col>
        </el-row>
        <ht-form-item label="接口来源" label-width="140px">
          <ht-radio
            v-model="formData.sourceType"
            :options="[
              {key: 0, value: '连接'},
              {key: 1, value: '服务'}
            ]"
            @change="handleSourceTypeChange"
          ></ht-radio>
        </ht-form-item>
        <el-row :gutter="0" justify="start" align="top" type="flex">
          <el-col :span="12" style="">
            <ht-form-item
              label="服务管理"
              label-width="140px"
              v-if="formData.sourceType === 1"
            >
              <ht-select
                class="ht"
                v-model="formData.refId"
                :options="bizSystemList"
                :props="bizSystemProps"
                :validate="{required: true}"
                placeholder="请选择服务管理"
                @change="connectChanage"
              />
            </ht-form-item>
            <ht-form-item label="连接管理" label-width="140px" v-else>
              <ht-select
                class="ht"
                v-model="formData.refId"
                :options="connectList"
                :props="connectProps"
                :validate="{required: true}"
                placeholder="请选择连接管理"
                @change="connectChanage"
              />
            </ht-form-item>
          </el-col>
        </el-row>
        <div v-if="formData.connectionType == 'dataSource'">
          <el-row :gutter="0" justify="start" align="top" type="flex">
            <el-col :span="24" style="">
              <ht-form-item label="构建类型" label-width="140px">
                <ht-select
                  class="ht"
                  v-model="dbDetail.type"
                  :options="typeList"
                  :validate="{required: true}"
                  placeholder="请选择构建类型"
                />
              </ht-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0" justify="start" align="top" type="flex">
            <el-col :span="12" style="">
              <ht-form-item label="分页" label-width="140px">
                <ht-radio
                  v-model="dbDetail.needPage"
                  class="ht"
                  :options="[
                    {key: 1, value: '是'},
                    {key: 0, value: '否'}
                  ]"
                  validate="required"
                />
              </ht-form-item>
            </el-col>
            <el-col :span="12" style="">
              <ht-form-item
                label="分页大小"
                label-width="140px"
                v-if="dbDetail.needPage"
              >
                <ht-input
                  v-model="dbDetail.pageSize"
                  class="ht"
                  placeholder="请输入分页大小"
                  autocomplete="off"
                  validate="required"
                ></ht-input>
              </ht-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="0"
            justify="start"
            align="top"
            type="flex"
            v-if="dbDetail.type == 'search'"
          >
            <el-col :span="12" style="">
              <ht-form-item label="查询表(视图)" label-width="140px">
                <ht-select
                  style="width: 100px"
                  v-model="dbDetail.isTable"
                  :options="isTableList"
                />&nbsp;&nbsp;
                <ht-input
                  v-model="objName"
                  style="width: 170px"
                  placeholder="请输入表或视图名称"
                  autocomplete="off"
                ></ht-input
                >&nbsp;&nbsp;
                <el-button type="primary" @click="getByDsObjectName"
                  >查 询</el-button
                >
              </ht-form-item>
            </el-col>
            <el-col :span="12" style="">
              <ht-form-item label="选择表或视图" label-width="140px">
                <ht-select
                  v-model="dbDetail.objName"
                  :options="tableOrViewList"
                  :remote-method="getByDsObjectName"
                  :props="{key: 'name', value: 'comment'}"
                />&nbsp;&nbsp;
                <el-button
                  type="primary"
                  v-if="dbDetail.objName"
                  @click="showSettingDialog"
                  >设置列</el-button
                >
              </ht-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="0"
            justify="start"
            align="top"
            type="flex"
            v-if="dbDetail.type == 'custom'"
          >
            <el-col :span="12" style="">
              <ht-form-item label="sql语句" label-width="140px">
                <span slot="label">
                  <el-tooltip
                    content="sql支持传参，参数取设置的条件字段，例：select * from uc_user where account_ ='{account}'，根据不同字段类型按需加上引号"
                    placement="top"
                    effect="dark"
                  >
                    <!-- content to trigger tooltip here -->
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                  sql语句
                </span>
                <ht-input
                  type="textarea"
                  v-model="dbDetail.diySql"
                  :autosize="{minRows: 10, maxRows: 10}"
                />
                <el-button type="primary" @click="showSettingDialog"
                  >设置参数</el-button
                >
                <!-- &nbsp;&nbsp;<el-button
                type="primary"
                @click="checkSql"
                v-if="!formData.id"
                >验证SQL</el-button
              > -->
              </ht-form-item>
            </el-col>
          </el-row>
        </div>

        <div v-else>
          <el-row :gutter="0" justify="start" align="top" type="flex">
            <el-col :span="12">
              <ht-form-item label="请求地址" label-width="140px">
                <ht-input
                  v-model="restfulDetail.url"
                  class="ht"
                  placeholder="请输入请求地址"
                  autocomplete="off"
                  validate="required"
                >
                  <template slot="append">
                    <el-tooltip
                      slot="label"
                      effect="dark"
                      content="Restful接口地址，基础地址由外部系统提供，只需配置相对地址，如：/base/tools/v1/getPinyin"
                    >
                      <i class="icon-question"></i>
                    </el-tooltip>
                  </template>
                </ht-input>
              </ht-form-item>
            </el-col>
            <el-col :span="12">
              <ht-form-item label="请求类型" label-width="140px">
                <ht-radio
                  v-model="restfulDetail.requestType"
                  class="ht"
                  :options="[
                    {key: 'POST', value: 'POST'},
                    {key: 'GET', value: 'GET'}
                  ]"
                />
              </ht-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0" justify="start" align="top" type="flex">
            <el-col :span="12" >
              <ht-form-item label="token认证" label-width="140px">
                <template slot="label">
                  <el-tooltip content="是否需要本系统token作为接口头部">
                    <i class="property-tip icon-question" />
                  </el-tooltip>
                  token认证
                </template>
                <ht-radio
                  v-model="restfulDetail.tokenAuth"
                  :options="[
                    {key: '1', value: '是'},
                    {key: '0', value: '否'}
                  ]"
                  :validate="{required: true}"
                />
              </ht-form-item>
            </el-col>
            <el-col :span="12" style="">
              <ht-form-item label="列表(key)" label-width="140px">
                <ht-input
                  v-model="restfulDetail.listKey"
                  class="ht"
                  placeholder="请输入列表"
                  autocomplete="off"
                ></ht-input>
              </ht-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0" justify="start" align="top" type="flex">
            <el-col :span="12" style="">
              <ht-form-item label-width="140px" label="接口头部">
                <ht-input
                  v-model="restfulDetail.header"
                  class="ht"
                  placeholder="请求接口的头部信息"
                  autocomplete="off"
                >
                  <template slot="append">
                    <el-tooltip
                      slot="label"
                      effect="dark"
                      content='接口头部（header）为JSON格式，如：{"Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9"}'
                    >
                      <i class="icon-question"></i>
                    </el-tooltip>
                  </template>
                </ht-input>
              </ht-form-item>
            </el-col>
            <el-col :span="12" style="">
              <ht-form-item label="参数配置" label-width="140px">
                <el-button type="primary" @click="showSettingDialog"
                  >设置参数</el-button
                >
              </ht-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button type="primary" @click="saveData">{{
          $t('eip.common.save')
        }}</el-button>
        <el-button @click="beforeCloseDialog">{{
          $t('eip.common.cancel')
        }}</el-button>
      </div>

      <!-- 设置列 -->
      <ht-sidebar-dialog
        width="100%"
        :title="titleSetting"
        class="cd-column__dialog"
        :visible="dialogVisibleSetting"
        :before-close="close"
        :close-on-click-modal="false"
        append-to-body
        :show-close="false"
      >
        <template v-slot:title>
          <div class="flex" style="justify-content: space-between;width: 100%;">
            <div style="float: left;width: 100%;">
              <el-page-header
                style="float: left;"
                @back="close"
                :content="titleSetting"
              ></el-page-header>
              <el-button
                style="float: left;margin-left: 20px;"
                type="success"
                @click="addFields"
                v-if="isShowAdd"
                icon="el-icon-plus"
                >添加字段</el-button
              >
              <el-button
                style="float: right;"
                type="primary"
                @click="save"
                icon="el-icon-check"
                >保 存</el-button
              >
            </div>
          </div>
        </template>
        <el-form data-vv-scope="settingSave" class="form-table__wrap">
          <el-row :gutter="20" class="form-table__row">
            <el-col :span="7" class="form-table__left">
              <el-table
                :data="table.columnList"
                @selection-change="handleSelectionChange"
                border
                ref="htTableSetting"
                @row-dblclick="fillToCondition"
                @row-click="clickRow"
              >
                <el-table-column type="selection" width="40" />
                <el-table-column key="1" label="字段" width="250">
                  <template v-slot="{row}">
                    <ht-input
                      v-model="row.fieldName"
                      placeholder="请输入字段"
                      autocomplete="off"
                      validate="required"
                      :maxlength="50"
                    ></ht-input>
                  </template>
                </el-table-column>
                <el-table-column label="注解" key="3">
                  <template v-slot="{row}">
                    <ht-input
                      v-model="row.comment"
                      style="width:100%;"
                      placeholder="请输入注解"
                      autocomplete="off"
                      validate="required"
                      :maxlength="50"
                    ></ht-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="类型"
                  prop="columnType"
                  width="80"
                  key="4"
                />
                <el-table-column
                  label="操作"
                  width="100"
                  v-if="isShowAdd"
                  key="2"
                >
                  <template v-slot="{$index}">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteSetting(table.columnList, $index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="1">
              <el-button
                type="primary"
                circle
                icon="icon-hide"
                :title="addColumnsTitle"
                style="-webkit-transform: rotate(270deg);transform: rotate(270deg)"
                @click="addColumns"
              />
            </el-col>
            <el-col :span="16" class="form-table__right">
              <el-tabs
                v-model="tabStatus"
                @tab-click="handleTabSwitch"
                type="border-card"
              >
                <el-tab-pane
                  label="返回字段"
                  name="return"
                  v-if="
                    formData.connectionType == 'restful' ||
                      (formData.connectionType == 'dataSource' &&
                        dbDetail.type == 'search')
                  "
                >
                  <div v-if="formData.connectionType == 'restful'">
                    <el-tag type="warning"
                      >如果返回的数据为复杂的JSON结构，可以指定列表（key）字段，当前返回字段为列表中的字段。</el-tag
                    >
                    <ol class="guide-ol">
                      <li>
                        例如返回的数据为：
                        <code
                          >{state: true, message: "数据请求成功", result: {page:
                          1, size:20, total: 200, rows: [{name: "name1",age:
                          20},{name: "name2",age: 18}]}}</code
                        >
                      </li>
                      <li>
                        指定列表（key）字段为
                        <code>result.rows</code>，现在返回字段就可以指定
                        <code>{name: "name1",age: 20}</code>中的字段，如：
                        <code>name</code>或者
                        <code>age</code>
                      </li>
                    </ol>
                    <br />
                  </div>
                  <el-table :data="dbDetail.resultfield" border>
                    <el-table-column prop="field" label="字段名" width="200">
                      <template v-slot="{row}">
                        <ht-input
                          :permission="
                            formData.connectionType == 'restful' ? 'w' : 'r'
                          "
                          v-model="row.field"
                          placeholder="返回的字段名"
                          autocomplete="off"
                          validate="required"
                          :maxlength="50"
                          :showWordLimit="true"
                        ></ht-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="返回名称">
                      <template v-slot="{row}">
                        <ht-input
                          v-model="row.comment"
                          placeholder="请输入返回名称"
                          autocomplete="off"
                          validate="required"
                          :maxlength="50"
                          :showWordLimit="true"
                        ></ht-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template v-slot="{$index}">
                        <el-button
                          size="mini"
                          type="danger"
                          icon="el-icon-delete"
                          @click="
                            deleteSetting(dbDetail.resultfield, $index)
                          "
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="条件字段" name="condition">
                  <el-table  :data="dbDetail.conditionfield" border>
                    <el-table-column label="字段名" width="130">
                      <template v-slot="{row}">
                        <ht-input
                          :permission="
                            formData.connectionType == 'restful' ? 'w' : 'r'
                          "
                          v-model="row.field"
                          placeholder="字段名"
                          autocomplete="off"
                          validate="required"
                          :maxlength="50"
                        ></ht-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="显示名" width="250">
                      <template v-slot="{row}">
                        <ht-input
                          v-model="row.comment"
                          placeholder="请输入显示名"
                          autocomplete="off"
                          validate="required"
                          :maxlength="50"
                        ></ht-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="条件"
                      width="250"
                      v-if="
                        formData.connectionType == 'dataSource' &&
                          dbDetail.type == 'search'
                      "
                    >
                      <template v-slot="{row}">
                        <ht-select
                          v-show="row.dbType == 'number' || row.dbType == 'int'"
                          v-model="row.condition"
                          :options="number_opList"
                          :validate="{required: true}"
                        />
                        <ht-select
                          v-show="
                            row.dbType == 'varchar' || row.dbType == 'clob'
                          "
                          v-model="row.condition"
                          :options="string_opList"
                          :validate="{required: true}"
                        />
                        <ht-select
                          v-show="row.dbType == 'date'"
                          v-model="row.condition"
                          :options="date_opList"
                          :validate="{required: true}"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="值来源" width="250">
                      <template v-slot="{row}">
                        <ht-select
                          v-model="row.defaultType"
                          :options="value_sourceList_list"
                          @change="sourceListChang(row)"
                          :validate="{required: true}"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="默认值" width="250">
                      <template v-slot="{row}">
                        <ht-input
                          type="textarea"
                          v-if="row.dbType != 'date' && row.defaultType == 2"
                          :autosize="{minRows: 1, maxRows: 4}"
                          v-model="row.defaultValue"
                          placeholder="请输入默认值"
                          autocomplete="off"
                          :validate="{required: row.defaultType == '2'}"
                          :maxlength="200"
                          :showWordLimit="true"
                        ></ht-input>
                        <ht-date
                          v-if="row.dbType == 'date'"
                          v-model="row.defaultValue"
                          :validate="{required: row.defaultType == '2'}"
                          format="yyyy-MM-dd"
                        />
                        <div
                          v-if="
                            row.dbType == 'date' && row.condition == 'BETWEEN'
                          "
                        >
                          <ht-date
                            v-model="row.endDate"
                            placeholder="选择结束日期"
                            :validate="{required: row.defaultType == '2'}"
                            format="yyyy-MM-dd"
                          />
                        </div>
                        <!-- <ht-select 
                          v-if="row.defaultType == '3'" 
                          :options="scriptOptions" 
                          style="width:100%"
                          placeholder="选择常用脚本"
                          filterable
                          @change="handleScriptSelect($event, row)"
                          v-model="row.selectScript"></ht-select> -->
                        <el-button
                          @click="showScriptDialog(row)"
                          type="text"
                          style="float:left"
                          v-if="row.defaultType == '3'"
                          >选择脚本
                          <i class="el-icon-search"></i>
                        </el-button>
                        <ht-input
                          type="textarea"
                          v-if="row.defaultType == '3'"
                          :autosize="{minRows: 4, maxRows: 6}"
                          v-model="row.defaultValue"
                          placeholder="请输入默认值"
                          autocomplete="off"
                          validate="required"
                          :maxlength="200"
                          :showWordLimit="true"
                        ></ht-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="控件类型" width="140">
                      <template v-slot="{row}">
                        <ht-select
                          v-if="
                            row.defaultType == '1'
                              ? (row.controllerType = '1')
                              : (row.controllerType = '')
                          "
                          v-model="row.controllerType"
                          :options="param_ctList"
                          :validate="{required: true}"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template v-slot="{$index}">
                        <el-button
                          size="mini"
                          type="danger"
                          icon="el-icon-delete"
                          @click="
                            deleteSetting(
                              dbDetail.conditionfield,
                              $index
                            )
                          "
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane
                  label="POST请求参数"
                  name="dataParam"
                  v-if="
                    formData.connectionType == 'restful' &&
                      restfulDetail.requestType == 'POST'
                  "
                >
                  <div style="min-height: 320px;">
                    <el-tag type="warning"
                      >以POST方式请求接口时传入的参数，参数中可以通过${field}传入条件字段中定义的参数。</el-tag
                    >
                    <VariablesSelector
                      :data="dbDetail.conditionfield"
                      node-key="field"
                      :props="{label: 'comment', children: 'children'}"
                      @node-click="handleVarSelectorClick"
                    />
                    <codemirror
                      ref="dataParamCode"
                      v-model="restfulDetail.dataParam"
                      :options="cmOptions"
                      class="code"
                      style="width: 95%;min-height:270px;"
                    ></codemirror>
                  </div>
                </el-tab-pane>
                <el-tab-pane
                  label="排序字段"
                  name="order"
                  v-if="
                    formData.connectionType == 'dataSource' &&
                      dbDetail.type == 'search'
                  "
                >
                  <el-table :data="dbDetail.sortfield" border>
                    <el-table-column prop="field" label="字段名" width="200" />
                    <el-table-column prop="comment" label="注解" width="200" />
                    <el-table-column label="排序类型">
                      <template v-slot="{row}">
                        <ht-select
                          v-model="row.sortType"
                          :options="sort_typeList"
                          :validate="{required: true}"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template v-slot="{$index}">
                        <el-button
                          size="mini"
                          type="danger"
                          icon="el-icon-delete"
                          @click="
                            deleteSetting(dbDetail.sortfield, $index)
                          "
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane
                  label="自定义SQL"
                  name="custom"
                  v-if="
                    formData.connectionType == 'dataSource' &&
                      dbDetail.type == 'search'
                  "
                >
                  <el-checkbox v-model="isSqlBuildType">
                    自定义SQL
                    <el-tooltip class="item" effect="dark" placement="top">
                      <div slot="content">
                        <ul>
                          <li>
                            自定义SQL
                            <ul>
                              <li>if(map.get('ACTDEFID')!=null){</li>
                              <li>
                                return "select * from UC_USER where ACTDEFID
                                like '%"+map.get("ACTDEFID")+"%'";
                              </li>
                              <li>}</li>
                              <li>其中的map为系统所封装的一个参数</li>
                              <li>
                                在脚本中使用map.get('ACTDEFID')可以获取表单提交时所携带的ACTDEFID参数值，
                                脚本应拼接并返回任意的可执行的sql语句;同时，sql语句字段返回应该包含我们定义的
                                返回字段，和显示字段，通常使用select *
                                from的方式保证需求字段都在这个查询里面
                              </li>
                            </ul>
                          </li>
                        </ul>
                      </div>
                      <i class="icon-question" style="margin-right: 8px" />
                    </el-tooltip>
                  </el-checkbox>
                  <ht-select
                    v-model="selectOp"
                    @change="changeOptions()"
                    :options="selectOptions"
                    :props="{key: 'field', value: 'comment'}"
                  ></ht-select>
                  <br />
                  <br />
                  <!--<el-button @click="getScriptList">常用脚本</el-button>-->
                  <el-input
                    type="textarea"
                    :autosize="{minRows: 12}"
                    placeholder="请输入内容"
                    v-model="dbDetail.diySql"
                    @input="diySqlChange($event)"
                  ></el-input>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
        </el-form>
      </ht-sidebar-dialog>
      <!-- 脚本选择对话框 -->
      <eip-script-dialog
        :appendToBody="true"
        ref="eipScriptDialog"
        @onConfirm="handleScriptSelected"
      ></eip-script-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {Message, TableColumn} from 'element-ui'
import utils from '@/hotent-ui-util.js'
import req from '@/request.js'
import form from '@/api/form.js'
const EipScriptDialog = () => import('@/components/dialog/EipScriptDialog.vue')
const VariablesSelector = () =>
  import('@/components/common/VariablesSelector.vue')

export default {
  components: {
    EipScriptDialog,
    VariablesSelector
  },
  data() {
    return {
      restfulDetail:{},
      dbDetail: {
          type: '',
          dsalias: '',
          isTable: '1',
          objName: '',
          sqlBuildType: '0',
          needPage: 0,
          resultfield: [],
          conditionfield: [],
          sortfield: []
        },
      dialogVisible: false,
      isSqlBuildType: false,
      isSubmit: true, //侧边栏是否提交
      connectProps: {key: 'id', value: 'name'},
      bizSystemProps: {key: 'id', value: 'sysName'},
      params: {},
      formData: {
        refId: '',
        name: '',
        alias: '',
        desc: '',
        connectionType: '',
        dbDetail: {
          type: '',
          dsalias: '',
          isTable: '1',
          objName: '',
          sqlBuildType: '0',
          needPage: 0,
          resultfield: [],
          conditionfield: [],
          sortfield: []
        },
        restfulDetail: {
          requestType: 'POST',
          tokenAuth: '0',
          url:''
        }
      },
      connectList: [],
      bizSystemList: [],
      typeList: [
        {key: 'search', value: '表/视图'},
        {key: 'custom', value: '自定义sql'}
      ],
      isTableList: [
        {
          key: '0',
          value: '视图'
        },
        {
          key: '1',
          value: '表'
        }
      ], //表和视图
      objName: '', //查询数据源时表或视图名称
      tableOrViewList: [], //数据源表
      saveMethod: 'POST',
      number_opList: [
        {value: '等于', key: 'EQ'},
        {value: '大于等于', key: 'GE'},
        {value: '大于', key: 'GT'},
        {value: '小于', key: 'LT'},
        {value: '小于等于', key: 'LE'},
        {value: 'in', key: 'IN'}
      ], //运算条件数组-number
      string_opList: [
        {value: '等于', key: 'EQ'},
        {value: 'like', key: 'LK'},
        {value: 'likeEnd', key: 'LFK'},
        {value: 'in', key: 'IN'}
      ], //运算条件数组-varchar
      date_opList: [
        {value: '等于', key: 'EQ'},
        // { value: "between", key: "BETWEEN" },
        {value: '大于等于', key: 'GE'},
        {value: '小于等于', key: 'LE'}
      ], //运算条件数组-日期
      value_sourceList_list: [
        {value: '固定值', key: '2'},
        {value: '脚本', key: '3'},
        {value: '参数传入', key: '4'}
      ], //值来源数组_列表
      value_sourceList_tree: [
        {value: '固定值', key: '2'},
        {value: '动态传入', key: '4'}
      ], //值来源数组_树
      sort_typeList: [
        {value: '升序', key: 'asc'},
        {value: '降序', key: 'desc'}
      ], //排序字段升序还是降序
      param_ctList: [{value: '单行文本框', key: '1'}], //控制器的类型
      tabStatus: 'return', //设置列的条件字段、返回字段等的tabs标签页
      table: {}, //获取设置列获取字段信息
      titleSetting: '未命名-设置列', //设置列侧边栏的名称
      dialogVisibleSetting: false, //是否显示可配置设置列
      isCheckSql: false,
      selectOptions: [],
      selectOp: '',
      cmOptions: {
        showCursorWhenSelecting: true,
        value: '',
        mode: 'application/json',
        readOnly: false,
        smartIndent: true,
        autofocus: true,
        tabSize: 2,
        theme: 'eclipse',
        lineNumbers: true,
        line: true,
        inputStyle: 'textarea'
      },
      innerValidation: true,
      scriptOptions: [],
      editConditionRow: {}
    }
  },
  computed: {
    addColumnsTitle: function() {
      let statusWord = ''
      switch (this.tabStatus) {
        case 'condition':
          statusWord = '条件'
          break
        case 'return':
          statusWord = '返回'
          break
        case 'order':
          statusWord = '排序'
          break
      }
      return `将左侧所选字段添加到${statusWord}字段中`
    },
    isShowAdd() {
      return (
        this.formData.sourceType == 1 ||
        this.formData.connectionType == 'restful' ||
        (this.formData.connectionType == 'dataSource' &&
          this.dbDetail.type == 'custom')
      )
    }
  },
  mounted() {
    this.loadConnectList()
    this.loadBizSystemList()
    this.$validator = this.$root.$validator
  },
  methods: {
    loadConnectList() {
      req
        .get(
          window.context.portal + '/portal/portalConnectionManager/v1/getList'
        )
        .then(resp => {
          this.connectList = resp.data
        })
    },
    loadBizSystemList() {
      req
        .get(window.context.portal + '/portalBizSystem/v1/getList')
        .then(resp => {
          if (resp) {
            this.bizSystemList = resp.data
          }
        })
    },
    connectChanage(change) {
      if (change && change != '') {
        if (this.formData.sourceType == 1) {
          this.formData.connectionType = 'restful'
        } else {
          for (let i = 0; i < this.connectList.length; i++) {
            let item = this.connectList[i]
            if (change == item.id) {
              this.formData.connectionType = item.connectionType
              if (this.formData.connectionType == 'dataSource') {
                this.dbDetail.dsalias = item.alias
              }
              break
            }
          }
        }
      }
    },
    showDialog(id) {
      let _this = this
      if (id) {
        req
          .get('${portal}/portal/portalInterfaceManager/v1/getDetail?id=' + id)
          .then(resp => {
            this.formData = _.cloneDeep(resp.data.value)
            if (this.formData.dbDetail) {
              this.formData.dbDetail.resultfield = this.formData.dbDetail.resultfield&&JSON.parse(
                this.formData.dbDetail.resultfield
              )
              this.formData.dbDetail.conditionfield = this.formData.dbDetail.conditionfield&&JSON.parse(
                this.formData.dbDetail.conditionfield
              )
              this.formData.dbDetail.sortfield = this.formData.dbDetail.sortfield&& JSON.parse(
                this.formData.dbDetail.sortfield
              )
            }
            if (this.formData.restfulDetail) {
              this.formData.dbDetail = {}
              this.formData.dbDetail.resultfield = this.formData.restfulDetail.resultfield&&JSON.parse(
                this.formData.restfulDetail.resultfield
              )
              this.formData.dbDetail.conditionfield = this.formData.restfulDetail.conditionfield&&JSON.parse(
                this.formData.restfulDetail.conditionfield
              )
            }
            if (this.formData.restfulDetail) {
              this.restfulDetail = this.formData.restfulDetail
            } else {
              this.formData.restfulDetail = {
                requestType: 'POST',
                tokenAuth: '0',
              }
              this.restfulDetail = {
                requestType: 'POST',
                tokenAuth: '0',
              }
            }
            this.dbDetail = this.formData.dbDetail || this.formData.restfulDetail || {
              type: '',
              dsalias: '',
              isTable: '1',
              objName: '',
              sqlBuildType: '0',
              needPage: 0,
              resultfield: [],
              conditionfield: [],
              sortfield: []
            }
            this.dialogVisible = true
          })
      } else {
        this.formData = {
          refId: '',
          name: '',
          alias: '',
          desc: '',
          connectionType: '',
          dbDetail: {
            type: '',
            dsalias: '',
            isTable: '1',
            objName: '',
            sqlBuildType: '0',
            needPage: 0,
            resultfield: [],
            conditionfield: [],
            sortfield: []
          },
          restfulDetail: {
            requestType: 'POST',
            tokenAuth: '0',
            url:''
          },
          sourceType: 0
        }
        this.restfulDetail = this.formData.restfulDetail || {}
        this.dbDetail = this.formData.dbDetail || {}
        this.dialogVisible = true
      }
    },
    beforeCloseDialog() {
      this.objName = ''
      this.string_opList = [
        {value: '等于', key: 'EQ'},
        {value: 'like', key: 'LK'},
        {value: 'likeEnd', key: 'LFK'},
        {value: 'in', key: 'IN'}
      ] //运算条件数组-varchar
      this.value_sourceList_tree = [
        {value: '固定值', key: '2'},
        {value: '动态传入', key: '4'}
      ] //值来源数组_树
      this.dialogVisible = false
    },
    saveData() {
      let _this = this
      this.formData = {...this.formData,restfulDetail:this.restfulDetail,dbDetail:this.dbDetail}
      this.$validator.validateAll('PortalInterfaceManagerForm').then(result => {
        if (result) {
          if (!this.innerValidation) {
            Message.warning(
              '设置列校验失败，请进入设置列中完善信息并点击右上角保存按钮'
            )
            return
          }
          if (this.formData.connectionType == 'dataSource') {
            if (
              this.formData.dbDetail.objName == '' &&
              this.formData.dbDetail.type == 'search'
            ) {
              Message.warning('请选择表或视图')
              return
            }
            if (this.formData.dbDetail&&this.formData.dbDetail.resultfield&&
              this.formData.dbDetail.resultfield.length == 0 &&
              this.formData.dbDetail.type == 'search'
            ) {
              Message.warning('请设置需要返回的字段')
              return
            }
            if (this.formData.dbDetail&&this.formData.dbDetail.conditionfield&&
              this.formData.dbDetail.type == 'custom' &&
              this.formData.dbDetail.conditionfield.length == 0
            ) {
              Message.warning('请设置需要返回的字段')
              return
            }
          }
          //处理表单数据
          let formData = JSON.parse(JSON.stringify(_this.formData))
          //处理数据源

         if(formData.dbDetail){
           formData.dbDetail.resultfield = JSON.stringify(
            formData.dbDetail?formData.dbDetail.resultfield:[]
          )
          formData.dbDetail.conditionfield = JSON.stringify(
            formData.dbDetail?formData.dbDetail.conditionfield:[]
          )
          formData.dbDetail.sortfield = JSON.stringify(
            formData.dbDetail?formData.dbDetail.sortfield:[]
          )
          if (formData.connectionType == 'restful') {
            //处理restful接口
            formData.restfulDetail.resultfield = formData.dbDetail?formData.dbDetail.resultfield:[]
            formData.restfulDetail.conditionfield =
              formData.dbDetail?formData.dbDetail.conditionfield :[]
          }
         }
          req
            .post('${portal}/portal/portalInterfaceManager/v1/save', formData)
            .then(resp => {
              if (resp.data.state) {
                this.$message({
                  type: 'success',
                  message: resp.data.message
                })
                this.$emit('reloadList', '')
                this.beforeCloseDialog()
              }
            })
        } else {
          let arr = this.$validator.errors.items.filter(
            item => item.scope == 'PortalInterfaceManagerForm'
          )
          let errorLength = arr.length
          this.$message({
            showClose: true,
            message: `有${errorLength}个字段未通过校验，请正确填写表单内容。`,
            type: 'warning'
          })
        }
      })
    },
    afterSaveData() {
      setTimeout(() => {
        this.$emit('reloadList', '')
        this.beforeCloseDialog()
      }, 500)
    },
    changeOptions() {
      if (this.dbDetail.diySql) {
        this.dbDetail.diySql =
          this.dbDetail.diySql + this.selectOp
      } else {
        this.dbDetail.diySql = this.selectOp
      }
      this.selectOp = null
      this.$forceUpdate()
    },
    diySqlChange(e) {
      this.$forceUpdate()
    },
    handleVarSelectorClick(s, n) {
      if (n && n.data && n.data.field) {
        const fieldExp = '${' + n.data.field + '}'
        this.$refs.dataParamCode &&
          this.$refs.dataParamCode.codemirror.replaceSelection(fieldExp)
      }
    },
    //判断数据是否包含某个对象，并返回数据包含对象的下标
    indexArray(array, item) {
      if (array.length == 0) {
        return -1
      }
      for (let i = 0; i < array.length; i++) {
        if (JSON.stringify(array[i]) == JSON.stringify(item)) {
          return i
        }
      }
      return -1
    },
    //批量勾选设置列的字段
    handleSelectionChange(rows) {
      //先把所有选择的字段设置为未选中
      if (this.table.columnList.length > 0) {
        for (let i = 0; i < this.table.columnList.length; i++) {
          if (this.table.columnList[i].selected) {
            this.table.columnList[i].selected = false
          }
        }
      }
      if (rows && rows.length > 0) {
        //再根据勾选的字段设置为选中
        for (let i = 0; i < rows.length; i++) {
          let res = this.indexArray(this.table.columnList, rows[i])
          if (this.table.columnList[res]) {
            this.table.columnList[res].selected = true
          }
        }
      }
    },
    //保存设置列的内容
    save() {
      const this_ = this
      this_.$validator.validateAll('settingSave').then(result => {
        if (result) {
          for (let i in this.dbDetail.conditionfield) {
            let column = this.dbDetail.conditionfield[i]
            if (column.dbType == 'date' && column.condition == 'BETWEEN') {
              column.defaultValue += '|' + column.endDate
            }
          }
          if (!this_.dbDetail.diySql && this_.isSqlBuildType) {
            Message.warning('请添加sql语句')
            return
          }
          if (
            this.dbDetail.sortfield &&
            this.dbDetail.sortfield.length > 3
          ) {
            Message.warning('您添加的排序字段太多，最多只能添加3个排序字段！')
            return
          }
          this.dialogVisibleSetting = false
        } else {
          let arr = this_.$validator.errors.items.filter(
            item => item.scope == 'settingSave'
          )
          let errorLength = arr.length
          this_.$message({
            showClose: true,
            message: `有${errorLength}个字段未通过校验，请正确填写表单内容。`,
            type: 'warning'
          })
        }
      })
    },
    //关闭设置列弹框
    close() {
      let this_ = this
      this_.$validator.validateAll('settingSave').then(result => {
        if (!result) {
          this_.innerValidation = false
          this_.doClose()
          return
        }
        for (let i in this.dbDetail.conditionfield) {
          let column = this.dbDetail.conditionfield[i]
          if (column.dbType == 'date' && column.condition == 'BETWEEN') {
            column.defaultValue += '|' + column.endDate
          }
        }
        if (!this_.dbDetail.diySql && this_.isSqlBuildType) {
          this_.innerValidation = false
          this_.doClose()
          return
        }
        if (
          this.dbDetail.sortfield &&
          this.dbDetail.sortfield.length > 3
        ) {
          this_.innerValidation = false
          this_.doClose()
          return
        }
        this_.innerValidation = true
        this_.doClose()
      })
    },
    doClose() {
      this.dialogVisibleSetting = false
    },
    //添加设置列的字段
    addFields() {
      let column = {}
      column.fieldName = ''
      column.comment = ''
      column.columnType = 'varchar'
      if (!this.table.columnList) {
        this.table.columnList = []
      }
      this.table.columnList.push(column)
    },
    //把设置列的字段新增到条件字段、返回字段等
    addColumns() {
      //检查是否选择了列
      for (let i in this.table.columnList) {
        let c = this.table.columnList[i]
        if (c.selected) break
        if (i == this.table.columnList.length - 1) {
          if (i == this.table.columnList.length - 1) {
            Message.warning('请选择左边的列')
          }
        }
      }
      //判断tabs标签页是否选择了条件字段
      if (this.tabStatus == 'condition') {
        for (let i in this.table.columnList) {
          let c = this.table.columnList[i]
          if (!c.selected) continue
          let column = this.getCondition(c)
          let show = this.judgeAryData(
            this.dbDetail.conditionfield,
            column
          )
          if (show) {
            this.dbDetail.conditionfield.push(column)
          }
        }
        //去除重复项
        this.dbDetail.resultfield.unique(function(a, b) {
          return a.field == b.field
        })
        //判断tabs标签页是否选择了返回字段
      } else if (this.tabStatus == 'return') {
        for (let i in this.table.columnList) {
          let c = this.table.columnList[i]
          if (!c.selected) continue
          let column = this.getReturn(c)
          let show = this.judgeAryData(
            this.dbDetail.resultfield,
            column
          )
          if (show) {
            this.dbDetail.resultfield.push(column)
          }
        }
        //去除重复项
        this.dbDetail.resultfield.unique(function(a, b) {
          return a.field == b.field
        })
      } else if (this.tabStatus == 'order') {
        let errorMsg = ''
        //判断tabs标签页是否选择了排序字段
        for (let i in this.table.columnList) {
          let c = this.table.columnList[i]
          if (!c.selected) continue

          //大文本类型与一些未明确的字段类型不可作为排序字段
          if (c.columnType == 'clob' || !c.columnType) {
            errorMsg += c.fieldName + '  '
            continue
          }
          let column = this.getOrder(c)

          let show = this.judgeAryData(this.dbDetail.sortfield, column)
          if (show) {
            this.dbDetail.sortfield.push(column)
          }
        }
        if (errorMsg) {
          this.$message.error(
            '字段:' + errorMsg + '的字段类型不支持作为排序字段'
          )
        }
        //去除重复项
        this.dbDetail.sortfield.unique(function(a, b) {
          return a.field == b.field
        })
      }
    },
    getCondition(c) {
      let column = {}
      column.field = c.fieldName
      column.comment = c.comment
      column.condition = 'EQ'
      column.dbType = c.columnType
      column.defaultType = '2'
      column.defaultValue = ''
      return column
    },
    getReturn(c) {
      let column = {}
      column.field = c.fieldName
      column.comment = c.comment
      column.idKey = '0'
      column.AggFuncOp = '' //合计函数运算符
      column.columnType = c.columnType //字段类型
      return column
    },
    getOrder(c) {
      let column = {}
      column.field = c.fieldName
      column.sortType = 'asc'
      column.comment = c.comment
      return column
    },
    //判断是否存在重复字段
    judgeAryData(data, column) {
      let show = true
      if(data){
        for (var i = 0; i < data.length; i++) {
          if (
            data[i].field == column.field &&
            data[i].comment == column.comment
          ) {
            show = false
            break
          }
        }
      }
      return show
    },
    //删除字段
    deleteSetting(list, index) {
      list.splice(index, 1)
    },
    sourceListChang(item) {
      //条件字段是参数传入或动态传入，但是固定值还有值，则清空固定值
      if (
        (item.defaultType == '1' || item.defaultType == '4') &&
        item.defaultValue != ''
      ) {
        for (let i = 0; i < this.dbDetail.conditionfield.length; i++) {
          if (
            (this.dbDetail.conditionfield[i].defaultType == '1' ||
              this.dbDetail.conditionfield[i].defaultType == '4') &&
            this.dbDetail.conditionfield[i].defaultValue != ''
          ) {
            this.dbDetail.conditionfield[i].defaultValue = ''
          }
        }
      }
      //如果选中了脚本类型，则加载脚本对话框
      if (item.defaultType == '3' && this.scriptOptions.length === 0) {
        item.defaultValue = ''
      }
    },
    //打开设置列弹框
    showSettingDialog() {
      this.tabStatus = 'return' //默认打开返回字段
      this.dialogVisibleSetting = true
      if (
        this.dbDetail.conditionfield &&
        this.dbDetail.conditionfield.length > 0 &&
        this.selectOptions.length == 0
      ) {
        this.dbDetail.conditionfield.forEach(item => {
          if (item.defaultType == '1') {
            let selectOp = {}
            selectOp.field = item.field
            selectOp.comment = item.comment
            this.selectOptions.push(selectOp)
          }
        })
      }
      if (
        this.dbDetail.sqlBuildType == '0' ||
        !this.dbDetail.sqlBuildType
      ) {
        this.isSqlBuildType = false
      } else {
        this.isSqlBuildType = true
      }
      this.titleSetting = '设置列'
      //打开设置如果是数据源，先获取数据源的字段
      if (
        this.formData.connectionType == 'dataSource' &&
        this.dbDetail.type == 'search'
      ) {
        let params = {
          dsalias: this.dbDetail.dsalias,
          isTable: this.dbDetail.isTable,
          objName: this.dbDetail.objName
        }
        const this_ = this
        //获取数据源的字段
        let url = window.context.form + '/form/customQuery/v1/getTable'
        req.post(url, params).then(function(data) {
          this_.table = data.data.table
          this_.handleFilterColumn()
        })
      }
      //自定义sql
      if (
        this.formData.connectionType == 'dataSource' &&
        this.dbDetail.type == 'custom'
      ) {
        this.tabStatus = 'condition' //默认打开条件字段
        this.value_sourceList_tree = [{key: '固定值', value: '2'}]
        if (this.dbDetail.conditionfield) {
          this.dbDetail.conditionfield.forEach(item => {
            if (item.defaultValue == '1') {
              let selectOp = {}
              selectOp.field = item.field
              selectOp.comment = item.comment
              this.selectOptions.push(selectOp)
            }
          })
        }
        //字段设置为空
        this.table = {columnList: []}
      }
      //打开设置列如果不是数据源
      if (this.formData.connectionType == 'restful') {
        //值来源数组_树改变如下
        this.value_sourceList_tree = [{key: '固定值', value: '2'}]
        //判断REST接口是否是GET请求
        if (this.restfulDetail.requestType == 'GET') {
          //运算条件数组-varchar改变如下
          this.string_opList = [{value: '等于', key: 'EQ'}]
        } else {
          //运算条件数组-varchar改变如下
          this.string_opList = [{value: 'like', key: 'LK'}]
        }
        if (this.dbDetail.conditionfield) {
          this.dbDetail.conditionfield.forEach(item => {
            if (item.defaultValue == '1') {
              let selectOp = {}
              selectOp.field = item.field
              selectOp.comment = item.comment
              this.selectOptions.push(selectOp)
            }
          })
        }
        //字段设置为空
        this.table = {columnList: []}
      }
    },
    //查询数据源表或视图
    getByDsObjectName() {
      const this_ = this
      if (this.formData.refId == null || this.formData.refId == '') {
        Message.warning('请选择连接管理')
        return
      }
      this.params = {}
      this.params.dsalias = this.dbDetail.dsalias
      this.params.isTable = this.dbDetail.isTable
      this.params.objName = this.objName
      let url = window.context.form + '/form/customQuery/v1/getByDsObjectName'
      req.post(url, this_.params).then(function(data) {
        this_.tableOrViewList = [] //每次查询前先设置为空
        if (!data || data.data.length == 0) {
          Message.warning('该数据源中未查询到表或视图')
          return
        }
        Message.success('查询成功')
        for (let i = 0; i < data.data.length; i++) {
          data.data[i].comment =
            data.data[i].name + '(' + data.data[i].comment + ')'
          this_.tableOrViewList.push(data.data[i])
        }
        //选择表或试图时默认选择第一个
        this_.dbDetail.objName = this_.tableOrViewList[0].name
      })
    },
    // 设置参数的面板中tab切换时
    handleTabSwitch(m) {
      if (m.name == 'dataParam') {
        this.$refs.dataParamCode && this.$refs.dataParamCode.refresh()
      }
      // 选中自定义SQL tab
      if (m.name == 'custom') {
        // 清空自定义sql条件字段
        this.selectOptions.splice(0, this.selectOptions.length)
        if (this.dbDetail.conditionfield) {
          this.dbDetail.conditionfield.forEach(item => {
            if (item.defaultType == '1') {
              let selectOp = {}
              selectOp.field = item.field
              selectOp.comment = item.comment
              this.selectOptions.push(selectOp)
            }
          })
        }
      }
    },
    handleFilterColumn() {
      for (let i = this.table.columnList.length - 1; i >= 0; i--) {
        if (
          this.table.columnList[i].fieldName &&
          this.table.columnList[i].fieldName.toLowerCase() == 'f_form_data_rev_'
        ) {
          this.table.columnList.splice(i, 1)
        }
      }
    },
    fillToCondition(row, event, column) {
      if (this.tabStatus == 'condition') {
        let col = this.getCondition(row)
        if (this.judgeAryData(this.dbDetail.conditionfield, col)) {
          this.dbDetail.conditionfield.push(col)
        } else {
          this.$message.warning('该字段已存在')
        }
      } else if (this.tabStatus == 'return') {
        let col = this.getReturn(row)
        if (this.judgeAryData(this.dbDetail.resultfield, col)) {
          this.dbDetail.resultfield.push(col)
        } else {
          this.$message.warning('该字段已存在')
        }
      } else if (this.tabStatus == 'order') {
        if (!row.columnType == 'clob' || !row.columnType) {
          this.$message.warning('该字段不支持排序')
          return
        }
        let col = this.getOrder(row)
        if (this.judgeAryData(this.dbDetail.sortfield, col)) {
          this.dbDetail.sortfield.push(col)
        } else {
          this.$message.warning('该字段已存在')
        }
      }
    },
    handleScriptSelected(script, name) {
      this.editConditionRow.defaultValue =
        this.editConditionRow.defaultValue + script
    },
    showScriptDialog(row) {
      this.$refs.eipScriptDialog.showDialog()
      this.editConditionRow = row
    },
    // 表格单击切换选中状态
    clickRow(row) {
      this.$refs.htTableSetting.toggleRowSelection(row)
    },
    checkSql() {
      if (!this.dbDetail.diySql) {
        this.$message({type: 'warning', message: '请输入sql语句'})
        return
      }
      let checkSql = JSON.stringify(this.dbDetail.diySql)
      checkSql = checkSql.replace(/\s/g, '')
      if (checkSql.toLocaleUpperCase().indexOf('ORDERBY') != -1) {
        this.$message({
          type: 'warning',
          message: '请检查sql语句，不能包含order by排序语句'
        })
        return
      }
      if (checkSql.toLocaleUpperCase().indexOf('GROUPBY') != -1) {
        this.$message({
          type: 'warning',
          message: '请检查sql语句，不能包含group by分组语句'
        })
        return
      }
      let param = {
        sql: this.dbDetail.diySql,
        dsName: this.dbDetail.dsalias
      }
      form.checkSql(param).then(response => {
        if (response.state) {
          this.$message({type: 'success', message: response.message})
          this.isCheckSql = true
        }
      })
    },
    handleSourceTypeChange() {
      this.formData.refId = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.sp-manager__dialog /deep/ .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
}

.ht {
  width: 320px;
}
</style>
