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

import createBase from '@/components/api/create-base.vue';
-->
<template>
  <div class="base-info-show border-box">
    <el-form
      ref="baseForm"
      label-width="104px"
      :model="apiInfoData"
      :rules="rules">
      <el-form-item
        label="API名称:"
        prop="interfaceName">
        <limit-input
          :input-width="329"
          :disflag="$route.query.interfaceId ? true : false"
          :input-value.sync="apiInfoData.interfaceName"
          :holder="'请输入API名称'"
          :get-by-type="'word'"
          :max-length="20" />
      </el-form-item>
      <el-form-item
        label="API类型:"
        prop="target">
        <el-radio-group
          v-model="apiInfoData.target"
          :disabled="$route.query.interfaceId ? true : false">
          <el-radio label="1">
            公开
          </el-radio>
          <el-radio label="0">
            私有
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="访问类型:"
        prop="optType">
        <el-select
          v-model="apiInfoData.optType"
          placeholder="请选择"
          :disabled="$route.query.interfaceId ? true : false">
          <el-option
            label="list"
            value="list" />
          <el-option
            label="delete"
            value="delete" />
          <el-option
            label="update"
            value="update" />
          <el-option
            label="get"
            value="get" />
          <el-option
            label="search"
            value="search" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="请求路径:"
        prop="interfaceUrl">
        <el-input
          v-model="apiInfoData.interfaceUrl"
          class="w-329"
          :disabled="$route.query.interfaceId ? true : false"
          @blur="blurInterfaceUrl" />
      </el-form-item>
      <el-form-item label="描述:">
        <limit-textarea
          :input-width="500"
          :dis-input="$route.query.interfaceId ? true : false"
          :input-value.sync="apiInfoData.interfaceDescribe"
          :holder="''"
          :get-by-type="'word'"
          :max-length="100" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('baseForm')">
          下一步
        </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 { getRequest } from '@/api/api';
