<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-08-07 17:17:50
 * @LastEditors: 无尘
 * @LastEditTime: 2019-10-15 11:09:46
 -->
<!--
<create-base></create-base>

import createBase from '@/components/api/create-base.vue';
-->
<template>
  <div class="base-info-show border-box">
    <el-form label-width="104px" :model="apiInfoData" ref="baseForm" :rules="rules">
      <el-form-item label="协议:" prop="protocol">{{ apiInfoData.protocol }}</el-form-item>
      <el-form-item label="请求方法:" prop="requestType">
        <el-select v-model="apiInfoData.requestType" placeholder="请选择">
          <el-option label="GET" value="GET"></el-option>
          <el-option label="POST" value="POST"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="导入参数" class="color-303133 font-w-700">
        <!-- <el-radio-group v-model="importType" @change="changeImportType">
          <el-radio-button label="1">导入json参数</el-radio-button>
          <el-radio-button label="2">导入dubbo参数</el-radio-button>
        </el-radio-group> -->
        <div role="radiogroup" class="el-radio-group">
          <label for="importJson" role="radio" tabindex="0" :class="['el-radio-button el-radio-button--large', importType == 1 ? 'is-active' : '']" @click="changeImportType(1)">
            <input id="importJson" name="drone" type="radio" tabindex="-1" class="el-radio-button__orig-radio" value="1" />
            <span class="el-radio-button__inner">导入json参数</span>
          </label>
          <label for="importDubbo" role="radio" tabindex="0" :class="['el-radio-button el-radio-button--large', importType == 2 ? 'is-active' : '']" @click="changeImportType(2)">
            <input id="importDubbo" name="drone" type="radio" tabindex="-1" class="el-radio-button__orig-radio" value="2" />
            <span class="el-radio-button__inner">导入dubbo参数</span>
          </label>
        </div>
      </el-form-item>
      <el-form-item label="参数配置" class="color-303133 font-w-700"> </el-form-item>
      <el-form-item label="参数位置:">
        <div class="font-14 color-303133">header</div>
      </el-form-item>
      <el-form-item label="">
        <header-param ref="frontHeaderTable" :itemData="headerData" :frontOriginType="'header'"></header-param>
      </el-form-item>
      <el-form-item label="参数位置:">
        <div class="font-14 color-303133">query</div>
      </el-form-item>
      <el-form-item label="">
        <header-param ref="frontQueryTable" :itemData="queryData" :frontOriginType="'query'"></header-param>
      </el-form-item>
      <el-form-item v-if="apiInfoData.requestType == 'POST'" label="参数位置:">
        <div class="font-14 color-303133">body</div>
        <div class="font-14 color-303133">
          <el-radio v-model="apiInfoData.frontBodyType" label="json">json</el-radio>
          <el-radio v-model="apiInfoData.frontBodyType" label="form">form</el-radio>
        </div>
      </el-form-item>
      <el-form-item v-if="apiInfoData.requestType == 'POST' && apiInfoData.frontBodyType == 'json'" 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_3 is-leaf">
                      <div class="cell">必选</div>
                    </th>
                    <th colspan="1" rowspan="1" class="el-table_1_column_4 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_6 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">
                <body-param ref="frontBodyJsonTable" :itemData="bodyJsonData" :frontOriginType="'body'" @refreshData="refreshData"></body-param>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="apiInfoData.requestType == 'POST' && apiInfoData.frontBodyType == 'form'" label="">
        <header-param ref="frontBodyFormTable" :itemData="bodyFormData" :frontOriginType="'form'"></header-param>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitback">上一步</el-button>
        <el-button type="primary" @click="submitForm('baseForm')">下一步</el-button>
      </el-form-item>
    </el-form>
    <import-dubbo :showDialog="showDialog" @hideDialog="hideDialog"> </import-dubbo>
    <web-editor :showJsonDialog="showJsonDialog" @hideJsonDialog="hideJsonDialog"> </web-editor>
  </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 bodyParam from '@/components/createApi/body-param.vue';
