<template>
  <div class="api-edit-3">
    <div class="param-setting">
      <div class="panel-title flex-between">
        参数设置
        <el-button size="mini" type="primary" @click="onTableChangee(form.queryTable)">重新获取</el-button>
      </div>
      <el-table :data="queryParam" border height="calc(100% - 45px)" size="mini">
        <el-table-column label="字段名" prop="columnName"></el-table-column>
        <el-table-column label="字段类型">
          <template v-slot="{ row }">{{ getColumnType(row) }}</template>
        </el-table-column>
        <el-table-column label="是否必填">
          <template v-slot="{ row }">
            <el-radio-group v-model="row.optionalStatus">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="参数名称">
          <template v-slot="{ row }">
            <el-input v-model="row.title" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="参数code">
          <template v-slot="{ row }">
            <el-input v-model="row.paramName" size="mini"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template v-slot="{ row }">
            <el-button size="mini" type="danger" @click="del(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="form p-5" style="background-color: #fff">
      <div class="panel-title">基础设置</div>
      <el-form label-width="90px" size="mini">
        <el-form-item label="接口名">
          <el-input v-model="form.apiName"></el-input>
        </el-form-item>
        <el-form-item label="接口key">
          <el-input v-model="form.apiKey"></el-input>
        </el-form-item>
        <el-form-item label="接口分类">
          <el-select v-model="form.categoryId" filterable>
            <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="接口状态">
          <el-radio-group v-model="form.apiStatus">
            <el-radio :label="0">下线</el-radio>
            <el-radio :label="1">上线</el-radio>
            <el-radio :label="2">故障</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所用数据源">
          <el-select v-model="form.datasourceId" filterable @change="onSourceChange">
            <el-option
              v-for="item in dataSourceList"
              :key="item.id"
              :label="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 @change="onTableChange">
            <el-option
              v-for="(table, i) of tableList"
              :key="i"
              :label="table.tableComments + ' ' + table.tableViewName"
              :value="table.tableViewName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <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>
    </div>
    <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>
  </div>
</template>
<script>
import * as reportApis from '@/api/report/report';
import { Base64 } from 'js-base64';
import {dataapiRelease} from "@/api/report/report";
import {typeList} from "@/api/apimngr";

