<template>
  <app-dialog
    v-model="visible"
    :fullscreen="true"
    :loading="loading"
    :title="title"
    append-to-body
    class="detail-dialog"
    width="550px"
    @cancel="onCancel"
    @confirm="onConfirm"
  >
    <el-form ref="form" :label-position="labelPosition" :model="form" :rules="rules" label-width="110px">
      <el-divider content-position="left"><i class="el-icon-tickets" style="color: rgb(24, 144, 255)" /><span
        class="divider-top"
      >基础信息</span></el-divider>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw" type="flex">
        <app-filter-item label="接口名称" prop="apiName">
          <el-input v-model="form.apiName" clearable placeholder="请输入" />
        </app-filter-item>
        <app-filter-item label="数据库" prop="dbAlias">
          <!--          <el-input v-model="form.dbAlias" clearable placeholder="请输入" />-->
          <el-select v-model="form.dbAlias" filterable placeholder="请选择">
            <el-option v-for="item in sqloptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </app-filter-item>
      </el-row>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw; margin-top: 1vh" type="flex">
        <app-filter-item :span="12" label="接口地址" prop="apiUrl">
          <el-input v-model="form.apiUrl" clearable placeholder="请输入" />
        </app-filter-item>
      </el-row>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw; margin-top: 1vh" type="flex">
        <app-filter-item :span="12" label="接口描述" prop="apiDesc">
          <el-input v-model="form.apiDesc" clearable placeholder="请输入" />
        </app-filter-item>
      </el-row>
      <el-divider content-position="left"><i class="el-icon-setting" style="color: rgb(24, 144, 255)" /><span
        class="divider-top"
      >接口配置</span></el-divider>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw" type="flex">
        <app-filter-item :span="6" label="接口查询方式" prop="apiQureyType">
          <el-radio-group v-model="form.apiQureyType">
            <!--            <el-radio-button v-for="(radio, index) in options" :key="index" :label="radio">{{ radio }}</el-radio-button>-->
            <el-radio-button v-for="radio in options" :key="radio.value" :label="radio.value">{{ radio.label }}
            </el-radio-button>
          </el-radio-group>
        </app-filter-item>
        <app-filter-item :span="6" label="请求方式" prop="apiMode">
          <el-radio-group v-model="form.apiMode">
            <!--            <el-radio-button v-for="radio in tableNameList" :key="radio.value" :label="radio.value">{{ radio.label }} </el-radio-button>-->
            <el-radio-button v-for="(radio, index) in tableNameList" :key="radio.label" :label="radio">{{ radio.label
            }}
            </el-radio-button>
          </el-radio-group>
        </app-filter-item>
      </el-row>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw; margin-top: 1vh" type="flex">
        <app-filter-item :span="16" label="SQL查询语句" prop="apiSql">
          <el-input v-model="form.apiSql" placeholder="请在此输入sql代码" style="background-color: black; color: white"
                    type="textarea"
          />
        </app-filter-item>
      </el-row>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw; margin-top: 5vh" type="flex">
        <app-filter-item :span="24" label="请求参数说明" prop="requestParams">
          <!--          <request-description v-model="form.requestParams" />-->
          <!--          <el-input v-model="form.requestParams" placeholder="请在此输入sql代码" style="background-color: black; color: white;" type="textarea" />-->
          <el-table :data="form.params" border style="width: 100%" @selection-change="addJsonSelectionChange">
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" width="150">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">参数名称</span>
                <i style="color: #f56c6c">*</i>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'params.' + scope.$index + '.param'">
                  <el-input v-model="scope.row.param" autocomplete="off" type="text" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="625">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">说明</span>
                <i style="color: #f56c6c">*</i>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'params.' + scope.$index + '.comment'">
                  <el-input v-model="scope.row.comment" autocomplete="off" style="width: 510px" type="text" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="150">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">类型</span>
                <i style="color: #f56c6c">*</i>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'params.' + scope.$index + '.type'">
                  <el-select v-model="scope.row.type" placeholder="请选择">
                    <el-option v-for="item in typeoptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="110">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">是否必填</span>
                <i style="color: #f56c6c">*</i>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'params.' + scope.$index + '.required'">
                  <el-switch v-model="scope.row.required" active-color="#13ce66" inactive-color="#ff4949" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" width="200">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">操作</span>
                <i style="color: #f56c6c">*</i>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'params.' + scope.$index + '.value'">
                  <el-button circle icon="el-icon-plus" type="primary" @click="addTableItem" />
                  <el-button circle icon="el-icon-delete" type="danger" @click="delTableItem" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </app-filter-item>
        <app-filter-item :span="24" label="请求头说明" prop="requestHeader">
          <request-header />
        </app-filter-item>
        <app-filter-item :span="16" label="请求参数样例" prop="requestExample">
          <el-input v-model="form.requestExample" clearable placeholder="请输入javascript代码"
                    style="background-color: black; color: white" type="textarea"
          />
        </app-filter-item>
      </el-row>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw; margin-top: 5vh" type="flex">
        <app-filter-item :span="24" label="返回参数说明" prop="responseParams">
          <return-description />
        </app-filter-item>
        <app-filter-item :span="16" label="返回数据样例" prop="responseExample">
          <el-input v-model="form.responseExample" clearable placeholder="请输入javascript代码"
                    style="background-color: black; color: white" type="textarea"
          />
        </app-filter-item>
      </el-row>
      <el-row :gutter="15" style="flex-wrap: wrap; margin-left: 5vw; margin-top: 5vh" type="flex">
        <app-filter-item :span="24" label="响应状态码信息" prop="responseStatus">
          <response-message />
        </app-filter-item>
      </el-row>
    </el-form>
  </app-dialog>
