<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" disabled 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-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 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, 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">
          <code-editor v-model="form.apiSql" :full-screen="true" disabled="1" language="sql"
                       style="min-height: 100px"
          />
        </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">
          <el-table :data="form.requestParams" border style="width: 100%" @selection-change="addJsonRequestParams">
            <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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestParams.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestParams.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestParams.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestParams.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestParams.' + scope.$index + '.value'">
                  <el-button circle icon="el-icon-plus" type="primary" @click="addTableRequestParams" />
                  <el-button circle icon="el-icon-delete" type="danger" @click="delTableRequestParams" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </app-filter-item>
        <app-filter-item :span="24" label="请求头说明" prop="requestHeader">
          <el-table :data="form.requestHeader" border style="width: 100%" @selection-change="addJsonRequestHeader">
            <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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestHeader.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestHeader.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestHeader.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestHeader.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'requestHeader.' + scope.$index + '.value'">
                  <el-button circle icon="el-icon-plus" type="primary" @click="addTableRequestHeader" />
                  <el-button circle icon="el-icon-delete" type="danger" @click="delTableRequestHeader" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </app-filter-item>
        <app-filter-item :span="16" label="请求参数样例" prop="requestExample">
          <code-editor v-model="form.requestExample" :full-screen="true" disabled="1" language="sql"
                       style="min-height: 100px"
          />
        </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">
          <el-table :data="form.responseParams" border style="width: 100%" @selection-change="addJsonResponseParams">
            <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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'responseParams.' + 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="735">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">说明</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'responseParams.' + 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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'responseParams.' + 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="200">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">操作</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'responseParams.' + scope.$index + '.value'">
                  <el-button circle icon="el-icon-plus" type="primary" @click="addTableResponseParams" />
                  <el-button circle icon="el-icon-delete" type="danger" @click="delTableResponseParams" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </app-filter-item>
        <app-filter-item :span="16" label="返回数据样例" prop="responseExample">
          <code-editor v-model="form.responseExample" :full-screen="true" disabled="1" language="sql"
                       style="min-height: 100px"
          />
        </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">
          <el-table :data="form.responseStatus" border style="width: 100%" @selection-change="addJsonResponseStatus">
            <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>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'responseStatus.' + 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="885">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">说明</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'responseStatus.' + 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="200">
              <template slot="header" slot-scope="scope">
                <span style="color: #2d65dc">操作</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'responseStatus.' + scope.$index + '.value'">
                  <el-button circle icon="el-icon-plus" type="primary" @click="addTableResponseStatus" />
                  <el-button circle icon="el-icon-delete" type="danger" @click="delTableResponseStatus" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </app-filter-item>
      </el-row>
    </el-form>
  </app-dialog>
</template>

<script>
import API from '@/api/business/shareApi';
import dialogMixin from '@/mixins/dialog.js';
import codeEditor from '@/components/codeEditor/index.vue';

