<template>
  <topology
      ref="topologyRef"
      @handleSave="handleSave"
      @handlePreview="handlePreview"
      @handleTopoLine="handleTopoLine"
      :node-type-list="nodeTypeList"
      :node-app-config="nodeAppConfig"
      :edge-app-config="edgeAppConfig"
      :relational-map="relationalMap"
  >
  </topology>
  <div class="top-dialog">
    <el-dialog title="预览" width="1500px" v-model="previewShow" @close="closePreview" @submit.prevent="handlePreviewData">
      <el-form inline class="query-form" ref="queryForm" >
        <el-form-item v-for="column in uniCons" :key="column.ucId"
                      :label="column.ucName">
          <el-input :placeholder="column.ucDescribe" :type="column.ucType" v-model="column.query" clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePreviewData" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="table">
        <el-table :data="previewTable" v-loading="previewLoading">
          <el-table-column v-for="column in uniColumns" :key="column.prop" :prop="column.prop"
                           :label="column.label" align="center">
            <template #default="scope">
              <template v-if="column.displayType === 'date'">
                {{ simpleDateMoreFormat(scope.row[column.prop], column.displayParam) }}
              </template>
              <template v-if="column.displayType === 'text'">
                {{ scope.row[column.prop] }}
              </template>
              <template v-if="column.displayType === 'image'">
                <change-image :displayType="'image'" :column-prop="scope.row[column.prop]" :params="imageSettingParams"></change-image>
<!--                <el-image :src="scope.row[column.prop]">-->
<!--                  <template #error>-->
<!--                    <div class="image-slot">-->
<!--                      <el-image :src="avatar"></el-image>-->
<!--                    </div>-->
<!--                  </template>-->
<!--                </el-image>-->
              </template>
              <template v-if="column.displayType === 'dict'">
                {{ scope.row[column.prop] }} 字典
              </template>
              <template v-if="column.displayType === 'html'">
                <div v-html="scope.row[column.prop]"></div>
                超文本标记
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <paging :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" :page-sizes="[10, 20, 30, 40,50]"
              :total="total" @changeSize="handleSizeChange" @goPage="handleCurrentChange"/>
    </el-dialog>
  </div>
  <div class="top-dialog">
    <el-dialog v-model="isTopLineVisited" title="上线" width="700px">
      <el-form :model="form" :rules="formRules" class="query-form" ref="formInstance">
        <el-form-item label="上级菜单">
          <el-tree-select v-model="form.parentId" :data="menuOpt" style="width: 100%;"
                          :filter-node-method="filterNodeMethod" filterable :check-strictly="true"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formInstance)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import Topology from "@/views/custom-query/topo/top/topology.vue"
import {getTopoDragInfo, saveTopo, previewTopo, previewTopologyData, topoToLine} from "@/api/custom-query/topo-search"
import {simpleDateMoreFormat} from "./utils/date.js";
import {reactive} from "vue";
import {ElMessage} from "element-plus";
import {Search, Refresh} from '@element-plus/icons-vue'
import {getMenuOpt} from '@/api/system/menuman.js'
import Paging from "@/components/pagination/index.vue";
import ChangeImage from "./components/changeImage/ChangeImage.vue";
const router = useRouter()
const params = reactive(router.currentRoute.value.params)
const isTopLineVisited = ref(false)
const form = ref({
  parentId: ''
})
const formRules = ref({
  parentId: [{required: true, message: '请选择上级菜单', trigger: 'blur'}]
})
const imageSettingParams = ref({})
const formInstance = ref()
const menuOpt = ref([])
const topologyRef = ref()
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
})
const jsonData = ref()
const queryForm = ref([])
const queryValue = ref(null)
const total = ref(0)
const previewLoading = ref(true)
const nodeTypeList = ref([])
const relationalMap = ref(new Map())
const graphDefaultData = ref([])
const previewShow = ref(false)
const previewTable = ref({})
const uniColumns = ref({})
const uniCons = ref({})
const ucId = ref(null)

