<template>
  <div class="api_interface">
    <div class="obpm-title">
      <div class="d-inline-block">
        <i class="fa fa-plug" aria-hidden="true"></i>
        <div class="title-name d-inline-block ml-2">{{$t('view.api')}}</div>
      </div>
      <div class="bar d-inline-block float-right">
        <el-button type="primary" size="small" @click="save('apiForm')">{{
          $t('btns.save')
        }}</el-button>
        <el-button plain size="small" @click="exit">{{
          $t('btns.exit')
        }}</el-button> 
      </div>
    </div>
    <div class="obpm-main overflow-ys"  :style="'height:'+tableHeight" style="padding-right: 50px;">
      <el-form :model="apiForm" :rules="apiRules" ref="apiForm" class="demo-ruleForm" label-position="top">
        <el-row>
          <el-form-item label="API状态" class="padding0Label">
            <div class="dflex">
              <div class="success_status">
                <label>
                  <input class="radio_type" name="status" type="radio"  v-model="apiForm.status" value="published"/>
                  <span class="marginL10">{{$t('view.publish')}}</span>
                </label>
              </div>
              <div class="warning_status dflex">
                <label>
                  <input class="radio_type" name="status" type="radio"  v-model="apiForm.status" value="development" />
                  <span class="marginL10">{{$t('view.develop')}}</span>
                </label>
                <label>
                  <input class="radio_type" name="status" type="radio"  v-model="apiForm.status" value="test" />
                  <span class="marginL10">{{$t('view.test')}}</span>
                </label>
              </div>
              <div class="danger_status dflex">
                <label>
                  <input class="radio_type" name="status" type="radio"  v-model="apiForm.status" value="abnormal" />
                  <span class="marginL10">{{$t('view.err')}}</span>
                </label>
                <label>
                  <input class="radio_type" name="status" type="radio"  v-model="apiForm.status" value="maintain" />
                  <span class="marginL10">{{$t('view.upkeep')}}</span>
                </label>
                <label>
                  <input class="radio_type" name="status" type="radio"  v-model="apiForm.status" value="abandoned" />
                  <span class="marginL10">{{$t('view.waste')}}</span>
                </label>
              </div>
            </div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item :label="$t('label.api_path')" class="padding0Label" prop="name">
            <el-select v-model="apiForm.requestType" :placeholder="$t('placeholder.select')" size="mini">
              <el-option label="GET" value="get"></el-option>
              <el-option label="POST" value="post"></el-option>
              <el-option label="PUT" value="put"></el-option>
              <el-option label="DELETE" value="delete"></el-option>
            </el-select>
            <span> /magic-api </span>
            <el-input v-model="apiForm.requestUrl" placeholder="示例:/hello/{username}/{userid}?age={age}" style="width: 74%" size="mini"/>
          </el-form-item>
        </el-row>
        <el-form-item :label="$t('label.group_api')" class="padding0Label">
          <el-select v-model="apiForm.apiGroup" :placeholder="$t('placeholder.select')" size="mini">
            <el-option :label="item.name" v-for="item in groupData" :key="item.id" :value="item.id"></el-option>
          </el-select>
          <el-input v-model="apiForm.name" :placeholder="$t('placeholder.select')" style="width: 82%" size="mini"/>
        </el-form-item>
        <el-form-item :label="$t('label.code')" class="padding0Label">
          <el-select v-model="apiForm.encode" :placeholder="$t('placeholder.select')" size="mini">
            <el-option label="UTF-8" value="UTF-8"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('label.tabs')" class="padding0Label">
          <!-- <el-input v-model="apiForm.tags" size="mini"></el-input> -->
          <el-tag
            :key="tag"
            v-for="tag in apiForm.tags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">{{$t('btns.add')}}</el-button>
        </el-form-item>
        <div>
          <p class="params_wrap">
            <span>{{$t('view.response_content')}} </span>
            <span v-if="!isOpen" @click="changeOpen">{{$t('btns.unfold')}}<i class="el-icon-arrow-down"></i></span>
            <span v-if="isOpen" @click="changeOpen">{{$t('btns.shrink')}}<i class="el-icon-arrow-up"></i></span>
          </p>
          <div class="response_wrap" v-show="isOpen">
            <div class="response_left">
              <div class="response_header">
                <label class="marginL10 marginR10">
                  <input class="radio_type50" name="responseType" type="radio"  v-model="apiForm.responseType" value="json" @change="updateDesc"/>
                  <span class="marginL10">JSON</span>
                </label>
                <label class="marginL10 marginR10">
                  <input class="radio_type50" name="responseType" type="radio"  v-model="apiForm.responseType" value="xml" @change="updateDesc"/>
                  <span class="marginL10">XML</span>
                </label>
                <label class="marginL10 marginR10">
                  <input class="radio_type50" name="responseType" type="radio"  v-model="apiForm.responseType" value="raw" @change="updateDesc"/>
                  <span class="marginL10">Raw</span>
                </label>
                <label class="marginL10 marginR10">
                  <input class="radio_type50" name="responseType" type="radio"  v-model="apiForm.responseType" value="binary" @change="updateDesc"/>
                  <span class="marginL10">Binary</span>
                </label>
              </div>
              <div class="wrapBox">
                <div class="response_content">
                  <el-input
                    type="textarea"
                    resize="none"
                    :rows="10"
                    :placeholder="$t('placeholder.params_description')"
                    v-model="apiForm.responseScript">
                  </el-input>
                  <i
                    style="cursor: pointer;"
                    class="fa fa-code" aria-hidden="true"
                    @click="showScriptEditor('responseScript')"
                  ></i>
                </div>
                <div class="response_desc">
                  <el-card class="box-card">
                    <div v-html="desc"></div>
                  </el-card>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <ScriptEditor
      v-if="scriptEditorVisible"
      :scriptEditorVisible="scriptEditorVisible"
      :editorCode="showScritptEditorCode"
      @closeScriptEditorDialog="scriptEditorVisible = false"
      @saveScriptEditor="handleScriptEditor"
    />
  </div>