export default {
  name: 'DetailDialog',
  components: { codeEditor },
  mixins: [dialogMixin],
  props: {
    selectedRows: {
      type: Array,
      default: () => [],
    },
    relatedId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      addJsonMultipleRequestParams: [],
      addJsonMultipleRequestHeader: [],
      addJsonMultipleResponseParams: [],
      addJsonMultipleResponseStatus: [],
      tabItemId: 1, // 表格数据的 id
      labelPosition: 'left',
      timeValue: '',
      qurey: '',
      mode: '',
      sqloptions: [],
      options: [
        { label: '分页', value: 1 },
        { label: '不分页', value: 0 },
      ],
      form: {
        sourceType: '1',
        sql: '',
        apiQureyType: '',
      },
      typeoptions: [
        { value: '1', label: '字符串' },
        { value: '2', label: '数字型' },
        { value: '3', label: '日期' },
        { value: '4', label: '时间' },
      ],
      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.onConfirm();
  // },

  methods: {
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    initData(data) {
      // console.log('idididi', data); // 进页面打印id
      // console.log('idididi', data.requestParams); // 进页面打印id
      const orgForm = this.$options.data().form;
      this.form = { ...orgForm, ...data };
      // 重点修改这里，确保正确赋值 requestParams 数据
      // 请求参数说明
      if (data.requestParams && typeof data.requestParams === 'string') {
        try {
          const parsedParams = JSON.parse(data.requestParams);
          if (Array.isArray(parsedParams)) {
            this.form.requestParams = parsedParams.map((item) => ({
              param: item.param || '',
              comment: item.comment || '',
              type: item.type || '',
              required: item.required !== 'false', // 处理布尔值转换
            }));
          }
        } catch (error) {
          console.error('解析 requestParams 数据出错:', error);
        }
      }
      // 请求头说明
      if (data.requestHeader && typeof data.requestHeader === 'string') {
        try {
          const parsedParams = JSON.parse(data.requestHeader);
          if (Array.isArray(parsedParams)) {
            this.form.requestHeader = parsedParams.map((item) => ({
              param: item.param || '',
              comment: item.comment || '',
              type: item.type || '',
              required: item.required !== 'false', // 处理布尔值转换
            }));
          }
        } catch (error) {
          console.error('解析 requestHeader 数据出错:', error);
        }
      }
      // 返回参数说明
      if (data.responseParams && typeof data.responseParams === 'string') {
        try {
          const parsedParams = JSON.parse(data.responseParams);
          if (Array.isArray(parsedParams)) {
            this.form.responseParams = parsedParams.map((item) => ({
              param: item.param || '',
              comment: item.comment || '',
              type: item.type || '',
            }));
          }
        } catch (error) {
          console.error('解析 responseParams 数据出错:', error);
        }
      }
      // 响应状态码信息
      if (data.responseStatus && typeof data.responseStatus === 'string') {
        try {
          const parsedParams = JSON.parse(data.responseStatus);
          if (Array.isArray(parsedParams)) {
            this.form.responseStatus = parsedParams.map((item) => ({
              param: item.param || '',
              comment: item.comment || '',
            }));
          }
        } catch (error) {
          console.error('解析 responseStatus 数据出错:', error);
        }
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      this.selectSql();
    },
    // 数据源接口调用
    selectSql() {
      return API.addSourceData()
        .then((res) => {
          console.log('cacacacs', res); // 数据库
          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);
        })
        .catch((error) => {
          console.error('获取数据源失败', error);
        });
    },
    RndNum(n) {
      // 生成随机数
      let rdmNum = '';
      for (let i = 0; i < n; i++) {
        rdmNum += Math.floor(Math.random() * 10); // [0,10)的整数
      }
      return rdmNum;
    },
    // 请求参数说明-------------------------------
    addJsonRequestParams(val) {
      this.addJsonMultipleRequestParams = val;
    },
    // 添加
    addTableRequestParams() {
      this.tabItemId = `T${this.RndNum(6)}`; // 生成以T开头的七位随机数
      this.form.requestParams.push({
        name: '',
        value: '',
        tabItemId: this.tabItemId,
      });
    },
    // 删除
    delTableRequestParams() {
      // 确认删除
      if (this.addJsonMultipleRequestParams.length > 0) {
        const arrs = [];
        const ids = this.addJsonMultipleRequestParams.map((val) => val.tabItemId); // 拿到选中的数据id,
        this.form.requestParams.forEach((item) => {
          if (!ids.includes(item.tabItemId)) {
            // 当id在params中，表示数据被选中，该将其删除，即将不被选中的保留
            arrs.push(item);
          }
        });
        this.form.requestParams = arrs;
      } else {
        this.$message.warning('请选择要删除的数据');
      }
    },
    // 请求头说明---------------------
    addJsonRequestHeader(val) {
      this.addJsonMultipleRequestHeader = val;
    },
    // 添加
    addTableRequestHeader() {
      this.tabItemId = `T${this.RndNum(6)}`; // 生成以T开头的七位随机数
      this.form.requestHeader.push({
        name: '',
        value: '',
        tabItemId: this.tabItemId,
      });
    },
    // 删除
    delTableRequestHeader() {
      // 确认删除
      if (this.addJsonMultipleRequestHeader.length > 0) {
        const arrs = [];
        const ids = this.addJsonMultipleRequestHeader.map((val) => val.tabItemId); // 拿到选中的数据id,
        this.form.requestHeader.forEach((item) => {
          if (!ids.includes(item.tabItemId)) {
            // 当id在params中，表示数据被选中，该将其删除，即将不被选中的保留
            arrs.push(item);
          }
        });
        this.form.requestHeader = arrs;
      } else {
        this.$message.warning('请选择要删除的数据');
      }
    },
    // 返回参数说明-------------------------------
    addJsonResponseStatus(val) {
      this.addJsonMultipleResponseParams = val;
    },
    // 添加
    addTableResponseParams() {
      this.tabItemId = `T${this.RndNum(6)}`; // 生成以T开头的七位随机数
      this.form.responseParams.push({
        name: '',
        value: '',
        tabItemId: this.tabItemId,
      });
    },
    // 删除
    delTableResponseParams() {
      // 确认删除
      if (this.addJsonMultipleResponseParams.length > 0) {
        const arrs = [];
        const ids = this.addJsonMultipleResponseParams.map((val) => val.tabItemId); // 拿到选中的数据id,
        this.form.responseParams.forEach((item) => {
          if (!ids.includes(item.tabItemId)) {
            // 当id在params中，表示数据被选中，该将其删除，即将不被选中的保留
            arrs.push(item);
          }
        });
        this.form.responseParams = arrs;
      } else {
        this.$message.warning('请选择要删除的数据');
      }
    },
    // 响应状态码信息---------------------------
    addJsonResponseParams(val) {
      this.addJsonMultipleResponseStatus = val;
    },
    // 添加
    addTableResponseStatus() {
      this.tabItemId = `T${this.RndNum(6)}`; // 生成以T开头的七位随机数
      this.form.responseStatus.push({
        code: '',
        comment: '',
        tabItemId: this.tabItemId,
      });
    },
    // 删除
    delTableResponseStatus() {
      // 确认删除
      if (this.addJsonMultipleResponseStatus.length > 0) {
        const arrs = [];
        const ids = this.addJsonMultipleResponseStatus.map((val) => val.tabItemId); // 拿到选中的数据id,
        this.form.responseStatus.forEach((item) => {
          if (!ids.includes(item.tabItemId)) {
            // 当id在params中，表示数据被选中，该将其删除，即将不被选中的保留
            arrs.push(item);
          }
        });
        this.form.responseStatus = arrs;
      } else {
        this.$message.warning('请选择要删除的数据');
      }
    },

    // 取消按钮
    onCancel() {
      this.visible = false;
      this.form = this.$options.data().form;
    },
    // 确定按钮-新增后接口调用，展示在列表
    onConfirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const formData = {
            ...this.form,
            tableId: this.relatedId,
          };
          // this.form.catalogId = this.addId;
          formData.requestParams = JSON.stringify(formData.requestParams); // 请求参数说明
          formData.requestHeader = JSON.stringify(formData.requestHeader); // 请求头说明
          formData.responseParams = JSON.stringify(formData.responseParams); // 返回参数说明
          formData.responseStatus = JSON.stringify(formData.responseStatus); // 响应状态码信息
          API.delAction(formData, false)
            .then((res) => {
              console.log(res);
              this.$message.success('接口编辑成功！');
              // 新增成功后，通过 $emit 触发自定义事件，传递新增成功的信号以及可能相关的数据（父组件可以监听这个事件来做出相应的处理）
              this.$emit('confirm');
            })
            .catch((error) => {
              console.error('获取数据失败', error);
            });
          this.loading = false;
          // }
        } else {
          console.log('表单验证失败，请检查所有必填项');
          return false;
        }
      });
      this.loading = false;
      this.visible = 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>
