<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="40%">
    <p slot="title">
      {{ id ? '编辑自定义事件' : '新增自定义事件' }}
      <el-popover placement="bottom" title="注意事项" width="400" trigger="hover">
        <div v-if="addForm.eventType === 1">
          <p>1、将自动执行类中的第一个静态方法；</p>
          <p>2、前置事件必须返回一行一列数据，当返回值为0允许继续执行，非0时终止执行；</p>
          <p>3、自定义参数定在后，需要在‘插入参数’中进行插入到代码中，自定义变量值放在两个&号中间；</p>
          <p>样例如下：</p>
          <p>public class lowCodeTest {</p>
          <p>&nbsp;public static Integer main() {</p>
          <p>&nbsp;&nbsp;String username = "jakcy";</p>
          <p>&nbsp;&nbsp;Integer result = 0;</p>
          <p>&nbsp;&nbsp;if(username.equals("jakcy")){</p>
          <p>&nbsp;&nbsp;&nbsp;result = 1;</p>
          <p>&nbsp;&nbsp; }</p>
          <p>&nbsp;&nbsp;return result;</p>
          <p>&nbsp; }</p>
          <p>}</p>
        </div>
        <div v-else>
          <p>1、前置事件必须返回一行一列数据，当返回值为0允许继续执行，非0时终止执行；</p>
          <p>2、'包路径'表示jar执行类的路径地址，如:com.demo.utils.DcService</p>
          <p>3、'函数名'表示jar执行类的方法名，方法必须为静态方法，如:main，函数名不需要加括号；</p>
          <p>4、添加参数key值必须为java.lang.String类型,如需其它类型，在main方法中进行转换；</p>
        </div>
        <el-button slot="reference" type="text" >注意事项<i class="el-icon-question" /></el-button>
      </el-popover>
    </p>
    <el-form :model="addForm" label-position="left" label-width="100px" ref="addForm">
      <el-form-item label="事件名称">
        <el-input v-model="addForm.eventName" placeholder="请输入事件名称"></el-input>
      </el-form-item>
      <el-form-item label="处理时机">
        <el-radio-group v-model="addForm.executeTiming">
          <el-radio v-model="addForm.executeTiming" :label="2">后置执行</el-radio>
          <el-radio v-model="addForm.executeTiming" :label="1">
            前置执行
            <el-tooltip style="cursor: pointer" effect="dark" placement="top">
              <div slot="content">
                注：前置事件必须返回一行一列数据，当返回值为0允许继续执行，非0时终止执行；
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="jar包上传" v-if="addForm.eventType === 2">
        <el-upload
          :action="define.comUploadUrl"
          :headers="uploadHeaders"
          :file-list="fileList"
          :on-success="handleSuccess"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-exceed="handleExceed"
          :limit="1">
          <el-button size="small" icon="el-icon-upload" >点击上传</el-button>
        </el-upload>
        <template v-if="fileList.length">
          <transition-group class="el-upload-list el-upload-list el-upload-list--text" tag="ul" name="el-list">
            <li class="el-upload-list__item is-success" v-for="(file, index) in fileList" :key="file.fileId">
              <a class="el-upload-list__item-name"> <i class="el-icon-document"></i>{{ file.name }} </a>
              <label class="el-upload-list__item-status-label">
                <i class="el-icon-upload-success el-icon-circle-check"></i>
              </label>
              <i class="el-icon-close"  @click="handleRemove(file, index)"></i>
            </li>
          </transition-group>
        </template>
      </el-form-item>
      <el-form-item label="包路径" v-if="addForm.eventType === 2">
        <el-input v-model="addForm.className" placeholder="请输入包路径"></el-input>
      </el-form-item>
      <el-form-item label="函数名" v-if="addForm.eventType === 2">
        <el-input v-model="addForm.methodName" placeholder="请输入函数名"></el-input>
      </el-form-item>
      <el-form-item v-if="addForm.eventType === 2">
        <el-button type="text" size="mini" @click="eventJarValueList.push({parameterType:'java.lang.String', value:'自定义的value2'});">+添加参数</el-button>
        <div v-for="(value,key) in eventJarValueList" style="display: flex;align-content: center;flex-wrap: nowrap;align-items: center;margin-bottom: 10px" :key="key">
          <el-popover :ref="`jarParamSelector-${key}`" :key="key" 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(value,`[${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(value,`[${field.columnName}]`)">
                    {{ field.columnTitle + '【' + field.columnName + '】' }}
                  </div>
                </template>
              </div>
              <el-cascader-panel v-model="nowParam" :options="paramList" :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }" @change="setJarValueFun(value,`\${${$event}}`)"></el-cascader-panel>
            </div>
            <el-button slot="reference" type="text" size="mini">+插入变量</el-button>
          </el-popover>
          <div>
            <el-input v-model="value.parameterType" placeholder="请输入参数" disabled></el-input>
          </div>
          <p style="margin: 0 10px">：</p>
          <div style="position: relative">
            <el-input v-model="value.value" placeholder="请输入值" ></el-input>
          </div>
          <i class="el-icon-delete delete-btn" @click="eventJarValueList.splice(key,1)" style="cursor: pointer;margin-left: 10px"></i>
        </div>
      </el-form-item>
      <el-form-item label="脚本" v-if="addForm.eventType === 1">
        <el-popover ref="paramSelector" placement="bottom-start" trigger="click">
          <div style="display: flex">
            <div style="margin-right: 10px">
              <p>自定义参数</p>
              <template v-for="(field,k) in eventValueList">
                <div :key="k" :title="field.key" class="diyText" @click="$refs.editor.editor.insert(`&${field.key}&`);$refs.paramSelector.doClose()">
                  {{ field.key + '【' + field.value + '】' }}
                </div>
              </template>
            </div>
            <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="$refs.editor.editor.insert(`[${field.columnName}]`);$refs.paramSelector.doClose()">
                  {{ field.columnTitle + '【' + field.columnName + '】' }}
                </div>
              </template>
              <template v-for="field of tobeChooseZhibiao">
                <div :key="field.columnTitle" :title="field.columnName" class="zhibiao" @click="$refs.editor.editor.insert( `[${field.columnName}]`);$refs.paramSelector.doClose()">
                  {{ field.columnTitle + '【' + field.columnName + '】' }}
                </div>
              </template>
            </div>
            <el-cascader-panel v-model="nowParam" :options="paramList" :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }" @change="$refs.editor.editor.insert( `\${${$event}}`);$refs.paramSelector.doClose()"></el-cascader-panel>
          </div>
          <el-button slot="reference" type="text" size="mini">+插入参数</el-button>
        </el-popover>
          <aceEditor ref="editor" v-model="nowComputedField.columnFormula" height="200" lang="javascript" snippets wrap />
<!--        <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 12}" placeholder="请输入脚本" v-model="addForm.eventSql"></el-input>-->
      </el-form-item>
      <el-form-item v-if="addForm.eventType === 1">
        <el-button type="text" size="mini" @click="eventValueList.push({key:'自定义的key', value:'自定义的value2'})">+添加参数</el-button>
        <div v-for="(value,key) in eventValueList" style="display: flex;align-content: center;flex-wrap: nowrap;align-items: center;margin-bottom: 10px" :key="key">
          <div>
            <el-input v-model="value.key" placeholder="请输入参数" ></el-input>
          </div>
          <p style="margin: 0 10px">：</p>
          <div style="position: relative">
            <el-input v-model="value.value" placeholder="请输入值" ></el-input>
          </div>
          <i class="el-icon-delete delete-btn" @click="eventValueList.splice(key,1)" style="cursor: pointer;margin-left: 10px"></i>
        </div>
      </el-form-item>
    </el-form>
    <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 {getToken} from "@/utils/auth";
import { categoryList, paramList } from '@/api/newbi/globalParams'
import { cubeFieldList } from '@/api/workFlow/FlowEngine'
import aceEditor from "@/components/AceEditor/index.vue";
import {addCustomEvent} from "@/api/onlineDev/visualDev";
import alert from "element-ui/packages/alert";
export default {
  computed: {
    alert() {
      return alert
    }
  },
  components: {aceEditor},
  props: ['dbLinkId', 'modelId', 'dbSourceId','eventTypeRadio'],
  data() {
    return {
      showEditComputedField: false,
      uploadHeaders: { 'Blade-Auth': 'bearer ' + getToken() },
      fileList:[],
      id:'',
      addForm: {
        eventName: '',
        jarFilePath: '',
        methodName: '',
        className: '',
        eventSql: '',
        eventType: 1,
        executeTiming:2,
        eventStatus: 0,
      },
      eventValueList: [{key:'自定义的key', value:'自定义的value2'}],
      eventJarValueList: [{parameterType:'java.lang.String', value:'自定义的value2'}],
      paramList: [],
      tobeChooseWeidu: [], // 计算字段编辑框里维度字段
      tobeChooseZhibiao: [], // 计算字段编辑框里指标字段
      nowParam:[],
      nowComputedField: {
        columnFormula: ''
      },
    }
  },
  created() {
    this.getGlobalData()
  },
  methods: {
    setJarValueFun(value,field){
      value.value = field;
      document.body.click()

    },
    // 获取系统变量
    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
        })
      })
    },
    addFuncClick(row) {
      this.showEditComputedField = true
      this.fileList = []
      this.eventValueList = [{key:'自定义的key', value:'自定义的value2'}]
      this.eventJarValueList = [{parameterType:'java.lang.String', value:'自定义的value2'}]
      if (row && row.id){
        this.addForm.eventType = row.eventType
      }else {
        this.addForm.eventType = this.eventTypeRadio
      }
      this.$nextTick(() => {
        if (row && row.id) {
          this.addForm.eventName = row.eventName
          this.addForm.executeTiming = row.executeTiming
          this.addForm.eventType = row.eventType
          this.addForm.eventStatus = row.eventStatus
          this.id = row.id
          let obj = JSON.parse(row.eventValue)
          this.eventValueList = Object.keys(obj).map(key => ({ key, value: obj[key] }));
          if (this.addForm.eventType === 1) this.$refs.editor.editor.setValue(row.eventSql)
          if (this.addForm.eventType === 2){
            let jarEventVal = JSON.parse(row.eventSql)
            this.addForm.className = jarEventVal.className
            this.addForm.methodName = jarEventVal.methodName
            this.addForm.jarFilePath = jarEventVal.jarFilePath
            this.fileList = [{name: jarEventVal.jarFilePath,fileId: jarEventVal.jarFilePath,url: jarEventVal.jarFilePath}]
            this.eventJarValueList = obj
          }
        } else {
          this.addForm.eventName = ''
          this.addForm.executeTiming = 2
          this.addForm.eventStatus = 0
          this.id = ''
          this.addForm.className = ''
          this.addForm.methodName = ''
          this.addForm.jarFilePath = ''
          if (this.addForm.eventType === 1) this.$refs.editor.editor.setValue('')
        }
      })
    },
    beforeUpload(file) {
      const unitNum = 1024 * 1024 * 500
      let isRightSize = file.size < unitNum
      if (!isRightSize) {
        this.$message.error(`文件大小超过500MB`)
      }
      return isRightSize
    },
    handleSuccess(res, file, fileList) {
      // 如果数组类型
      if (res.code === 200) {
        this.fileList.push({name: file.name,fileId: res.msg,url: res.msg})
        this.addForm.jarFilePath = res.msg
      } else {
        fileList.filter((o) => o.uid != file.uid)
        this.fileList = []
        this.$message({ message: '上传失败', type: 'error', duration: 1500 })
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多可以上传1个文件`)
    },
    handleRemove(file, index) {
      this.fileList.splice(index, 1)
      this.$emit('input', this.fileList)
    },
    codeModeSubmit(){
      let eventValue = {}
      this.eventValueList.forEach((i,k)=>{eventValue[i.key] = i.value})
      let { columnFormula } = this.nowComputedField
      if (this.addForm.eventType === 1 && !columnFormula) {
        return this.$message({ message: '请补充完整', type: 'warning' })
      }
      let jarEventSql = {jarFilePath : this.addForm.jarFilePath, className : this.addForm.className, methodName : this.addForm.methodName}
      let params = {
        id: this.id,
        eventName: this.addForm.eventName,
        executeTiming: this.addForm.executeTiming,
        eventDatasourceId: this.dbSourceId,
        eventType: this.addForm.eventType,
        eventStatus: this.addForm.eventStatus,
        eventSql: this.addForm.eventType === 1 ? columnFormula : JSON.stringify(jarEventSql),
        eventValue: this.addForm.eventType === 1 ? JSON.stringify(eventValue) : JSON.stringify(this.eventJarValueList)
      }
      addCustomEvent(this.modelId, params).then((res) => {
        this.$message({
          message: res.data.msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.$emit('onChangeExp')
            this.showEditComputedField = false
          }
        })
      })
    },
  }

}
</script>
<style scoped lang="scss">
.weidu {
  line-height: 24px;
  box-sizing: border-box;
  border: 1px solid #1d54d5;
  background-color: #e4eafa;
  padding: 0 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin: 3px 0;
  cursor: pointer;
}
.zhibiao {
  line-height: 24px;
  box-sizing: border-box;
  border: 1px solid #00b375;
  background-color: #d4f2e8;
  padding: 0 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin: 3px 0;
  cursor: pointer;
}
.diyText {
  line-height: 24px;
  box-sizing: border-box;
  border: 1px solid #7e52bb;
  background-color: #dad2ea;
  padding: 0 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  margin: 3px 0;
  cursor: pointer;
}
</style>
