<template>
<div>
  <el-dialog
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="showEditComputedField"
    append-to-body
    class="dataset-edit-computed-fields"
    width="700px"
  >
    <p slot="title">
      {{ id ? '编辑自定义事件' : '新增自定义事件' }}
    </p>
    <div>事件名称：<el-input style="width:300px" v-model="eventName" placeholder="请输入事件名称"></el-input></div>
    <el-tabs v-model="activeName">
      <el-tab-pane label="请求设置" name="post">
        <el-form :model="addForm" label-position="left" label-width="100px" ref="addForm" :rules="rules" >
          <el-form-item label="请求路径" prop="url">
            <el-input v-model="addForm.url" placeholder="请输入请求路径"></el-input>
          </el-form-item>
          <el-form-item label="请求方式" prop="method">
            <el-radio-group v-model="addForm.method" @change="$event === 'GET' ? formActiveName = 'headers' :'' ">
              <el-radio label="GET"></el-radio>
              <el-radio label="POST"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-tabs v-model="formActiveName">
            <el-tab-pane label="headers" name="headers">
              <el-button size="mini" type="success" plain icon="el-icon-plus" @click="addForm.headers.push({name:'',value:''})" style="margin-bottom:10px">添加header</el-button>
              <el-table size="mini" :data="addForm.headers"  border  style="width: 100%">
                <el-table-column width="50" align="center">
                  <template slot-scope="scope">
                    <i class="el-icon-delete" style="font-size:20px" @click="addForm.headers.splice(scope.$index,1)"></i>
                  </template>
                </el-table-column>
                <el-table-column label="参数名称" width="180"  align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="参数名称"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="参数值"  align="center">
                  <template slot-scope="scope">
                    <el-popover :ref="`jarParamSelector-headers`" key="headers" placement="bottom-start" trigger="click">
                      <div style="display: flex">
                        <div style="margin-right: 10px;max-height: 300px;overflow-y: auto">
                          <p>引用字段</p>
                          <template v-for="field of tobeChooseWeidu">
                            <div :key="field.columnTitle" :title="field.columnName" class="weidu" @click="setJarValueFun(scope.row,`[${field.columnName}]`)">
                              {{ field.columnTitle + '【' + field.columnName + '】' }}
                            </div>
                          </template>
                          <template v-for="field of tobeChooseZhibiao">
                            <div :key="field.columnTitle" :title="field.columnName" class="zhibiao" @click="setJarValueFun(scope.row,`[${field.columnName}]`)">
                              {{ field.columnTitle + '【' + field.columnName + '】' }}
                            </div>
                          </template>
                        </div>
                        <el-cascader-panel v-model="hedParam" :options="paramList" :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }" @change="setJarValueFun(scope.row,`\${${$event}}`)"></el-cascader-panel>
                      </div>
                      <el-button slot="reference" size="mini" type="success" plain>插入变量</el-button>
                    </el-popover>
                    <el-input v-model="scope.row.value" placeholder="参数值" style="width:300px;margin-left:10px;"></el-input>

                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="params" name="params">
              <el-button size="mini" type="success" plain icon="el-icon-plus" @click="addForm.params.push({name:'',value:''})" style="margin-bottom:10px">添加params</el-button>
              <el-table size="mini" :data="addForm.params"  border  style="width: 100%">
                <el-table-column width="50" align="center">
                  <template slot-scope="scope">
                    <i class="el-icon-delete" style="font-size:20px" @click="addForm.params.splice(scope.$index,1)"></i>
                  </template>
                </el-table-column>
                <el-table-column label="参数名称" width="180"  align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="参数名称"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="参数值"  align="center">
                  <template slot-scope="scope">
                    <el-popover :ref="`jarParamSelector-params`" key="params" placement="bottom-start" trigger="click">
                      <div style="display: flex">
                        <div style="margin-right: 10px;max-height: 300px;overflow-y: auto">
                          <p>引用字段</p>
                          <template v-for="field of tobeChooseWeidu">
                            <div :key="field.columnTitle" :title="field.columnName" class="weidu" @click="setJarValueFun(scope.row,`[${field.columnName}]`)">
                              {{ field.columnTitle + '【' + field.columnName + '】' }}
                            </div>
                          </template>
                          <template v-for="field of tobeChooseZhibiao">
                            <div :key="field.columnTitle" :title="field.columnName" class="zhibiao" @click="setJarValueFun(scope.row,`[${field.columnName}]`)">
                              {{ field.columnTitle + '【' + field.columnName + '】' }}
                            </div>
                          </template>
                        </div>
                        <el-cascader-panel v-model="parParam" :options="paramList" :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }" @change="setJarValueFun(scope.row,`\${${$event}}`)"></el-cascader-panel>
                      </div>
                      <el-button slot="reference" size="mini" type="success" plain>插入变量</el-button>
                    </el-popover>
                    <el-input v-model="scope.row.value" placeholder="参数值" style="width:300px;margin-left:10px;"></el-input>

                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="body" name="body" v-if="addForm.method === 'POST' ">
              <el-radio-group v-model="addForm.bodyType">
                <el-radio label="form-data">form-data</el-radio>
                <el-radio label="raw-json">raw-json</el-radio>
              </el-radio-group>
              <div v-if="addForm.bodyType === 'form-data' ">
                <el-button size="mini" type="success" plain icon="el-icon-plus" @click="formDataList.push({key:'',value:''})" style="margin:10px 0">添加参数</el-button>
                <el-table size="mini" :data="formDataList"  border  style="width: 100%">
                  <el-table-column width="50" align="center">
                    <template slot-scope="scope">
                      <i class="el-icon-delete" style="font-size:20px" @click="formDataList.splice(scope.$index,1)"></i>
                    </template>
                  </el-table-column>
                  <el-table-column label="key" width="180"  align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.key" placeholder="key"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="value"  align="center">
                    <template slot-scope="scope">
                      <el-popover :ref="`jarParamSelector-body`" key="params" placement="bottom-start" trigger="click">
                        <div style="display: flex">
                          <div style="margin-right: 10px;max-height: 300px;overflow-y: auto">
                            <p>引用字段</p>
                            <template v-for="field of tobeChooseWeidu">
                              <div :key="field.columnTitle" :title="field.columnName" class="weidu" @click="setJarValueFun(scope.row,`[${field.columnName}]`)">
                                {{ field.columnTitle + '【' + field.columnName + '】' }}
                              </div>
                            </template>
                            <template v-for="field of tobeChooseZhibiao">
                              <div :key="field.columnTitle" :title="field.columnName" class="zhibiao" @click="setJarValueFun(scope.row,`[${field.columnName}]`)">
                                {{ field.columnTitle + '【' + field.columnName + '】' }}
                              </div>
                            </template>
                          </div>
                          <el-cascader-panel v-model="bodParam" :options="paramList" :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }" @change="setJarValueFun(scope.row,`\${${$event}}`)"></el-cascader-panel>
                        </div>
                        <el-button slot="reference" size="mini" type="success" plain>插入变量</el-button>
                      </el-popover>
                      <el-input v-model="scope.row.value" placeholder="value" style="width:300px;margin-left:10px;"></el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <el-input v-if="addForm.bodyType === 'raw-json' " type="textarea" :rows="6" placeholder="请输入body内容" v-model="addForm.body">
              </el-input>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="响应设置" name="req">