</template>

<script>
import {getAPISDetail, createApi, updateApi,getAPISGroup} from '@/service/AdvancedToolAPI.js'
import ScriptEditor from '@/components/Common/scriptEditor'
export default {
  name:'APIInterface',
  components:{
    ScriptEditor
  },
  data () {
    return {
      isOpen: true, //是否展开
      tableHeight: ((document.documentElement.clientHeight || document.body.clientHeight) - 60 - 32 - 41 - 40 - 50) + 'px',
      apiForm:{
        name: '',
        requestType: 'get',
        requestUrl: '',
        apiGroup: '',
        encode: 'UTF-8',
        tags: [],
        status: 'published',
        responseType: "json", 
        responseScript: "" // 响应头
      },
      apiRules: {},
      inputVisible: false, // 标签的输入框
      inputValue: '',      // 标签输入框的值
      scriptEditorVisible: false, // 脚本编辑器弹窗
      currentScriptEditor: '',  // 当前选中的是哪一个
      groupData: [],
      desc: '', // 响应的示例代码
    };
  },
  methods:{
    save(formName){
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let params = {
            ...this.apiForm,
            tags: this.apiForm.tags.join(';'),
          }
          // 更新
          if(params.id){
            try{
              let response = await updateApi(params, params.id, sessionStorage.getItem('appId'))
              if (response.data.errcode == 0) {
                this.$message.success(this.$t('msg.update_ss'));
              }
            }catch(e){
              console.log(e)
            }
          }else{ // 增加
            try{
              let response = await createApi(params, sessionStorage.getItem('appId'))
              if (response.data.errcode == 0) {
                this.$message.success(this.$t('msg.add_ss'));
                this.apiForm.id = response.data.data.id
              }
            }catch(e){
              console.log(e)
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    exit(){
      this.$router.back()
    },
    handleClose(tag) {
      this.apiForm.tags.splice(this.apiForm.tags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.apiForm.tags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    /**
     * 显示脚本编辑器弹框
     */
    showScriptEditor(val) {
      this.scriptEditorVisible = true
      this.currentScriptEditor = val
    },

    /**
     * 将脚本编辑器的值写入到textarea中
     */
    handleScriptEditor(val) {
      switch (this.currentScriptEditor){
        case 'responseScript':
          this.apiForm.responseScript = val;
          break;
        default:
          break;
      }
    },
    changeOpen(){
      this.isOpen = !this.isOpen
    },
    async getApiGroup(){
      let params = {
        name: '',
        pageNo: 1,
        linesPerPage: 10000
      }
      const response = await getAPISGroup(params, sessionStorage.getItem('appId'))
      // 将值塞进数组中
      this.groupData = response.data.data.datas
      this.updateDesc()
    },
    /**
     * 更新切换响应模式时的desc
     */
    updateDesc(){
      let type = this.apiForm.responseType
      switch (type) {
        case 'json':
          this.desc = `<span>//结果返回对象，会自动转成json格式</br>
                    (function(){</br>
                    var result = new Packages.java.util.HashMap(); //创建指定类对象</br>
                    result.put("A","A");</br>
                    result.put("B","B");</br>
                    result.put("C","C");</br>
                    return result;</br>
                    })()</p>`
          break;
        case 'xml':
          this.desc = `<span>
            //结果返回对象，会自动转成xml格式</br>
            (function(){</br>
            var dept = new Packages.cn.myapps.authtime.department.model.DepartmentVO(); //创建指定类对象</br>
            dept.setId("zxzxzxz");</br>
            dept.setName("部门");</br>
            return dept;</br>
            })()
          </span>`
          break;
        case 'raw':
          this.desc = `<span>
          //结果返回字符串</br>
          (function(){</br>
          var result = "abc";</br>
          return result;</br>
          })()
          </span>`
          break;
        case 'binary':
          this.desc = `<span>
          //结果返回文件对象</br>
          (function(){</br>
          var file = new Packages.java.io.File("D://spy//trunk2018//obpm-demo//uploads//doc//202106//0a4e5024-f1c7-4cff-bb5d-5d5f8adedb04.docx"); //创建指定类对象</br>
          return file;</br>
          })()
          </span>`
          break;
        default:
          break;
      }
    }
  },
  async created(){
    if(this.$route.query.edit == 'true'){
      let resp = await getAPISDetail(this.$route.query.apiId)
      this.apiForm = {
        ...resp.data.data,
        tags: resp.data.data.tags.split(';'),
      }
    }
    this.getApiGroup()
  },
  computed: {
    /**
     * 将 textarea 的值写入 脚本编辑器
     */
    showScritptEditorCode() {
      let code
      switch (this.currentScriptEditor) {
        case 'responseScript':
          code = this.apiForm.responseScript
          break;
        default:
          break;
      }
      return code
    },
  },
}

</script>
<style lang='scss' scoped>
.api_interface{
  .success_status{
    background-color: #e5f1ee;
    box-sizing: border-box;
    label{
      padding: 0 10px;
    }
  }
  .warning_status{
    background-color: #fff6cc;
    padding: 0 10px;
    box-sizing: border-box;
    label{
      padding: 0 10px;
    }
  }
  .danger_status{
    background-color: #ffe5e6;
    padding: 0 10px;
    box-sizing: border-box;
    label{
      padding: 0 10px;
    }
  }
  .params_wrap{
    display: flex;
    justify-content: space-between;
    height: 32px;
    line-height: 32px;
    background-color: #f8f8f8;
    border-left: 3px solid #046d53;
    font-size: 14px;
    padding-left: 16px;
    padding-right: 8px;
    margin: 20px 0;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .response_wrap{
    width: 100%;
    .response_header{
      border: 1px solid #ccc;
      height: 50px;
      line-height: 50px;
      padding: 0 10px;
    }
    .wrapBox{
      display: flex;
      .response_content, .response_desc{
        flex: 1;
      }
    }
  }
  .radio_type {
    width: 20px;
    height: 20px;
    appearance: none;
    position: relative;
    outline: none;
  }
  .radio_type:before {
      content: "";
      width: 15px;
      height: 15px;
      border: 1px solid #323232;
      display: inline-block;
      border-radius: 50%;
      vertical-align: middle;
  }
  .radio_type:checked:before {
      content: "";
      width: 15px;
      height: 15px;
      border: 1px solid #323232;
      display: inline-block;
      border-radius: 50%;
      vertical-align: middle;
  }
  .radio_type:checked:after {
      content: "";
      width: 5px;
      height: 5px;
      text-align: center;
      background: #323232;
      border-radius: 50%;
      display: block;
      position: absolute;
      top: 15px;
      left: 5px;
  }
  .radio_type:checked + label {
      color: #edd19d;
  }
  .radio_type50 {
    width: 20px;
    height: 20px;
    appearance: none;
    position: relative;
    outline: none;
  }
  .radio_type50:before {
      content: "";
      width: 15px;
      height: 15px;
      border: 1px solid #323232;
      display: inline-block;
      border-radius: 50%;
      vertical-align: middle;
  }
  .radio_type50:checked:before {
      content: "";
      width: 15px;
      height: 15px;
      border: 1px solid #323232;
      display: inline-block;
      border-radius: 50%;
      vertical-align: middle;
  }
  .radio_type50:checked:after {
      content: "";
      width: 5px;
      height: 5px;
      text-align: center;
      background: #323232;
      border-radius: 50%;
      display: block;
      position: absolute;
      top: 24px;
      left: 5px;
  }
  .radio_type50:checked + label {
      color: #edd19d;
  }
}
</style>