import importDubbo from '@/components/createApi/import-dubbo.vue';
import webEditor from '@/components/createApi/web-editor.vue';
import showMsg from '@/assets/js/showmsg';
import { isRepeat } from '@/assets/js/public';
export default {
  name: 'create-front',
  components: {
    limitTextarea,
    limitInput,
    headerParam,
    bodyParam,
    importDubbo,
    webEditor
  },

  data() {
    return {
      importType: '',
      showDialog: false,
      apiInfoData: {
        protocol: 'http',
        requestType: 'GET',
        frontBodyType: 'json',
        frontParams: {},
        headerData: {},
        queryData: {},
        bodyJsonData: {},
        bodyFormData: {}
      },
      // 导入 dubbo
      dubboData: {
        apiPackage: '',
        method: ''
      },
      // header
      headerData: {
        type: 'object',
        level: 1,
        properties: {
          /* header: {
            level: 2,
            currentKey: 'header',
            frontOriginType: 'header', //来源类型 query,body,header
            backendOriginType: 'header',
            type: 'string',
            isBackendField: 0, //是否后端字段
            defaultVal: 'val', //默认值
            isRootKey: 0, //是否是后端参数字段
            isRootKeyFlag: false, // 禁用标志
            rootKey: '', //后端参数字段
            objectClass: '', //如果是object 并且是dubbo
            description: '描述',
            example: '示例',
            check: true,
            properties: {}
          } */
        },
        required: []
      },
      // query
      queryData: {
        type: 'object',
        level: 1,
        properties: {
          /* query: {
            level: 2,
            currentKey: 'query',
            frontOriginType: 'query', // 来源类型 query,body,header
            backendOriginType: 'query',
            type: 'string',
            isBackendField: 0, // 是否后端字段
            defaultVal: 'val', // 默认值
            isRootKey: 0, // 是否是后端参数字段
            isRootKeyFlag: false, // 禁用标志
            rootKey: '', // 后端参数字段
            objectClass: '', // 如果是object 并且是dubbo
            description: '描述',
            example: '示例',
            check: true,
            properties: {}
          } */
        },
        required: []
      },
      // body
      bodyJsonData: {
        type: 'object',
        level: 1,
        properties: {
          bodyRoot: {
            level: 2,
            currentKey: 'bodyRoot',
            frontOriginType: 'body', //来源类型 query,body,header
            backendOriginType: 'body',
            type: 'object',
            isBackendField: 0, //是否后端字段
            defaultVal: '', //默认值
            isRootKey: false, //是否是后端参数字段
            isRootKeyFlag: false, // 禁用标志
            rootKey: '', //后端参数字段
            objectClass: '', //如果是object 并且是dubbo
            description: '描述',
            example: '示例',
            check: true,
            properties: {},
            required: []
          }
        },
        required: []
      },
      bodyFormData: {
        type: 'object',
        level: 1,
        properties: {
          /* form: {
            level: 2,
            currentKey: 'form',
            frontOriginType: 'body', //来源类型 query,body,header
            backendOriginType: 'body',
            type: 'string',
            isBackendField: 0, //是否后端字段
            defaultVal: 'val', //默认值
            isRootKey: 0, //是否是后端参数字段
            isRootKeyFlag: false, // 禁用标志
            rootKey: '', //后端参数字段
            objectClass: '', //如果是object 并且是dubbo
            description: '描述',
            example: '示例',
            check: true,
            properties: {}
          } */
        },
        required: []
      },
      rules: {
        requestType: [{ required: true, message: '请选择请求方法', trigger: 'blur' }]
      },
      // 导入json
      showJsonDialog: false
    };
  },
  methods: {
    /**
     * 修改导入类型
     */
    changeImportType(e) {
      const that = this;
      that.importType = e;
      if (e == '2') {
        that.showDialog = true;
      } else {
        // that.showJsonDialog = true;
      }
    },

    /**
     * dubbo 选择返回
     */
    hideDialog(data, dubboData) {
      const that = this;
      that.showDialog = false;
      if (!data) {
        return false;
      }
      that.dubboData = JSON.parse(JSON.stringify(dubboData));
      that.handleFrontData(JSON.parse(data));
    },
    /**
     * json 选择后返回
     */
    hideJsonDialog(data, type) {
      const that = this;
      that.showJsonDialog = false;
      if (!data) {
        return false;
      }
      if (type == 'first') {
        // json
      } else {
        // jsonschema
      }
    },
    /**
     * 处理 isRootKey
     */
    async handleArrObjData(item, parentKey) {
      const that = this;
      for (let childKey in item) {
        item[childKey]['isRootKey'] = !item[childKey]['isRootKey'] || item[childKey]['isRootKey'] == '' || item[childKey]['isRootKey'] == 0 ? false : true; // 是否是后端参数字段
        // 是否禁用，不能选择,这里暂时设置一下，后面后端配置中会去重新设置 isRootKeyFlag 这个字段值
        item[childKey]['isRootKeyFlag'] = !parentKey.isRootKey || item[childKey]['isRootKey'] ? false : true;
        if (item[childKey]['isRootKey']) {
          parentKey.isRootKeyFlag = true; // 这里是必须的
        }
        if (item[childKey].type == 'array' && Object.keys(item[childKey].items.properties).length) {
          await that.handleArrObjData(item[childKey].items.properties, item[childKey]);
        }
        if (item[childKey].type == 'object' && Object.keys(item[childKey].properties).length) {
          await that.handleArrObjData(item[childKey].properties, item[childKey]);
        }
      }
      return item;
    },
    // 前端通用数据处理
    async handleQuery(allData, type) {
      const that = this;
      let newObj = {
        type: 'object',
        level: 1,
        properties: {},
        required: []
      };
      for (let key in allData.properties) {
        allData.properties[key].isRootKey = allData.properties[key].isRootKey == 1 || allData.properties[key].isRootKey == true ? true : false;
        allData.properties[key]['isRootKeyFlag'] = false;
        // form 判断
        if (allData.properties[key].frontOriginType == 'form') {
          that.apiInfoData.requestType = 'POST';
          that.apiInfoData.frontBodyType = 'form';
        }
        if (allData.properties[key].frontOriginType == type) {
          that.$set(newObj.properties, allData.properties[key].currentKey, allData.properties[key]);
        }
        // console.log(allData.properties[key]);
        // 如果有数组出现
        if (allData.properties[key].type == 'array' && Object.keys(allData.properties[key].items.properties).length) {
          await that.handleArrObjData(allData.properties[key].items.properties, allData.properties[key]);
        }
        // 如果有对象出现
        if (allData.properties[key].type == 'object' && Object.keys(allData.properties[key].properties).length) {
          await that.handleArrObjData(allData.properties[key].properties, allData.properties[key]);
        }
      }
      return newObj;
    },
    /**
     * 处理dubbo数据
     */
    async handleFrontData(data) {
      const that = this;
      let allData = JSON.parse(JSON.stringify(data));
      that.queryData = await that.handleQuery(allData, 'query');
      that.headerData = await that.handleQuery(allData, 'header');
      that.bodyFormData = await that.handleQuery(allData, 'form');
      that.bodyJsonData = await that.handleQuery(allData, 'body');
      // 设置 post 需要判断
      if (allData.properties.hasOwnProperty('bodyRoot')) {
        that.apiInfoData.requestType = 'POST';
        that.apiInfoData.frontBodyType = 'json';
      }

      // console.log(that.bodyJsonData);
      // 如果返回没有 bodyRoot,需要添加默认的
      let bodyJsonData = {
        type: 'object',
        level: 1,
        properties: {
          bodyRoot: {
            level: 2,
            currentKey: 'bodyRoot',
            frontOriginType: 'body', //来源类型 query,body,header
            backendOriginType: 'body',
            type: 'object',
            isBackendField: 0, //是否后端字段
            defaultVal: '', //默认值
            isRootKey: false, //是否是后端参数字段
            isRootKeyFlag: false, // 禁用标志
            rootKey: '', //后端参数字段
            objectClass: '', //如果是object 并且是dubbo
            description: '描述',
            example: '示例',
            check: true,
            properties: {},
            required: []
          }
        },
        required: []
      };
      if (!Object.keys(that.bodyJsonData.properties).length) {
        that.bodyJsonData = bodyJsonData;
      }
    },
    refreshData(data) {
      const that = this;
      that.frontData = data;
    },
    /**
     * 上一步
     */
    submitback() {
      const that = this;
      that.$emit('submitBack');
    },
    /**
     *  下一步
     *
     */
    submitForm(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.handleData();
        } else {
          return false;
        }
      });
    },

    /**
     * 处理 提交的 isRootKey
     */
    async handleRootKey(item, parentItem) {
      const that = this;
      for (let childKey in item) {
        item[childKey]['isRootKey'] = !item[childKey]['isRootKey'] || item[childKey]['isRootKey'] == '' || item[childKey]['isRootKey'] == 0 ? false : true; // 是否是后端参数字段
        if (item[childKey]['isRootKey']) {
          parentItem['isRootKey'] = false;
        }
        if (item[childKey].type == 'array' && Object.keys(item[childKey].items.properties).length) {
          await that.handleRootKey(item[childKey].items.properties, item[childKey]);
        }
        if (item[childKey].type == 'object' && Object.keys(item[childKey].properties).length) {
          await that.handleRootKey(item[childKey].properties, item[childKey]);
        }
      }
      return item;
    },
    /**
     * 下一步之前处理数据
     */
    /* eslint-disable */
    async handleData() {
      const that = this;
      // 判断参数重复
      let paramKeys = [...Object.keys(that.queryData.properties), ...Object.keys(that.headerData.properties)];
      if (that.apiInfoData.requestType == 'POST' && that.apiInfoData.frontBodyType == 'form') {
        paramKeys = [...paramKeys, ...Object.keys(that.bodyFormData.properties)];
      }
      let returnFlag = await isRepeat(paramKeys);
      if (returnFlag) {
        showMsg.showmsg('参数名重复', 'warning');
        return false;
      }
      // 如果有选导入 dubbo 数据，修改后端配置数据
      if (that.importType == 2 && that.dubboData.apiPackage != '' && that.dubboData.method != '') {
        let apiBack = JSON.parse(JSON.stringify(that.$store.state.backInfo));
        apiBack.dubboInterface = that.dubboData.apiPackage;
        apiBack.dubboMethod = that.dubboData.method;
        apiBack.interfaceType = '1';
        that.apiInfoData.dubboImport = '1'; // 20191015 增加dubbo导入判断字段，前端使用
        that.$store.dispatch('saveBackInfo', apiBack);
      }
      if (that.apiInfoData.requestType == 'POST' && that.apiInfoData.frontBodyType == 'json') {
        if (Object.keys(that.bodyJsonData.properties.bodyRoot.properties).length) {
          that.bodyJsonData.properties.bodyRoot.required = [];
          for (const key in that.bodyJsonData.properties.bodyRoot.properties) {
            that.bodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] = !that.bodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] || that.bodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] == 0 || that.bodyJsonData.properties.bodyRoot.properties[key]['isRootKey'] == false ? false : true;
            if (that.bodyJsonData.properties.bodyRoot.properties[key].check) {
              that.bodyJsonData.properties.bodyRoot.required.push(key);
            }
            // 如果有数组出现
            if (that.bodyJsonData.properties.bodyRoot.properties[key].type == 'array' && Object.keys(that.bodyJsonData.properties.bodyRoot.properties[key].items.properties).length) {
              that.bodyJsonData.properties.bodyRoot.properties[key].items.isRootKey = that.bodyJsonData.properties.bodyRoot.properties[key].items.isRootKey == false ? 0 : 1;
              await that.handleRootKey(that.bodyJsonData.properties.bodyRoot.properties[key].items.properties, that.bodyJsonData.properties.bodyRoot.properties[key]);
            }
            // 如果有对象出现
            if (that.bodyJsonData.properties.bodyRoot.properties[key].type == 'object' && Object.keys(that.bodyJsonData.properties.bodyRoot.properties[key].properties).length) {
              await that.handleRootKey(that.bodyJsonData.properties.bodyRoot.properties[key].properties, that.bodyJsonData.properties.bodyRoot.properties[key]);
            }
          }
        }
        that.apiInfoData.bodyJsonData = that.bodyJsonData;
      } else {
        that.apiInfoData.bodyJsonData = {};
      }
      if (that.apiInfoData.requestType == 'POST' && that.apiInfoData.frontBodyType == 'form') {
        if (Object.keys(that.bodyFormData.properties).length) {
          that.bodyFormData.required = [];
          for (const key in that.bodyFormData.properties) {
            if (that.bodyFormData.properties[key].check) {
              that.bodyFormData.required.push(key);
            }
          }
        }
        that.apiInfoData.bodyFormData = that.bodyFormData;
      } else {
        that.apiInfoData.bodyFormData = {};
      }
      if (Object.keys(that.headerData.properties).length) {
        that.headerData.required = [];
        for (const key in that.headerData.properties) {
          if (that.headerData.properties[key].check) {
            that.headerData.required.push(key);
          }
        }
      }
      if (Object.keys(that.queryData.properties).length) {
        that.queryData.required = [];
        for (const key in that.queryData.properties) {
          if (that.queryData.properties[key].check) {
            that.queryData.required.push(key);
          }
        }
      }
      that.apiInfoData.headerData = that.headerData;
      that.apiInfoData.queryData = that.queryData;
      that.$store.dispatch('saveFrontInfo', that.apiInfoData);
      that.$emit('submitNext', that.apiInfoData);
      console.log('front:', that.apiInfoData);
    },
    /**
     * 处理状态中的前端数据
     */
    handleStoreData() {
      const that = this;
      that.apiInfoData = JSON.parse(JSON.stringify(that.$store.state.frontInfo));
      that.headerData = that.apiInfoData.headerData;
      that.queryData = that.apiInfoData.queryData;
      const bodyJsonData = {
        type: 'object',
        level: 1,
        properties: {
          bodyRoot: {
            level: 2,
            currentKey: 'bodyRoot',
            frontOriginType: 'body', //来源类型 query,body,header
            backendOriginType: 'body',
            type: 'object',
            isBackendField: 0, //是否后端字段
            defaultVal: 'val', //默认值
            isRootKey: false, //是否是后端参数字段
            isRootKeyFlag: false, // 禁用标志
            rootKey: '', //后端参数字段
            objectClass: '', //如果是object 并且是dubbo
            description: '描述',
            example: '示例',
            check: true,
            properties: {}
          }
        },
        required: []
      };
      const bodyFormData = {
        type: 'object',
        level: 1,
        properties: {
          bodyForm: {
            level: 2,
            currentKey: 'bodyForm',
            frontOriginType: 'form', //来源类型 query,body,header,form
            backendOriginType: 'form',
            type: 'string',
            isBackendField: 0, //是否后端字段
            defaultVal: 'val', //默认值
            isRootKey: false, //是否是后端参数字段
            isRootKeyFlag: false, // 禁用标志
            rootKey: '', //后端参数字段
            objectClass: '', //如果是object 并且是dubbo
            description: '描述',
            example: '示例',
            check: true,
            properties: {}
          }
        },
        required: []
      };
      // console.log(that.apiInfoData.bodyJsonData);
      that.bodyJsonData = Object.keys(that.apiInfoData.bodyJsonData).length ? that.apiInfoData.bodyJsonData : bodyJsonData;
      that.bodyFormData = Object.keys(that.apiInfoData.bodyFormData).length ? that.apiInfoData.bodyFormData : bodyFormData;
    }
  },
  mounted() {
    const that = this;
    if (Object.keys(that.$store.state.frontInfo).length) {
      that.handleStoreData();
    }
  }
};
</script>
<style lang="less" scoped>
.w-320 {
  width: 320px;
}
.m-t-14 {
  margin-top: 14px;
}
.w-329 {
  width: 329px;
}
.base-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;
  }
}
</style>