</template>

<script>
import API from '@/api/business/dataServiceAPI';
import dialogMixin from '@/mixins/dialog.js';
// 请求参数说明组件
// 请求头说明
import RequestHeader from '@/views/dataResource/dataServices/dataServiceAPI/components/RequestHeader.vue';
// 返回参数说明组件
import ReturnDescription from '@/views/dataResource/dataServices/dataServiceAPI/components/ReturnDescription.vue';
// 响应状态码组件
import ResponseMessage from '@/views/dataResource/dataServices/dataServiceAPI/components/ResponseMessage.vue';

export default {
  name: 'CompanyDialog',
  components: { RequestHeader, ReturnDescription, ResponseMessage },
  mixins: [dialogMixin],
  props: {
    selectedRows: {
      type: Array,
      default: () => [],
    },
    addId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      tabItemId: 1, // 表格数据的 id
      labelPosition: 'left',
      timeValue: '',
      qurey: '',
      mode: '',
      sqloptions: [],
      options: [
        { label: '分页', value: 1 },
        { label: '不分页', value: 0 },
      ],
      typeoptions: [
        { value: 'string', label: 'string' },
        { value: 'number', label: 'number' },
        { value: 'boolean', label: 'boolean' },
        { value: 'integer', label: 'integer' },
      ],
      form: {
        sourceType: '1',
        sql: '',
        apiQureyType: '',
        // 本应该将其改为初始化空数组
        params: [
          { param: 'name_', comment: '学生姓名', type: 'string', required: 'false' },
          { param: 'page', comment: '页码', type: 'integer', required: 'false' },
          { param: 'limit', comment: '每页大小', type: 'integer', required: 'false' },
        ],
        // params: [],
      },
      tableNameList: ['GET', 'POST'],
      rules: {
        apiName: [{ required: true, message: '接口名称不能为空', trigger: 'blur' }],
        apiUrl: [{ required: true, message: '接口地址不能为空', trigger: 'blur' }],
        apiQureyType: [{ required: true, message: '接口查询方式不能为空', trigger: 'change' }],
        apiMode: [{ required: true, message: '请求方式不能为空', trigger: 'change' }],
        apiSql: [{ required: true, message: 'SQL查询语句不能为空', trigger: 'blur' }],
        dbAlias: [{ required: true, message: '请选择数据源', trigger: 'change' }],
      },
      loading: false,
    };
  },
  created() {
    this.fetchRequestParams();
    this.onConfirm();
  },

  methods: {
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    initData(data) {
      // console.log('idididi', this.addId); //进页面打印id
      const orgForm = this.$options.data().form;
      this.form = { ...orgForm, ...data };
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      this.selectSql();
    },
    // 数据源接口调用
    selectSql() {
      API.addSourceData()
        .then((res) => {
          console.log('cacacacs', res); // 数据库
          console.log(1111111111111111111111);
          this.sqloptions = res.data.map((data) => {
            const form = {
              // label: data.alias,
              // value: data.id,
              label: data.name,
              value: data.alias,
            };
            return form;
          });
          // console.log(res.rows);
          console.log('数据源', this.sqloptions);
          // console.log(res.value[0]);
        })
        .catch((error) => {
          console.error('获取数据源失败', error);
        });
    },
    fetchRequestParams() {
      // // 模拟从后端获取的数据;
      const requestParams = [{ param: 'name_', comment: '学生姓名', type: 'string', required: 'false' }];
      this.form.params = requestParams;

      // 此处有错误---------------
      // console.log('----1', this.form.params);
      // console.log('----333', this.form.params[0].param);
    },
    RndNum(n) {
      // 生成随机数
      let rdmNum = '';
      for (let i = 0; i < n; i++) {
        rdmNum += Math.floor(Math.random() * 10); // [0,10)的整数
      }
      return rdmNum;
    },
    addJsonSelectionChange(val) {
      this.addJsonMultiple = val;
    },
    // 添加
    addTableItem() {
      this.tabItemId = `T${this.RndNum(6)}`; // 生成以T开头的七位随机数
      this.form.params.push({
        name: '',
        value: '',
        tabItemId: this.tabItemId,
      });
    },
    // 删除
    delTableItem() {
      // 确认删除
      if (this.addJsonMultiple.length > 0) {
        const arrs = [];
        const ids = this.addJsonMultiple.map((val) => val.tabItemId); // 拿到选中的数据id,
        this.form.params.forEach((item) => {
          if (!ids.includes(item.tabItemId)) {
            // 当id在params中，表示数据被选中，该将其删除，即将不被选中的保留
            arrs.push(item);
          }
        });
        this.form.params = arrs;
      } else {
        this.$message.warning('请选择要删除的数据');
      }
    },
    //
    // 取消按钮
    onCancel() {
      this.visible = false;
      this.form = {};
    },
    // 确定按钮-新增后接口调用，展示在列表
    onConfirm() {
      // this.$refs.form.validate(async valid => {
      //   if (valid) {
      //     this.form.catalogId = this.addId;
      //     API.addAction(this.form, false)
      //       .then(res => {
      //         console.log(res);
      //       })
      //       .catch(error => {
      //         console.error('获取数据失败', error);
      //       });
      //     this.loading = false;
      //   } else {
      //     console.log('表单验证失败，请检查所有必填项');
      //     return false;
      //   }
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.divider-top {
  color: rgb(24, 144, 255);
  font-weight: bold;
  font-size: 16px;
  margin-left: 5px;
}

.custom-textarea {
  background-color: black;
  color: white;
}

.detail-dialog {
}

.el-form {
  height: 85vh;
  width: 80%;
  margin: 0 auto;
  border: solid 1px #e0e0e0;
  background-color: #fff;
  border-radius: 5px;
  overflow-y: auto;
  overflow-x: hidden;
}

.button-footer {
  margin-top: 20px;
  //border: solid 1px red;
  position: absolute;
  right: 150px;
  bottom: 0;
}

.el-dialog__header {
  border: solid 1px red;
}
</style>
