<template>
  <div>
    <draggable v-model="activeData.event.evenList" group="people">
      <div v-for="(item, index) in activeData.event.evenList" style="border: 1px dotted #ccc; margin-bottom: 5px; padding: 10px; position: relative">
        <el-form :model="item" ref="form" label-width="80px" size="mini">
          <el-form-item label="事件名称" prop="title">
            <el-input v-model="item.title" clearable></el-input>
          </el-form-item>
          <el-form-item label="事件类型" prop="type">
            <el-select v-model="item.type" clearable>
              <el-option label="change" value="change"></el-option>
              <el-option label="input" value="input"></el-option>
            </el-select>
            <div class="help">
              Input:值改变时触发 <br />
              change:仅在输入框失去焦点或用户按下回车时触发
            </div>
          </el-form-item>
          <el-form-item label="API接口" prop="api">
            <div class="flex gap-10">
              <el-cascader
                :options="dataInterfaceSelector"
                v-model="item.api"
                placeholder="请选择API接口"
                :props="{ expandTrigger: 'hover', emitPath: false }"
                :show-all-levels="false"
                clearable
                filterable
                @change="propsUrlChange(item)"
              >
              </el-cascader>
              <el-button @click="getDataInterfaceSelector">刷新</el-button>
            </div>
          </el-form-item>
          <el-divider>API输入参数设置</el-divider>
          <el-form-item :label="o.name" prop="params" v-for="o in item.params">
            <div class="flex">
              <el-select v-model="o.component">
                <el-option v-for="item in componentList" :key="o.__vModel__" :value="item.__vModelName__">
                  <span style="float: left">{{ item.__config__.label }}</span>
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="设置变量">
            <el-popover placement="left" title="选择变量" width="500" trigger="click">
              <el-table :data="previewArr" border row-key="path" default-expand-all height="700px">
                <el-table-column label="结构">
                  <template #default="scope">
                    {{ scope.row.key }}
                  </template>
                </el-table-column>
                <el-table-column label="jsonpath">
                  <template #default="scope">
                    {{ scope.row.path }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="140px" align="center">
                  <template #default="scope">
                    <el-button v-if="scope.row.type === 'array'" size="small" type="primary" plain @click="getAllPath(scope.row)"> 使用全部子项 </el-button>
                    <el-button v-if="scope.row.type !== 'array' && scope.row.type !== 'object'" size="small" type="primary" plain @click="getPath(scope.row, item)"> 使用 </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-button slot="reference" size="mini" type="primary" plain @click="previewClick(item)" icon="View">API返回值结构预览</el-button>
            </el-popover>
          </el-form-item>
          <el-table :data="item.ApiReturn" style="width: 100%">
            <el-table-column prop="keyName" label="API返回值"></el-table-column>
            <el-table-column label="页面变量名">
              <template slot-scope="scope">
                <el-input v-model="scope.row.varName" placeholder="请输入页面变量名" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="50">
              <template slot-scope="scope">
                <div class="close-btn select-line-icon" style="cursor: pointer" @click="item.ApiReturn.splice(scope.$index, 1)">
                  <i class="el-icon-delete" />
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-button style="position: absolute; top: -5px; right: 0" type="text" size="mini" @click="deleteEvenList(index)">X </el-button>
        </el-form>
      </div>
    </draggable>
    <el-button @click="addEvenList"> +新增</el-button>
  </div>
</template>
<script>
import AmisSdk from '@/components/AmisSdk.vue'
import { dataapicategoryList, dataapiDetail, dataapiList } from '@/api/systemData/dataInterface'
import draggable from 'vuedraggable'
import { openurl } from '@/components/Dataset-filter/report'
import { param } from '@/components/Dataset-filter/config'
import { loopActiveTabelList, loopRelationList } from '@/utils'
import comMixin from '@/components/Generator/index/RightComponents/mixin'
const eventObjDefault = {
  title: '事件名称',
  type: 'change',
  api: '',
  params: []
}
export default {
  name: 'Event',
  components: { AmisSdk, draggable },
  mixins: [comMixin],
  props: {
    activeData: {
      type: Object,
      default: () => ({})
    },
    formConf: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      amisJson: {
        type: 'input-sub-form',
        name: 'params',
        multiple: false,
        form: {
          title: '配置子表单',
          body: [
            {
              name: 'code',
              label: '参数',
              type: 'input-text'
            },
            {
              name: '数值',
              label: 'key',
              type: 'input-text'
            }
          ]
        }
      },
      dataInterfaceSelector: [],
      previewShow: false,
      previewArr: []
    }
  },
  computed: {
    componentList() {
      return this.formConf.fields
    }
  },
  mounted() {
    this.getDataInterfaceSelector()
  },
  methods: {
    getDataInterfaceSelector() {
      //获取api列表
      dataapicategoryList().then((res) => {
        let category = res.data.data
        dataapiList({ apiFormal: 1, apiTypes: '1,2' }).then((res) => {
          let list = res.data.data
          this.dataInterfaceSelector = category
            .map((i) => ({
              label: i.categoryName,
              value: i.id,
              children: list.filter((j) => j.categoryId === i.id).map((k) => ({ label: k.apiName, value: k.id, key: k.apiKey, ...k }))
            }))
            .filter((i) => i.children.length)
        })
      })
    },
    addEvenList() {
      this.activeData.event.evenList.push({ ...eventObjDefault })
    },
    deleteEvenList(index) {
      this.activeData.event.evenList.splice(index, 1)
    },
    propsUrlChange(item) {
      console.log(item, this.dataInterfaceSelector)
      const list = g.T.queryNodes(this.dataInterfaceSelector, 'children', function (it) {
        if (it.id == item.api) {
          return true
        }
      })
      this.resJson = JSON.parse(list[0].note || '{}')
      item.params = this.resJson.params
    },
    previewClick(item) {
      if (!item.api)
        return this.$message({
          message: '当前未选择API接口，不支持数据预览',
          type: 'warning'
        })
      dataapiDetail(item.api).then((res) => {
        let { apiKey, apiType, apiJsFunction } = res.data.data
        let resJson = JSON.parse(res.data.data.note || '{}')
        let formVarObj = {}
        let params = {}
        if (apiType === 2) {
          if (resJson.params && resJson.params.length) {
            resJson.params.forEach((i, k) => {
              formVarObj[i.key] = i.def
            })
          }
          params = { apiParam: JSON.stringify({ ...param, ...formVarObj }) }
        } else {
          if (resJson.params && resJson.params.length) {
            resJson.params.forEach((i, k) => {
              formVarObj[i.key] = i.def
            })
          }
          params = { ...param, ...formVarObj }
        }
        openurl(apiKey, params).then((res) => {
          let data = res.data
          if (apiType === 2) {
            data.data = JSON.parse(data.data)
            let handle = eval(`(${apiJsFunction})`)
            data = handle(data.data)
            console.log(data)
          }
          try {
            let arr = []
            this.previewShow = true
            this.jsonPath(arr, data, '$')
            this.previewArr = arr
          } catch (e) {
            this.$message({ message: '接口返回数据格式不支持', type: 'warning' })
          }
        })
      })
    },
    validateType(val) {
      // 校验JSON数据类型
      const type = typeof val
      if (type === 'object') {
        if (Array.isArray(val)) {
          return 'array'
        } else if (val === null) {
          return 'null'
        } else {
          return 'object'
        }
      } else {
        return type
      }
    },
    jsonPath(arr, json, basePath) {
      const type = this.validateType(json)
      if (type === 'object') {
        for (let key in json) {
          const item = {
            key,
            path: `${basePath}.${key}`
          }
          const childType = this.validateType(json[key])
          item.type = childType
          if (childType === 'object' || childType === 'array') {
            item.leaf = true
            item.children = []
            this.jsonPath(item.children, json[key], item.path)
          } else {
            item.leaf = false
            item.value = json[key]
          }
          arr.push(item)
        }
      } else if (type === 'array') {
        json = json[0]
        if (json === undefined) return
        for (let key in json) {
          const item = {
            key,
            path: `${basePath}[*].${key}`
          }
          const childType = this.validateType(json[key])
          item.type = childType
          if (childType === 'object' || childType === 'array') {
            item.leaf = true
            item.children = []
            this.jsonPath(item.children, json[key], item.path)
          } else {
            item.leaf = false
            item.value = json[key]
          }
          arr.push(item)
        }
      }
    },
    getPath(row, item) {
      console.log(row, item)
      item.ApiReturn.push({ keyName: key, varName: key })
    },
    getAllPath(array) {
      array.children.forEach((item) => this.getAPiPath(item))
    },
    getAPiPath({ key }, item) {
      this.activeData.__config__.ApiReturn.push({ keyName: key, varName: key })
      this.getAllapiVarList()
    },
    getAllapiVarList() {
      //获取API返回变量
      this.apiVarList = []
      let mapList = this.activeData.__config__.relationTable ? loopActiveTabelList(this.drawList, this.activeData.__config__.relationTable) : loopRelationList(this.drawList)
      mapList.forEach((item, key) => {
        let config = item.__config__
        if (config.ApiReturn && config.ApiReturn.length) {
          let list = config.ApiReturn.map((o) => {
            return {
              label: o.varName,
              value: o.varName
            }
          }).filter((l) => l !== undefined)
          this.apiVarList = [...this.apiVarList, ...list]
        }
      })
    }
  }
}
</script>
<style scoped lang="scss"></style>
