<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-08-16 10:02:07
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-23 18:10:50
 -->
<!--
<create-result></create-result>

import createResult from '@/components/api/create-result.vue';
-->
<template>
  <div class="result-info-show border-box">
    <el-form
      ref="resultForm"
      label-width="114px"
      :model="apiInfoData"
      :rules="rules">
      <el-form-item label="返回类型:">
        json
      </el-form-item>
      <el-form-item label="返回参数:">
        <div class="body-param-wrap">
          <div
            class="el-table el-table--fit el-table--enable-row-hover el-table--enable-row-transition"
            style="width: 100%; table-layout: fixed;">
            <div class="el-table__header-wrapper">
              <table
                cellspacing="0"
                cellpadding="0"
                border="0"
                class="el-table__header"
                style="width: 100%; table-layout: fixed;">
                <thead class="has-gutter">
                  <tr class="">
                    <th
                      colspan="1"
                      rowspan="1"
                      class="el-table_1_column_1 is-leaf">
                      <div class="cell">
                        参数名
                      </div>
                    </th>
                    <th
                      colspan="1"
                      rowspan="1"
                      class="el-table_1_column_2 is-leaf">
                      <div class="cell">
                        参数类型
                      </div>
                    </th>
                    <th
                      colspan="1"
                      rowspan="1"
                      class="el-table_1_column_5 is-leaf">
                      <div class="cell">
                        示例值
                      </div>
                    </th>
                    <th
                      colspan="1"
                      rowspan="1"
                      class="el-table_1_column_7 is-leaf">
                      <div class="cell">
                        操作
                      </div>
                    </th>
                  </tr>
                </thead>
              </table>
            </div>
            <div class="el-table__body-wrapper is-scrolling-none">
              <div class="table-content">
                <result-table
                  ref="resultBodyTable"
                  :item-data="resultParams"
                  @refreshData="refreshData" />
                <div
                  class="add-line text-center"
                  @click="toAddItem">
                  <i class="el-icon-circle-plus-outline color-5584FF" /><span class="color-5584FF font-14 p-l-4">添加行</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        label="错误码映射:"
        prop="errCode">
        <el-table
          :data="apiInfoData.errCode"
          style="width: 100%">
          <el-table-column label="原始错误码">
            <template slot-scope="scope">
              <div class="cell">
                <el-input
                  v-model="scope.row.orig_error_code"
                  placeholder="请输入原始错误码" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="错误码映射">
            <template slot-scope="scope">
              <div class="cell">
                <el-select
                  v-model="scope.row.error_code"
                  placeholder="请选择映射错误码"
                  @change="changeErr($event, scope.$index, scope.row)">
                  <el-option
                    v-for="item in errOptions"
                    :key="item.errorCode"
                    :label="item.errorCode"
                    :value="item.errorCode" />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="错误信息">
            <template slot-scope="scope">
              <div class="cell">
                <el-input
                  v-model="scope.row.error_info"
                  placeholder="请输入错误信息" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="cell">
                <el-button
                  type="text"
                  @click="delErrorCode(scope.$index)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div
          class="add-line add-err-line text-center"
          @click="addErrCodeItem">
          <i class="el-icon-circle-plus-outline color-5584FF" /><span class="color-5584FF font-14 p-l-4">添加错误码配置</span>
        </div>
      </el-form-item>
      <el-form-item
        label="成功返回示例:"
        prop="sucReturn">
        <el-input
          v-model="apiInfoData.sucReturn"
          class="w-389"
          type="textarea"
          :rows="3"
          placeholder="请输入内容" />
      </el-form-item>
      <el-form-item
        label="失败返回示例:"
        prop="errReturn">
        <el-input
          v-model="apiInfoData.errReturn"
          class="w-389"
          type="textarea"
          :rows="3"
          placeholder="请输入内容" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitback">
          上一步
        </el-button>
        <el-button
          type="primary"
          @click="submitForm('resultForm')">
          完 成
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
/* import limitTextarea from '@/components/limit-textarea.vue';
import limitInput from '@/components/limit-input.vue';
import headerParam from '@/components/createApi/header-param.vue'; */
import resultTable from '@/components/createApi/result-table.vue';
import { postRequest } from '@/api/api';
import { _debounce, isRepeat } from '@/assets/js/public';
import showMsg from '@/assets/js/showmsg';
import errMsg from '@/assets/js/error';
export default {
  name: 'CreateFront',
  components: {
    // limitTextarea,
    // limitInput,
    // headerParam,
    resultTable
  },

  data() {
    return {
      apiInfoData: {
        resultParams: {},
        sucReturn: '', // 成功返回示例
        errReturn: '', // 失败返回示例
        // 错误码
        errCode: [],
        sceneCode: '' // 场景 code
      },
      errOptions: [], // 错误码
      resultParams: {
        type: 'object',
        level: 1,
        properties: {
          root: {
            level: 2,
            currentKey: 'root',
            type: 'object',
            defaultVal: 'val', // 默认值
            description: '描述',
            example: '示例',
            properties: {}
          }
        }
      },
      rules: {
        sucReturn: [ { required: true, message: '请输入成功返回示例', trigger: 'blur' } ],
        errReturn: [ { required: true, message: '请输入失败返回示例', trigger: 'blur' } ]
      },
      keyLength: 1
    };
  },
  mounted() {
    const that = this;
    that.getErrcodeData();
    if (that.$route.query.interfaceId || Object.keys(that.$store.state.resultInfo).length) {
      that.handleStoreData();
    }
  },
  methods: {
    remoteMethod(query) {
      const that = this;
      if (query !== '') {
        that.getErrcodeData(query);
      } else {
        that.errOptions = [];
      }
    },
    /**
     * @description: 选择错误码
     * @param {String} $event
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    changeErr($event, index, row) {
      const that = this;
      if ($event) {
        that.errOptions.forEach(ele => {
          if ($event == ele.errorCode) {
            // eslint-disable-next-line
            row.error_info = ele.errorInfo;
          }
        });
      }
    },
    /**
     * @description: 添加一行
     * @author: 无尘
     */
    toAddItem() {
      const that = this;
      let length = that.keyLength++;
      that.$set(that.resultParams.properties, 'field' + length, {
        level: 2,
        parentKey: '', // 新增父级的 key
        type: 'string',
        currentKey: 'field' + length,
        defaultVal: '', // 默认值
        description: '描述',
        example: '示例',
        properties: {}
      });
    },
    /**
     * @description: 删除错误码
     * @param {Number} index
     * @author: 无尘
     */
    delErrorCode(index) {
      const that = this;
      that.apiInfoData.errCode.splice(index, 1);
    },
    /**
     * @description: 添加错误码配置
     * @author: 无尘
     */
    addErrCodeItem() {
      const that = this;
      /* eslint-disable */
      that.apiInfoData.errCode.push({
        error_code: '',
        error_info: '',
        orig_error_code: ''
      });
    },
    /**
     * @description: 上一步
     * @author: 无尘
     */
    submitback() {
      const that = this;
      let result = {
        resultParams: that.resultParams,
        sucReturn: that.apiInfoData.sucReturn, // 成功返回示例
        errReturn: that.apiInfoData.errReturn, // 失败返回示例
        // 错误码
        errCode: that.apiInfoData.errCode,
        // 场景 code
        sceneCode: that.apiInfoData.sceneCode
      };
      // console.log(result);
      that.$store.dispatch('saveResultInfo', result);
      that.$emit('submitBack');
    },
    /**
     * @description: 完成
     * @author: 无尘
     */
    submitForm: _debounce(function(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.handleFrontBackData();
        } else {
          return false;
        }
      });
    }, 500),
    /**
     * @description: 处理前端数据
     * @returns {Boolean}
     * @author: 无尘
     */
    async handleFrontData() {
      const that = this;
      if (!that.apiInfoData.errCode.length) {
        showMsg.showmsg('请完善错误码', 'warning');
        return false;
      }
      /* eslint-disable */
      const paramKeys = [...that.apiInfoData.errCode.map(item => item.error_code)];
      let returnFlag = await isRepeat(paramKeys);
      if (returnFlag) {
        showMsg.showmsg('原始错误码重复', 'warning');
        return false;
      }
      let obj = {
        type: 'object',
        level: 1,
        properties: {},
        required: []
      };
      let front = JSON.parse(JSON.stringify(that.$store.state.frontInfo));
      // 重新设置 isRootKey: true-->1,false--->0
      if (Object.keys(front.queryData.properties).length) {
        for (const key in front.queryData.properties) {
          front.queryData.properties[key].isRootKey = front.queryData.properties[key].isRootKey == 0 || front.queryData.properties[key].isRootKey == false ? 0 : 1;
        }
      }
      if (Object.keys(front.headerData.properties).length) {
        for (const key in front.headerData.properties) {
          front.headerData.properties[key].isRootKey = front.headerData.properties[key].isRootKey == 0 || front.headerData.properties[key].isRootKey == false ? 0 : 1;
        }
      }
      obj.properties = Object.assign(front.queryData.properties, front.headerData.properties);
      if (front.requestType == 'POST' && front.frontBodyType == 'json') {
        front.bodyJsonData.properties.bodyRoot.isRootKey = front.bodyJsonData.properties.bodyRoot.isRootKey == false ? 0 : 1;
        if (Object.keys(front.bodyJsonData.properties.bodyRoot.properties).length) {
          front.bodyJsonData.properties.bodyRoot.required = [];
          for (const key in front.bodyJsonData.properties.bodyRoot.properties) {
            front.bodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] = front.bodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] == 0 || front.bodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] == false ? 0 : 1;
            if (front.bodyJsonData.properties.bodyRoot.properties[key].check) {
              front.bodyJsonData.properties.bodyRoot.required.push(key);
            }
            // 如果有数组出现
            if (front.bodyJsonData.properties.bodyRoot.properties[key].type == 'array' && Object.keys(front.bodyJsonData.properties.bodyRoot.properties[key].items.properties).length) {
              front.bodyJsonData.properties.bodyRoot.properties[key].items.isRootKey = front.bodyJsonData.properties.bodyRoot.properties[key].items.isRootKey == false ? 0 : 1;
              await that.handleArrObjData(front.bodyJsonData.properties.bodyRoot.properties[key].items.properties, front.bodyJsonData.properties.bodyRoot.properties[key].items);
            }
            // 如果有对象出现
            if (front.bodyJsonData.properties.bodyRoot.properties[key].type == 'object' && Object.keys(front.bodyJsonData.properties.bodyRoot.properties[key].properties).length) {
              await that.handleArrObjData(front.bodyJsonData.properties.bodyRoot.properties[key].properties, front.bodyJsonData.properties.bodyRoot.properties[key]);
            }
          }
        }
        obj.properties = Object.assign(front.queryData.properties, front.headerData.properties, front.bodyJsonData.properties);
      }
      if (front.requestType == 'POST' && front.frontBodyType == 'form') {
        obj.properties = Object.assign(front.queryData.properties, front.headerData.properties, front.bodyFormData.properties);
      }

      // required
      if (Object.keys(obj.properties).length) {
        obj.required = [];
        for (const key in obj.properties) {
          if (obj.properties[key].check) {
            obj.required.push(key);
          }
        }
      }
      return obj;
    },
    async handleArrObjData(item, parentKey) {
      const that = this;
      parentKey.required = [];
      for (let childKey in item) {
        if (item[childKey].check) {
          parentKey.required.push(childKey);
        }
        item[childKey]['isRootKey'] = !item[childKey]['isRootKey'] || item[childKey]['isRootKey'] == 0 ? 0 : 1; // 是否是后端参数字段
        if (item[childKey].type == 'array' && Object.keys(item[childKey].items.properties).length) {
          await that.handleArrObjData(item[childKey].items.properties, item[childKey].items);
        }
        if (item[childKey].type == 'object' && Object.keys(item[childKey].properties).length) {
          await that.handleArrObjData(item[childKey].properties, item[childKey]);
        }
      }
      return item;
    },
    /**
     * @description: 处理后端数据
     * @author: 无尘
     */
    async handleBackData() {
      const that = this;
      let obj = {
        type: 'object',
        level: 1,
        properties: {},
        required: []
      };
      let back = JSON.parse(JSON.stringify(that.$store.state.backInfo));
      let front = JSON.parse(JSON.stringify(that.$store.state.frontInfo));

      // 重新设置 isRootKey: true-->1,false--->0
      if (Object.keys(back.backQueryData.properties).length) {
        for (const key in back.backQueryData.properties) {
          back.backQueryData.properties[key].isRootKey = back.backQueryData.properties[key].isRootKey == 0 || back.backQueryData.properties[key].isRootKey == false ? 0 : 1;
        }
      }
      if (Object.keys(back.backHeaderData.properties).length) {
        for (const key in back.backHeaderData.properties) {
          back.backHeaderData.properties[key].isRootKey = back.backHeaderData.properties[key].isRootKey == 0 || back.backHeaderData.properties[key].isRootKey == false ? 0 : 1;
        }
      }
      obj.properties = Object.assign(back.backQueryData.properties, back.backHeaderData.properties, back.constData.properties);
      if (front.requestType == 'POST' && front.frontBodyType == 'json') {
        back.backBodyJsonData.properties.bodyRoot.isRootKey = back.backBodyJsonData.properties.bodyRoot.isRootKey == false ? 0 : 1;
        if (Object.keys(back.backBodyJsonData.properties.bodyRoot.properties).length) {
          back.backBodyJsonData.properties.bodyRoot.required = [];
          for (const key in back.backBodyJsonData.properties.bodyRoot.properties) {
            back.backBodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] = back.backBodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] == 0 || back.backBodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] == false ? 0 : 1;
            if (back.backBodyJsonData.properties.bodyRoot.properties[key].check) {
              back.backBodyJsonData.properties.bodyRoot.required.push(key);
            }
             // 如果有数组出现
            if (back.backBodyJsonData.properties.bodyRoot.properties[key].type == 'array' && Object.keys(back.backBodyJsonData.properties.bodyRoot.properties[key].items.properties).length) {
              back.backBodyJsonData.properties.bodyRoot.properties[key].items.isRootKey = back.backBodyJsonData.properties.bodyRoot.properties[key].items.isRootKey == false ? 0 : 1;
              await that.handleArrObjData(back.backBodyJsonData.properties.bodyRoot.properties[key].items.properties, back.backBodyJsonData.properties.bodyRoot.properties[key].items);
            }
            // 如果有对象出现
            if (back.backBodyJsonData.properties.bodyRoot.properties[key].type == 'object' && Object.keys(back.backBodyJsonData.properties.bodyRoot.properties[key].properties).length) {
              await that.handleArrObjData(back.backBodyJsonData.properties.bodyRoot.properties[key].properties, back.backBodyJsonData.properties.bodyRoot.properties[key]);
            }
          }
        }
        obj.properties = Object.assign(back.backQueryData.properties, back.backHeaderData.properties, back.backBodyJsonData.properties, back.constData.properties);
      }
      if (front.requestType == 'POST' && front.frontBodyType == 'form') {
        obj.properties = Object.assign(back.backQueryData.properties, back.backHeaderData.properties, back.backBodyFormData.properties, back.constData.properties);
      }

      // 后端常量
      if (Object.keys(back.constData.properties).length) {
        for (const key in back.constData.properties) {
          back.constData.properties[key].isRootKey = 1;
          back.constData.properties[key].rootKey = back.constData.properties[key].currentKey;
          back.constData.properties[key].constFlag = back.constData.properties[key].constFlag ? 1 : 0;
        }
      }
      // required
      if (Object.keys(obj.properties).length) {
        obj.required = [];
        for (const key in obj.properties) {
          if (obj.properties[key].check) {
            obj.required.push(key);
          }
        }
      }
      return obj;
    },
    /**
     * @description: 处理前后端配置数据
     * @returns {Boolean}
     * @author: 无尘
     */
    async handleFrontBackData() {
      const that = this;
      let frontParams = await that.handleFrontData();
      if (!frontParams) {
        return false;
      }
      let endParams = await that.handleBackData();
      await that.toPostApi(frontParams, endParams);
    },
    /**
     * @description: 创建 API
     * @param {Array} frontParams
     * @param {Array} endParams
     * @author: 无尘
     */
    toPostApi(frontParams, endParams) {
      const that = this;
      let para = {
        interfaceName: that.$store.state.baseInfo.interfaceName, // 接口名称
        interfaceGroupId: that.$route.query.interfaceGroupId,
        interfaceUrl: that.$store.state.baseInfo.interfaceUrl, // 接口路径
        interfaceDescribe: that.$store.state.baseInfo.interfaceDescribe, // 接口描述
        projectId: that.$route.query.projectId, // 项目id
        target: that.$store.state.baseInfo.target, // 公开，私有
        optType: that.$store.state.baseInfo.optType, // 访问类型
        // 前端
        protocol: that.$store.state.frontInfo.protocol, // 协议http
        requestType: that.$store.state.frontInfo.requestType, // 前端请求类型post/get
        frontBodyType: that.$store.state.frontInfo.frontBodyType,
        frontParams: JSON.stringify(frontParams),
        // 后端
        interfaceType: that.$store.state.backInfo.interfaceType, // http or dubbo
        version: that.$store.state.backInfo.version, // api版本号
        backendRequestType: that.$store.state.backInfo.backendRequestType,
        backendHttpPath: that.$store.state.backInfo.backendHttpPath, // 后端请求路径
        dubboInterface: that.$store.state.backInfo.dubboInterface,
        dubboMethod: that.$store.state.backInfo.dubboMethod, // dubbo 请求方法
        dubboVersion: that.$store.state.backInfo.dubboVersion, // dubbo版本号
        proxyCode: that.$store.state.backInfo.proxyCode, // 注册中心地址
        timeout: that.$store.state.backInfo.timeout, // 超时
        endParams: JSON.stringify(endParams), // 返回
        resultParams: JSON.stringify(that.resultParams), // 返回结果
        sucReturn: that.apiInfoData.sucReturn, // 成功信息示例json
        errReturn: that.apiInfoData.errReturn, // 失败信息示例json
        errCode: JSON.stringify(that.apiInfoData.errCode), // 错误码映射信息
        sceneCode: that.apiInfoData.sceneCode, // 场景 code
        // 编辑
        interfaceId: that.$store.state.baseInfo.interfaceId, // api id
        interfaceVersionId: that.$store.state.baseInfo.interfaceVersionId //api 版本 id
      };
      postRequest(that.$store.state.baseInfo.interfaceId ? '/gateway-manage/update-api' : '/gateway-manage/create-api', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            showMsg.showmsg('保存成功', 'success');
            that.$store.dispatch('clearApiData');
            that.$router.push(`/apiListManage?interfaceId=${resData.result.interfaceId}&interfaceName=${resData.result.interfaceName}&projectId=${that.$route.query.projectId}&projectName=${that.$route.query.projectName}&interfaceGroupId=${that.$route.query.interfaceGroupId}&interfaceGroupName=${that.$route.query.interfaceGroupName}`);
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     * @description: 获取错误码
     * @param {String} search
     * @author: 无尘
     */
    getErrcodeData(search) {
      const that = this;
      let para = {
        pageNum: 1,
        pageSize: 100,
        search: search
      };
      postRequest('/gateway-manage/page-error-setting', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            that.errOptions = resData.result.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    handleStoreData() {
      const that = this;
      that.apiInfoData = JSON.parse(JSON.stringify(that.$store.state.resultInfo));
      that.resultParams = that.apiInfoData.resultParams;
      // console.log('result:', that.apiInfoData);
    }
  },

};
</script>
<style lang="less" scoped>
.w-320 {
  width: 320px;
}
.m-t-14 {
  margin-top: 14px;
}
.w-329 {
  width: 329px;
}
.result-info-show {
  width: 100%;
  margin-top: 56px;
  .el-form {
    /deep/ .el-form-item__label {
      color: #606266;
    }
    .font-w-700 {
      /deep/ .el-form-item__label {
        color: #303133;
        font-weight: 600;
      }
    }
    /deep/ .el-form-item__content {
      color: #303133;
    }
  }
  .el-table th {
    padding: 7px 0;
  }
  .add-line {
    height: 48px;
    line-height: 48px;
    cursor: pointer;
    &.add-err-line {
      border-bottom: 1px solid #ebeef5;
    }
  }
  .w-389 {
    width: 389px;
  }
}
</style>