const nodeAppConfig = reactive({
  // ip: '节点IP',
  // port: '节点端口',
  // sysName: '设备名称'
})
const edgeAppConfig = reactive({
  associated: "查询方式",
  sourceColumn: "主表字段",
  targetColumn: "关联字段"
})

const closePreview = () => {
  previewShow.value = false
}
const handleSave = (json) => {
  // if(JSON.parse(json).edges.length!==JSON.parse(json).nodes.length-1){
  //   ElMessage.warning('图与图之间尚未构成联系, 请检查后保存')
  // }else {
  saveTopo({
    queryId: params.queryId,
    topJson: json
  }).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  })
  // }
}
//点击上线按钮弹框
const handleTopoLine = (json) => {
  getMenuOpt().then(res => {
    menuOpt.value = [{
      value: 0,
      label: "一级目录",
      children: res.data
    }]
  })
  jsonData.value = json
  isTopLineVisited.value = true
}
const filterNodeMethod = (value, data) => data.label.includes(value)

const restForm = () => {
  form.value = {
    parentId: ''
  }
}
//取消
const handleCancel = () => {
  restForm();
  isTopLineVisited.value = false;
};
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid, fields) => {
    if (!valid) return
    topoToLine({
      menuId: form.value.parentId,
      queryId: params.queryId,
      topJson: jsonData.value
    }).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg)
        router.push('/custom/query/topo')
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

const handlePreview = (json) => {
  imageSettingParams.value=topologyRef.value.imageSettingParams
  previewLoading.value = true
  previewTopo({
    queryId: params.queryId,
    topJson: json,
  }).then(res => {
    console.log('预览', res)
    if (res.code === 1000) {
      previewShow.value = true
      previewTable.value = res.data.table.rows
      uniColumns.value = res.data.uniColumns
      uniCons.value = res.data.uniCons
      total.value = res.data.table.total
      previewLoading.value = false
      uniCons.value.forEach(item => {
        ucId.value = item.ucId
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}

//重置搜索
const handleReset = () => {
  uniCons.value.forEach(con => {
    con.query = ''
  })
  handlePreviewData()
}

const handlePreviewData = () => {
  previewLoading.value = true
  let queryData = []
  uniCons.value.forEach(con => {
    if (con.query) {
      let queryItem = {
        query: con.query,
        ucId: con.ucId
      }
      queryData.push(queryItem)
    }
  })
  previewTopologyData({
    list: queryData,
    queryId: params.queryId
  }, pageInfo).then(res => {
    previewTable.value = res.data.rows
    total.value = res.data.total
    previewLoading.value = false
  })
}


const getDragInfo = async () => {
  let queryId = params.queryId
  getTopoDragInfo(queryId).then(res => {
    if (res.code === 1000) {
      // console.log('拖拽数据', res.data)
      nodeTypeList.value = res.data.tableList
      // for (let relationalItem of res.data.relational) {
      //   let item = relationalMap.value.get(relationalItem.mainId)
      //   if (null == item) {
      //     item = [];
      //   }
      //   item.push(relationalItem)
      //   relationalMap.value.set(relationalItem.mainId,item)
      // }
      // console.log('res.data.relational', res.data.relational)
      if (res.data.relational.length === 0) {
        relationalMap.value = []
      } else {
        relationalMap.value = res.data.relational
      }
      if (res.data.topJson === null) {
        let data = {
          nodes: [],
          edges: [],
          combos: [],
          groups: []
        }
        topologyRef.value.initTopo(data);
      } else {
        graphDefaultData.value = JSON.parse(res.data.topJson)
        topologyRef.value.initTopo(graphDefaultData.value);
      }
    }
  })
}
//切换每页显示条数
const handleSizeChange = (val) => {
  pageInfo.pageSize = val
  handlePreviewData()
}

//点击页码进行分页功能
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val
  handlePreviewData()
}
getDragInfo()
</script>
<style lang="scss" scoped>
.demo-topology {
  width: 100%;
  height: 100%;
}
</style>

<style lang="scss">
html {
  overflow-x: hidden;
  overflow-y: hidden;
}
</style>