export default {
  data() {
    return {
      editType: 'add',
      form: {
        apiType: 3,
        categoryId: '',
        apiUrl: '',
        apiKey: '',
        apiName: '',
        datasourceId: '',
        queryTable: '',
        apiStatus: 1,
      },
      queryParam: [],
      dataSourceList: [],
      categoryList: [],
      tableList: [],
      fieldList: [],
      typeList: [
        { type: 'STRING', label: '字符串' },
        { type: 'DATETIME', label: '时间' },
        { type: 'INT', label: '整型数字' },
        { type: 'LONG', label: '长整型数字' },
        { type: 'FLT', label: '浮点数字' },
      ],

      // API发布
      showPush: false,
      //接口类型列表
      apiTypeList: [],
      pushFrom: {
        name: '', //接口名称
        url: '', //接口地址
        callLimit: 10000, //调用次数
        qpsLimit: 2, //qps限制
        status: 1, //状态
        apiTypeId: 0, //接口类型
        description: '', //描述
        version: '', //版本
        extJson: '', //扩展json
      },
    };
  },
  created() {
    // 获取数据源列表
    reportApis.reportdatasourceList().then(res => {
      this.dataSourceList = res.data;
    });
    // 获取接口分类列表
    reportApis.dataapicategoryList().then(res => {
      this.categoryList = res.data;
    });
    this.init();
  },
  methods: {
    init() {
      let { id } = this.$route.query;
      if (!id) return;
      this.editType = 'update';
      reportApis.dataapiDetail(id).then(res => {
        let { apiType, categoryId, apiKey, apiName, datasourceId, queryTable, queryParam, apiStatus,apiUrl } = res.data;
        this.queryParam = JSON.parse(queryParam);
        this.form = { id, apiType, categoryId, apiKey, apiName, datasourceId, queryTable, apiStatus,apiUrl };
        // console.log(datasourceId)
        reportApis.listViewsByDataSource({ datasourceId: datasourceId, current: 1, size: 10000 }).then(async res => {
          this.tableList = res.data.records;
          await this.onTableChange(queryTable);
        });
      });
    },
    onSave() {
      let data = { ...this.form };
      if (!data.categoryId) {
        return this.$message({ type: 'warning', message: '请选择分类' });
      }
      if (!data.apiKey) {
        return this.$message({ type: 'warning', message: '请输入接口key' });
      }
      if (!data.apiName) {
        return this.$message({ type: 'warning', message: '请输入接口名' });
      }
      if (!data.datasourceId) {
        return this.$message({ type: 'warning', message: '请选择数据源' });
      }
      if (!data.queryTable) {
        return this.$message({ type: 'warning', message: '请选择数据表' });
      }
      data.queryParam = JSON.stringify(this.queryParam);
      reportApis.dataapiSubmit(Base64.encode(JSON.stringify(data))).then(res => {
        this.$message({ type: 'success', message: '保存成功' });
        if (this.editType == 'add') {
          this.editType = 'update';
          this.$router.push({ path: '/apimngr/apiedit3', query: { id: res.data.data.id } });
        } else {
          setTimeout(this.init, 500);
        }
      });
    },
    onBack() {
      this.$router.back();
    },
    getColumnType(row) {
      let label = this.typeList.find(i => i.type == row.columnType).label;
      if (row.columnType == 'STRING') {
        let field = this.fieldList.find(i => i.columnName == row.columnName);
        if (field) {
          let size = this.fieldList.find(i => i.columnName == row.columnName).columnSize;
          label += `（${size}）`;
        }
      }
      return label;
    },
    // 选择数据表时
    async onTableChange(tableViewName) {
      reportApis.listColumnsByDatasource({ datasourceId: this.form.datasourceId, tableViewName }).then(res => {
        this.fieldList = res.data;
        if (!this.queryParam.length) {
          this.queryParam = this.fieldList.map(item => {
            return {
              title: item.columnComments,
              columnName: item.columnName,
              paramName: item.columnName,
              columnType: item.detailColumnType,
              optionalStatus: item.nullAbleStatus,
            };
          });
        }
      });
    },
    async onTableChangee(tableViewName) {
      reportApis.listColumnsByDatasource({ datasourceId: this.form.datasourceId, tableViewName }).then(res => {
        this.fieldList = res.data;
        this.queryParam = this.fieldList.map(item => {
          return {
            title: item.columnComments,
            columnName: item.columnName,
            paramName: item.columnName,
            columnType: item.detailColumnType,
            optionalStatus: item.nullAbleStatus,
          };
        });
      });
    },
    onSourceChange(id) {
      reportApis.listViewsByDataSource({ datasourceId: id, current: 1, size: 10000 }).then(res => {
        this.tableList = res.data.records;
        this.form.queryTable = '';
      });
    },
    del(row) {
      this.queryParam = this.queryParam.filter(i => i.columnName != row.columnName);
    },

    onPush() {
      this.showPush = true;
      typeList().then(res => {
          this.apiTypeList = res.data;
          this.showPush = true;
          this.pushFrom = {
            name: this.form.apiName, //接口名称
            url: 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.queryParam.map(item => {
            return {
              name: item.columnName,
              type: item.columnType,
              required: item.optionalStatus == 1 ? '否' : '是',
              description: item.title,
              default: item.columnName,
            };
          });
          // let returnParams = Object.keys(this.returenData.data.data[0]).map(item => {
          //   return {
          //     name: item,
          //     type: 'string',
          //     description: item,
          //   };
          // });
          // let response = {
          //   code: '200',
          //   message: '成功',
          //   data: this.returenData.data.data.slice(0, 20),
          // };
          this.pushFrom.extJson = {
            method: 'POST',
            type:'add',
            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' });
      }
      this.pushFrom.extJson = JSON.stringify(this.pushFrom.extJson);
      dataapiRelease(this.pushFrom).then(res => {
        this.$message({ message: '已提交', type: 'success' });
        this.showPush = false;
      });
    },
  },
};
</script>
<style lang="scss">
.api-edit-3 {
  background: #eee;
  padding: 10px !important;
  height: calc(100vh - 50px) !important;
  display: flex;

  .panel-title {
    margin: 10px 20px;
    font-size: 14px;
    color: #777;
    font-weight: 600;
  }

  .param-setting {
    flex: 1;
    overflow-y: auto;
  }

  .form {
    margin-left: 20px;

    .btns {
      margin-top: 30px;
      display: flex;
      justify-content: space-evenly;
    }
  }
}
</style>
