<template>
  <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 ? '编辑自定义赋值模式事件' : '新增自定义赋值模式事件' }}
      <span style="color:#ff0000;font-size:12px;">注：表单赋值当前仅支持更新数据</span>
    </p>
    <div >
      <div style="margin-bottom:5px;">
        事件名称：<el-input style="width:300px" v-model="eventName" placeholder="请输入事件名称"></el-input>
        <el-button style="float:right;" type="success" plain size="mini" @click="list.length < 3 && list.push({formName:'',dataTable:'',operate:1,primaryStrategy:'',idKeyName:'',FormColumnList:[{columnId:'',columnName:'',value:''}],columnList:[],filterColumnList:[{columnId:'',viewDataType:'STRING',function:'like',value:''}]});">+添加分组</el-button>
      </div>
      <div style="height: 500px;overflow-y:auto">
        <el-card class="box-card" v-for="(value,key) in list" style="margin-bottom: 10px" :key="key">
          <div slot="header">
            表单名称：
            <el-select v-model="value.formName" filterable placeholder="请选择" clearable @change="onRelationTableChange($event,value)">
              <el-option v-for="(item, index) in allTabelList.filter(o=> (o.associationType && o.associationType == 1) && (o.visualdevTableType && o.visualdevTableType == 1))" :label="item.fullName" :value="item.id" :key="item.id"></el-option>
            </el-select>
            <span style="margin-left:10px">物理数据表：{{value.dataTable}}</span>
            <i class="el-icon-delete" style="font-size:20px;color:#13ce66;float: right;cursor: pointer;" @click="list.length > 1 ? list.splice(key,1) : $message.warning('至少保留一个分组') "></i>
          </div>
          <el-button type="success" plain size="mini" @click="value.FormColumnList.push({columnId:'',columnName:'',value:''});">+添加字段</el-button>
          <el-select style="float:right;bottom:5px;" v-model="value.operate" filterable placeholder="请选择方式" clearable >
            <el-option  label="新增" :value="0" :key="0"></el-option>
            <el-option  label="编辑" :value="1" :key="1"></el-option>
          </el-select>
          <el-table v-loading="loading" size="mini" :data="value.FormColumnList"  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="value.FormColumnList.splice(scope.$index,1)"></i>
              </template>
            </el-table-column>
            <el-table-column label="表单字段" width="180"  align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.columnId" filterable @change="scope.row.columnName = value.columnList.find(o=> o.propId === $event).prop" placeholder="请选择表单字段" clearable >
                  <el-option v-for="(item, index) in value.columnList" :label="item.label" :value="item.propId" :key="item.propId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="赋值" align="center">
              <template slot-scope="scope">
                <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(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="nowParam" :options="paramList" :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }" @change="setJarValueFun(scope.row,`\${${$event}}`)"></el-cascader-panel>
                  </div>
                  <el-button slot="reference" type="success" plain size="mini">插入变量</el-button>
                </el-popover>
                <el-input v-model="scope.row.value" style="width:250px;margin-left:10px" placeholder="value"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <span style="margin-right:10px">筛选设置</span>
          <el-button type="success" plain size="mini" @click="value.filterColumnList.push({columnId:'',viewDataType:'STRING',function:'like',value:''});">+添加筛选条件</el-button>
          <el-table v-loading="loading" size="mini" :data="value.filterColumnList"  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="value.filterColumnList.splice(scope.$index,1)"></i>
              </template>
            </el-table-column>
            <el-table-column label="表单字段" width="180"  align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.columnId" filterable placeholder="请选择表单字段" clearable @change="scope.row.function = '';scope.row.viewDataType = value.columnList.find(o=>o.propId === scope.row.columnId)?.config?.viewDataType">
                  <el-option v-for="(item, index) in value.columnList" :label="item.label" :value="item.propId" :key="item.propId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column  label="过滤条件" width="130"  align="center">
              <template slot-scope="scope">
                <el-select size="mini" v-model="scope.row.function" placeholder="选择条件" @change="scope.row.function === 'between' ? scope.row.viewDataType === 'NUMBER' ? scope.row.value = ['',''] : scope.row.value = [] : scope.row.function === 'in' ? scope.row.value = [] : scope.row.value = '' ">
                  <el-option v-for="func of globalFunctions[scope.row.viewDataType].filter(o=> o.function !== 'in')" :key="func.function" :value="func.function" :label="func.label"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="赋值" align="center">
              <template slot-scope="scope">
                <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(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="nowParam" :options="paramList" :props="{ expandTrigger: 'click', emitPath: false, value: 'paramKey' }" @change="setJarValueFun(scope.row,`\${${$event}}`)"></el-cascader-panel>
                  </div>
                  <el-button slot="reference" type="success" plain v-if="!['between'].includes(scope.row.function) && scope.row.viewDataType !== 'DATETIME'" size="mini">插入变量</el-button>
                </el-popover>
                <template v-if="scope.row.viewDataType === 'STRING' || scope.row.viewDataType === 'NUMBER'">
                  <template v-if="scope.row.function === 'eq' || scope.row.function === 'like' || scope.row.function === ''">
                    <el-input  v-model="scope.row.value" style="width:130px;margin-left:10px" placeholder="value"></el-input>
                  </template>
                  <template  v-if="scope.row.function === 'between'">
                    <el-input style="width: 100px" size="mini" v-model="scope.row.value[0]"  placeholder="输入值"></el-input>
                    <span>~</span>
                    <el-input style="width: 100px" size="mini" v-model="scope.row.value[1]" placeholder="输入值"></el-input>
                  </template>
                </template>
                <template v-if="scope.row.viewDataType === 'DATETIME'">
                  <el-date-picker style="width:220px" v-model="scope.row.value" type="daterange" placeholder="选择日期" clearable value-format="timestamp" ></el-date-picker>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <div style="text-align:right" class="dialog-footer">
          <el-button @click="showEditComputedField = false">取 消</el-button>
          <el-button type="primary" @click="codeModeSubmit">确 定</el-button>
    </div>
    </div>
  </el-dialog>
</template>
<script>
import {cubeFieldList} from "@/api/workFlow/FlowEngine";
import {categoryList, paramList} from "@/api/newbi/globalParams";
import {addCustomEvent, getConfigData} from "@/api/onlineDev/visualDev";
import {globalFunctions} from "@/utils/dict";

export default {
  name: "customFormEvent",
  computed: {
    globalFunctions() {
      return globalFunctions
    }
  },
  props: ['modelId','dbLinkId','dbSourceId','allTabelList'],
  data(){
    return {
      eventName:'',
      executeTiming: 2,
      datasourceId:'',
      eventType: 4,
      eventStatus: 0,
      loading:false,
      showEditComputedField:false,
      tobeChooseWeidu: [], // 计算字段编辑框里维度字段
      tobeChooseZhibiao: [], // 计算字段编辑框里指标字段
      paramList: [],
      id:'',
      list:[
        {formName:'',dataTable:'',operate:1,primaryStrategy:'',idKeyName:'',FormColumnList:[{columnId:'',columnName:'',value:''}],columnList:[],filterColumnList:[{columnId:'',viewDataType:'STRING',function:'like',value:''}]}
      ],
      nowParam:[]
    }
  },
  methods:{
    setJarValueFun(value,field){
      value.value = field;
      document.body.click()
    },
    addFuncClick(row){
      this.showEditComputedField = true
      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.list = JSON.parse(row.eventSql)
        }else {
          this.id = ''
          this.eventName = ''
          this.executeTiming = 2
          this.eventType = 4
          this.eventStatus = 0
          this.datasourceId = this.dbSourceId
          this.list =[
            {formName:'',dataTable:'',operate:1,primaryStrategy:'',idKeyName:'',FormColumnList:[{columnId:'',columnName:'',value:''}],columnList:[],filterColumnList:[{columnId:'',viewDataType:'STRING',function:'like',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
        })
      })
    },
    onRelationTableChange(v,value) {
      this.loading = true
      getConfigData(v).then((res) => {
        let data = res.data.data
        value.dataTable = data.primaryTableName
        value.primaryStrategy = data.primaryStrategy
        let columnData = JSON.parse(data.columnData)
        value.columnList = columnData.columnList
        value.idKeyName = columnData.columnList.find(o=> o.propId === data.idKey)?.prop || ''
        this.loading = false
      }).finally(()=>{
        this.loading = false
      })
    },
    codeModeSubmit(){
      let params = {
        id: this.id,
        eventName: this.eventName,
        executeTiming: this.executeTiming,
        eventDatasourceId: this.dbSourceId,
        eventType: this.eventType,
        eventStatus: this.eventStatus,
        eventSql:  JSON.stringify(this.list),
      }
      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;
}
</style>