<!--        <el-button size="mini" type="success" plain icon="el-icon-plus" @click="addForm.fields.push({name:'',type:'STRING',jsonpath:''})">添加响应字段</el-button>-->
        <el-button size="mini"  plain icon="el-icon-refresh-left" @click="getReqData">响应数据结构预览</el-button>
        <el-button size="mini" type="text" icon="el-icon-paperclip" @click="openJson">jsonpath使用说明</el-button>
        <el-table size="mini" :data="addForm.fields"  border  style="width: 100%;margin:10px 0;">
<!--          <el-table-column width="50" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <i class="el-icon-delete" style="font-size:20px" @click="addForm.fields.splice(scope.$index,1)"></i>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="字段" width="180"  align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="字段名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="字段值" width="180"  align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" placeholder="字段名称"></el-input>
            </template>
          </el-table-column>
<!--          <el-table-column label="字段类型" width="180"  align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <el-select v-model="scope.row.type" placeholder="请选择字段类型">-->
<!--                <el-option label="字符串" value="STRING"></el-option>-->
<!--                <el-option label="整数" value="INT"></el-option>-->
<!--                <el-option label="长整数" value="BIGINT"></el-option>-->
<!--                <el-option label="浮点数" value="DOUBLE"></el-option>-->
<!--                <el-option label="精确浮点数" value="FLOAT"></el-option>-->
<!--                <el-option label="日期" value="DATE"></el-option>-->
<!--                <el-option label="时间" value="TIME"></el-option>-->
<!--                <el-option label="日期时间" value="TIMESTAMP"></el-option>-->
<!--              </el-select>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="json路径"  align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.jsonpath" placeholder="json路径"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <p style="margin-bottom:10px;">响应数据预览</p>
        <JSONEditor v-loading="loading" v-model="template" class="json-editor" />
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showEditComputedField = false">取 消</el-button>
      <el-button type="primary" @click="codeModeSubmit">确 定</el-button>
    </span>
  </el-dialog>