import showMsg from '@/assets/js/showmsg';
import errMsg from '@/assets/js/error';
export default {
  name: 'CreateBase',
  components: {
    limitTextarea,
    limitInput
  },

  data() {
    return {
      apiInfoData: {
        interfaceId: '',
        interfaceVersionId: '',
        interfaceName: '',
        target: '1',
        optType: 'get',
        interfaceUrl: '',
        interfaceDescribe: ''
      },
      rules: {
        interfaceName: [ { required: true, message: '请输入API名称', trigger: 'blur' } ],
        interfaceUrl: [ { required: true, message: '请输入请求路径', trigger: 'blur' } ]
      }
    };
  },
  mounted() {
    const that = this;
    /* eslint-disable */
    if (that.$route.query.interfaceId && !Object.keys(that.$store.state.baseInfo).length) {
      that.getData();
    }
    if (Object.keys(that.$store.state.baseInfo).length) {
      that.apiInfoData = that.$store.state.baseInfo;
    }
  },
  methods: {
    submitForm(formName) {
      const that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.blurInterfaceUrl(formName);
        } else {
          return false;
        }
      });
    },
    /**
     * 请求路径查询
     */
    blurInterfaceUrl(formName) {
      const that = this;
      let para = {
        update: that.$route.query.interfaceId ? true : false,
        interfaceUrl: that.apiInfoData.interfaceUrl
      };
      getRequest('/gateway-manage/is-exist-interface-url', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            if (resData.result) {
              showMsg.showmsg('接口已存在', 'warning');
              return false;
            }
            if (formName == 'baseForm') {
              that.$emit('submitNext', that.apiInfoData);
              that.$store.dispatch('saveBaseInfo', that.apiInfoData);
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 处理 isRootKey
     */
    async handleArrObjData(item) {
      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].type == 'array' && Object.keys(item[childKey].items.properties).length) {
          await that.handleArrObjData(item[childKey].items.properties);
        }
        if (item[childKey].type == 'object' && Object.keys(item[childKey].properties).length) {
          await that.handleArrObjData(item[childKey].properties);
        }
      }
      return item;
    },
    /**
     * 处理数据存入 store
     */
    // 前端通用数据处理
    async handleQuery(front, allData, type) {
      const that = this;
      let newObj = {
        type: 'object',
        level: 1,
        properties: {}
      };
      // 最开始处理的时候, frontParams 和 endParams是同一份数据，所有前后端公用一份参数数据
      for (let key in allData.frontParams.properties) {
        if (allData.frontParams.properties[key].frontOriginType == type && !allData.endParams.properties[key].constFlag) {
          allData.frontParams.properties[key].isRootKey = allData.frontParams.properties[key].isRootKey == 1 || allData.frontParams.properties[key].isRootKey == true ? true : false;
          that.$set(newObj.properties, allData.frontParams.properties[key].currentKey, allData.frontParams.properties[key]);
        }
        // 如果有数组出现
        if (allData.frontParams.properties[key].type == 'array' && Object.keys(allData.frontParams.properties[key].items.properties).length) {
          await that.handleArrObjData(allData.frontParams.properties[key].items.properties, allData.frontParams.properties[key].isRootKey);
        }
        // 如果有对象出现
        if (allData.frontParams.properties[key].type == 'object' && Object.keys(allData.frontParams.properties[key].properties).length) {
          await that.handleArrObjData(allData.frontParams.properties[key].properties, allData.frontParams.properties[key].isRootKey);
        }
      }
      return newObj;
    },
    /**
     * 处理常量参数
     */
    handleConst(back, allData) {
      const that = this;
      let newObj = {
        type: 'object',
        level: 1,
        properties: {}
      };
      for (let key in allData.endParams.properties) {
        if (allData.endParams.properties[key].constFlag) {
          allData.endParams.properties[key].constFlag = allData.endParams.properties[key].constFlag ? true : false;
          that.$set(newObj.properties, allData.endParams.properties[key].currentKey, allData.endParams.properties[key]);
        }
      }
      return newObj;
    },
    /**
     * 获取已经保存的数据，处理前端数据
     */
    async handleFrontData(data) {
      const that = this;
      let allData = JSON.parse(JSON.stringify(data));
      let front = {
        protocol: allData.protocol,
        requestType: allData.requestType,
        frontBodyType: allData.frontBodyType || 'json',
        frontParams: {},
        headerData: {},
        queryData: {},
        bodyJsonData: {},
        bodyFormData: {}
      };
      front.queryData = await that.handleQuery(front, allData, 'query');
      front.headerData = await that.handleQuery(front, allData, 'header');
      if (allData.requestType == 'POST' && allData.frontBodyType == 'form') {
        front.bodyFormData = await that.handleQuery(front, allData, 'form');
      }
      if (allData.requestType == 'POST' && allData.frontBodyType == 'json') {
        // console.log('body', allData);
        front.bodyJsonData = await that.handleQuery(front, allData, 'body');
      }
      // console.log('base:', allData.requestType, allData.frontBodyType, front);
      that.$store.dispatch('saveFrontInfo', front);
    },
    /**
     * 获取已经保存的数据，处理前端数据
     */
    async handleBackData(data) {
      const that = this;
      let allData = JSON.parse(JSON.stringify(data));
      let back = {
        interfaceType: String(allData.interfaceType), // 后端服务
        version: allData.version, // api 版本号
        backendRequestType: allData.backendRequestType,
        backendHttpPath: allData.backendHttpPath || '', // 请求路径
        dubboInterface: allData.dubboInterface || '', // dubbo接口名称
        dubboMethod: allData.dubboMethod || '', // dubbo请求方法
        dubboVersion: allData.dubboVersion || '', // dubbo 请求版本号
        proxyCode: allData.proxyCode || '', // 注册中心
        timeout: allData.timeout, // 超时
        backHeaderData: {},
        backQueryData: {},
        backBodyJsonData: {},
        backBodyFormData: {},
        constData: {}
      };
      back.backQueryData = await that.handleQuery(back, allData, 'query');
      back.backHeaderData = await that.handleQuery(back, allData, 'header');
      if (allData.requestType == 'POST' && allData.frontBodyType == 'form') {
        back.backBodyFormData = await that.handleQuery(back, allData, 'form');
      }
      if (allData.requestType == 'POST' && allData.frontBodyType == 'json') {
        back.backBodyJsonData = await that.handleQuery(back, allData, 'body');
      }
      // console.log('back:', back);
      // 常量
      back.constData = await that.handleConst(back, allData);
      that.$store.dispatch('saveBackInfo', back);
    },
    handleResultData(data) {
      const that = this;
      let allData = JSON.parse(JSON.stringify(data));
      let result = {
        resultParams: allData.resultParams,
        sucReturn: allData.sucReturn, // 成功返回示例
        errReturn: allData.errReturn, // 失败返回示例
        // 错误码
        errCode: allData.errCode,
        // 场景 code
        sceneCode: allData.sceneCode
      };
      // console.log(result);
      that.$store.dispatch('saveResultInfo', result);
    },
    /**
     *  获取数据
     */
    getData() {
      const that = this;
      let para = {
        interfaceId: that.$route.query.interfaceId,
        interfaceVersionId: that.$route.query.interfaceVersionId
      };
      getRequest('/gateway-manage/get-api', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            resData.result.frontParams = JSON.parse(resData.result.endParams); // 编辑获取的时候使用后端数据
            resData.result.endParams = JSON.parse(resData.result.endParams); // 编辑获取的时候使用后端数据
            resData.result.errCode = JSON.parse(resData.result.errCode);
            resData.result.resultParams = JSON.parse(resData.result.resultParams);
            that.apiInfoData.interfaceId = resData.result.interfaceId;
            that.apiInfoData.interfaceVersionId = resData.result.interfaceVersionId;
            that.apiInfoData.interfaceName = resData.result.interfaceName;
            that.apiInfoData.target = String(resData.result.target);
            that.apiInfoData.optType = resData.result.optType;
            that.apiInfoData.interfaceUrl = resData.result.interfaceUrl;
            that.apiInfoData.interfaceDescribe = resData.result.interfaceDescribe;
            that.handleFrontData(resData.result);
            that.handleBackData(resData.result);
            that.handleResultData(resData.result);
            that.$nextTick(() => {
              that.submitForm('baseForm');
            });
            return false;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  }
};
</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;
    }
    /deep/ .el-form-item__content {
      color: #303133;
    }
  }
}
</style>