</div>
</template>
<script>
import {cubeFieldList} from "@/api/newbi/dataset";
import {categoryList, paramList} from "@/api/newbi/globalParams";
import JSONEditor from "@/components/JsonEditor/index.vue";
import {addCustomEvent,apiExecute} from "@/api/onlineDev/visualDev";
export default {
  name: "customApiEvent",
  components: {JSONEditor},
  props: ['modelId','dbLinkId','dbSourceId'],
  data(){
    return {
      id:'',
      eventName:'',
      executeTiming: 2,
      datasourceId:'',
      eventType: 3,
      eventStatus: 0,
      activeName: 'post',
      formActiveName: 'headers',
      showEditComputedField: false,
      formDataList:[{key:'',value:''}],
      addForm:{
        url:'',
        method:'GET',
        params:[{name:'',value:''}],
        headers:[{name:'',value:''}],
        bodyType:'form-data',
        body:'',
        fields:[{name:'',value:'',jsonpath:''}],
      },
      tobeChooseWeidu: [], // 计算字段编辑框里维度字段
      tobeChooseZhibiao: [], // 计算字段编辑框里指标字段
      hedParam:[],
      parParam:[],
      bodParam:[],
      paramList: [],
      template:'',
      rules: {
        url: [
          { required: true, message: '请输入请求路径', trigger: 'blur' },
        ],
        method: [
          { required: true, message: '请选择请求方式', trigger: 'change' }
        ],
      },
      loading:false
    }
  },
  created(){

  },
  methods:{
    addFuncClick(row){
      this.showEditComputedField = true
      this.template = {}
      this.$nextTick(() => {
        if (row && row.id) {
          this.eventName = row.eventName
          this.executeTiming = row.executeTiming
          this.eventType = row.eventType
          this.eventStatus = row.eventStatus
          this.datasourceId = row.eventDatasourceId
          this.id = row.id
          this.addForm = JSON.parse(row.eventSql)
          if (this.addForm.method === 'POST' && this.addForm.bodyType === 'form-data') {
            this.formDataList = JSON.parse(this.addForm.body)
          }else{
            this.formDataList = [{key:'',value:''}]
          }
        } else {
          this.eventName = ''
          this.executeTiming = 2
          this.eventType = 3
          this.eventStatus = 0
          this.id = ''
          this.datasourceId = this.dbSourceId
          this.addForm = {
            url:'',
            method:'GET',
            params:[{name:'',value:''}],
            headers:[{name:'',value:''}],
            body:'',
            bodyType:'form-data',
            fields:[{name:'',value:'',jsonpath:''}],
          }
          this.formDataList = [{key:'',value:''}]
        }
      })
      this.getGlobalData()
    },
    // 获取系统变量
    getGlobalData() {
      //获取数据集
      cubeFieldList({cubeDataId: this.dbLinkId}).then((res) => {
        let tableFieldsWeidu = res.data.data.filter((i) => i.dimensionType === 'WEIDU').sort((a, b) => a.sortNum - b.sortNum)
        let tableFieldsZhibiao = res.data.data.filter((i) => i.dimensionType === 'ZHIBIAO').sort((a, b) => a.sortNum - b.sortNum)
        this.tobeChooseWeidu = tableFieldsWeidu.filter((i) => i.columnAttr == 'NORMAL')
        this.tobeChooseZhibiao = tableFieldsZhibiao.filter((i) => i.columnAttr == 'NORMAL')
      })
      categoryList({ size: 10000, current: 1 }).then((res) => {
        let list = res.data.data.records
        let parents = list.filter((i) => !i.parentId)
        let categoryList = []
        list.forEach((i) => {
          i.children = []
          if (i.parentId) {
            let parent = parents.find((j) => j.id == i.parentId)
            parent.hasChild = true
            i.label = parent.typeName + ' / ' + i.typeName
            categoryList.push(i)
          } else {
            i.label = i.typeName
          }
        })
        categoryList = categoryList.concat(parents.filter((i) => !i.hasChild))
        paramList({ size: 10000, current: 1 }).then((res) => {
          let params = res.data.data.records
          params.forEach((i) => {
            i.label = i.paramName
            let parent = categoryList.find((j) => j.id == i.typeId)
            parent.children.push(i)
          })
          this.paramList = categoryList
        })
      })
    },
    setJarValueFun(value,field){
      value.value = field;
      document.body.click()
    },
    getReqData(){
      this.template = {
        "code": "加载中...",
        "method": "POST",
        "params":[{
          "name":"",
          "value":""
        }],
        "headers": [{
          "name":"",
          "value":""
        }],
        "body": "",
        "fields": [
          {
            "name": "",
            "type": "STRING",
            "jsonpath": "",

          }
        ]
      }
      this.loading = true
      if (this.addForm.method === 'POST' && this.addForm.bodyType === 'form-data') {
        this.addForm.body = JSON.stringify(this.formDataList)
      }
      let data = {
        url:this.addForm.url,
        method:this.addForm.method,
        body:this.addForm.body,
        bodyType:this.addForm.bodyType,
        params:this.addForm.params.reduce((obj, header) => {
          obj[header.name] = header.value;
          return obj;
        }, {}),
        headers:this.addForm.headers.reduce((obj, header) => {
          obj[header.name] = header.value;
          return obj;
        }, {})
      }
      apiExecute(data).then((res)=>{
        try {
          this.template = JSON.parse(res.data.data)
        }catch (e){}
        this.loading = false
      }).finally(()=>{
        this.loading = false
      })
    },
    codeModeSubmit(){
      if (this.addForm.method === 'POST' && this.addForm.bodyType === 'form-data') {
        this.addForm.body = JSON.stringify(this.formDataList)
      }
      if (this.addForm.method !== 'POST') {
        this.addForm.body = ''
        this.formDataList = [{key:'',value:''}]
      }
      let params = {
        id: this.id,
        eventName: this.eventName,
        executeTiming: this.executeTiming,
        eventDatasourceId: this.dbSourceId,
        eventType: this.eventType,
        eventStatus: this.eventStatus,
        eventSql:  JSON.stringify(this.addForm),
      }
      addCustomEvent(this.modelId, params).then((res) => {
        this.$message({
          message: res.data.msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.$emit('onChangeExp')
            this.showEditComputedField = false
          }
        })
      })
    },
    openJson(){
      window.open('https://jsonpath.com/','_blank')
    }
  }
}
</script>
<style scoped lang="scss">
.json-editor {
  height: 300px;
  position: relative;
  box-sizing: border-box;
}
::v-deep .json-editor .CodeMirror {
  height: 100% !important;
}
</style>
