<template>
  <div class="main">
    <div class="main-head">
      <el-button type="primary" @click="onAddGroup">新增分组</el-button>
    </div>
    <div class="main-content">
      <template v-for="item in group">
        <el-card>
          <el-button type="primary" @click="onAddKey(item)">新增KEY</el-button>
          <template v-if="item.keyList?.length > 0">
            <el-button v-if="!item.isStart" type="success" @click="onStartKey(item)">开始</el-button>
            <el-button v-else type="danger" @click="onStopKey(item)">暂停</el-button>
            <el-button v-if="!item.isStart" type="warning" @click="onEditGroup(item)">编辑分组</el-button>
            <el-button v-if="!item.isStart" type="danger" @click="onDelGroup(item)">删除分组</el-button>
          </template>
          <div>{{item.name}}（{{item.second}}秒）</div>
          <div>{{item.cql}}</div>
          <el-divider />
          <div>
            <template v-for="(key, keyIndex) in item.keyList">
              <div :style="`color: ${key.online ? '' : 'red'}`">
                {{keyIndex + 1}}、{{key.key}}<el-button v-if="!item.isStart" type="danger" size="small" @click="onDelKey(item, key)">删除</el-button>
                <template v-if="item.isStart">
                  <div class="key-content">
                    <div class="key-position">
                      <EasyMapComponent
                          v-if="key.online"
                          class="map"
                          @easyMapLoad="(map, func) => initKeyMap(map, key)"
                      />
                      <div v-else>无信号</div>
                    </div>
                    <div class="key-heart">
                      <HeartLineChart :data="key.apiData"/>
                    </div>
                  </div>
                </template>
              </div>
            </template>
          </div>
        </el-card>
      </template>
    </div>
    <CusDialog
        title="新增分组"
        v-model:show="showGroupDialog"
        @submit="onSaveGroup"
        height="auto"
    >
      <div style="padding: 20px;">
        <CusForm ref="ref_groupForm" @handleEnter="onSaveGroup">
          <CusFormColumn
            label="分组名称"
            required
            :span="24"
            v-model:param="groupForm.name"
          />
          <CusFormColumn
            label="心跳频率"
            required
            link="number"
            unit="秒"
            :span="24"
            v-model:param="groupForm.second"
          />
          <CusFormColumn
              label="cql——{KEY}"
              required
              type="textarea"
              :span="24"
              :rows="8"
              v-model:param="groupForm.cql"
          />
        </CusForm>
      </div>
    </CusDialog>
    <CusDialog
        title="新增KEY"
        v-model:show="showKeyDialog"
        @submit="onSaveKey"
        height="auto"
    >
      <div style="padding: 20px;">
        <CusForm ref="ref_keyForm" @handleEnter="onSaveKey">
          <CusFormColumn
              label="KEY"
              required
              :span="24"
              v-model:param="keyForm.key"
          />
        </CusForm>
      </div>
    </CusDialog>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  ref,
  reactive,
  watch,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs,
  nextTick
} from 'vue'
import {useStore} from 'vuex'
import {useRouter, useRoute} from 'vue-router'
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import * as style from 'ol/style'
import HeartLineChart from './heart-line.vue'

export default defineComponent({
  name: '',
  components: {
    HeartLineChart
  },
  props: {},
  setup(props, {emit}) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties
    const state = reactive({
      DB: <any>null,
      ObjectStore: 'track-status',
      group: <any>[],
      showGroupDialog: false,
      groupForm: {},
      showKeyDialog: false,
      keyForm: {},
    })
    const ref_groupForm = ref()
    const ref_keyForm = ref()
    const request = window.indexedDB.open('SeatTools', 1)
    request.onerror = function (event) {}
    request.onsuccess = function (event) {
      state.DB = request.result
      state.group = []
      init()
    }
    request.onupgradeneeded = function (event: any) {
      state.DB = event.target.result
      if (!state.DB.objectStoreNames.contains(state.ObjectStore)) {
        const objectStore = state.DB.createObjectStore(state.ObjectStore, { autoIncrement: true })
      }
    }
    const init = () => {
      const os = state.DB.transaction(state.ObjectStore).objectStore(state.ObjectStore)
      os.openCursor().onsuccess = e => {
        const cursor = e.target.result
        if (cursor) {
          if (state.group.every(v => v.id !== cursor.key)) {
            state.group.push({
              id: cursor.key,
              name: cursor.value.name,
              cql: cursor.value.cql,
              second: cursor.value.second,
              keyList: JSON.parse(cursor.value.keyList),
              isStart: false
            })
          }
          cursor.continue()
        } else {
        }
      }
    }
    const onAddGroup = () => {
      state.showGroupDialog = true
      state.groupForm = {}
    }
    const onSaveGroup = () => {
      ref_groupForm.value.submit().then(() => {
        if (!state.groupForm.id) {
          const obj = {
            name: state.groupForm.name,
            second: state.groupForm.second,
            cql: state.groupForm.cql,
            keyList: JSON.stringify([])
          }
          const re = state.DB.transaction([state.ObjectStore], 'readwrite').objectStore(state.ObjectStore).add(obj)
          re.onsuccess = e => {
            ElMessage.success('添加成功！')
            state.showGroupDialog = false
            init()
          }
          re.onerror = e => {
            ElMessage.error('添加失败！')
          }
        } else {
          const obj = {
            name: state.groupForm.name,
            second: state.groupForm.second,
            cql: state.groupForm.cql,
            keyList: JSON.stringify(state.groupForm.keyList.map(v => {
              return {
                key: v.key
              }
            }))
          }
          const re = state.DB.transaction([state.ObjectStore], 'readwrite').objectStore(state.ObjectStore).put(obj, state.groupForm.id)
          re.onsuccess = e => {
            ElMessage.success('更新成功！')
            state.group.forEach(v => {
              if (v.id === state.groupForm.id) {
                v = state.groupForm
              }
            })
            state.showGroupDialog = false
          }
          re.onerror = e => {
            ElMessage.error('更新失败！')
          }
        }
      })
    }
    const onAddKey = (group) => {
      state.keyForm = {
        group: group
      }
      state.showKeyDialog = true
    }
    const onSaveKey = () => {
      ref_keyForm.value.submit().then(() => {
        const kList = [...state.keyForm.group.keyList.map(v => {
          const o = {key: v.key}
          return o
        }), {key: state.keyForm.key}]
        const obj = {
          name: state.keyForm.group.name,
          second: state.keyForm.group.second,
          cql: state.keyForm.group.cql,
          keyList: JSON.stringify(kList)
        }
        const re = state.DB.transaction([state.ObjectStore], 'readwrite').objectStore(state.ObjectStore).put(obj, state.keyForm.group.id)
        re.onsuccess = e => {
          ElMessage.success('更新成功！')
          state.group.forEach(v => {
            if (v.id === state.keyForm.group.id) {
              v.keyList = JSON.parse(JSON.stringify(kList))
            }
          })
          state.showKeyDialog = false
        }
        re.onerror = e => {
          ElMessage.error('更新失败！')
        }
      })
    }
    const onStartKey = (group) => {
      group.isStart = true
      const handle = () => {
        group.keyList.forEach(v => {
          let url = `/${store.state.app.apiProxy.rhFindShipApi}/geomesa/queryFusionShip/?cql=`;
          url += encodeURIComponent(group.cql.split('{KEY}').join(v.key))
          axios.get(url).then(res => {
            if (res.data.data?.length > 0) {
              v.online = true
              if (v.apiData) {
                v.apiData = [...v.apiData, res.data.data[0]]
              } else {
                v.apiData = [res.data.data[0]]
              }
              setKeyMap(v, v.apiData[v.apiData.length - 1])
            } else {
              v.online = false
              if (v.apiData) {
                v.apiData = [...v.apiData, {}]
              } else {
                v.apiData = [{}]
              }
            }
          })
        })
      }
      handle()
      group.interval = setInterval(() => {
        handle()
      }, 1000 * group.second)
    }
    const onStopKey = (group) => {
      group.isStart = false
      clearInterval(group.interval)
      group.interval = null
      group.keyList?.forEach(v => {
        v.apiData = []
      })
    }
    const setKeyMap = (key, data) => {
      if (key.MAP) {
        that.$easyMap.initShape({
          map: key.MAP,
          layerName: "MAP",
          layerZIndex: 9,
          list: [
            {
              easyMapParams: {
                id: new Date().getTime(),
                position: data.location,
                normalStyle: [
                  new style.Style({
                    image: new style.Circle({
                      radius: 5,
                      fill: new style.Fill({
                        color: 'red',
                      }),
                    }),
                  })
                ]
              }
            }
          ]
        });
        key.MAP.getView().animate({
          center: that.$easyMap.formatPosition.wptTcpt(data.location)
        })
      }
    }
    const initKeyMap = (map, key) => {
      key.MAP = map
      if (key.apiData?.length > 0) {
        const data = key.apiData[key.apiData.length - 1]
        setKeyMap(key, data)
      }
    }
    const onDelGroup = (group) => {
      ElMessageBox.confirm(`是否删除分组：${group.name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const re = state.DB.transaction([state.ObjectStore], 'readwrite').objectStore(state.ObjectStore).delete(group.id)
        re.onsuccess = e => {
          ElMessage.success('删除成功！')
          state.group.forEach((v, i) => {
            if (v.id === group.id) {
              state.group.splice(i, 1)
            }
          })
        }
        re.onerror = e => {
          ElMessage.error('更新失败！')
        }
      })
    }
    const onEditGroup = (group) => {
      console.log(group)
      state.groupForm = group
      state.showGroupDialog = true
    }
    const onDelKey = (group, key) => {
      ElMessageBox.confirm(`是否删除KEY：${key.key}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        group.keyList.forEach((v, i) => {
          if (v.key === key.key) {
            group.keyList.splice(i, 1)
          }
        })
        const obj = {
          name: group.name,
          second: group.second,
          cql: group.cql,
          keyList: JSON.stringify(group.keyList.map(v => {
            return {key: v.key}
          }))
        }
        const re = state.DB.transaction([state.ObjectStore], 'readwrite').objectStore(state.ObjectStore).put(obj, group.id)
        re.onsuccess = e => {
          ElMessage.success('更新成功！')
        }
        re.onerror = e => {
          ElMessage.error('更新失败！')
        }
      })
    }
    onMounted(() => {
    })
    return {
      ...toRefs(state),
      ref_groupForm,
      ref_keyForm,
      onAddGroup,
      onSaveGroup,
      onAddKey,
      onSaveKey,
      onStartKey,
      onStopKey,
      initKeyMap,
      onEditGroup,
      onDelGroup,
      onDelKey
    }
  },
})
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .main-head {

  }
  .main-content {
    flex: 1;
    overflow: auto;
    .key-content {
      width: 100%;
      height: 140px;
      display: flex;
      .key-position {
        width: 200px;
        height: 100%;
        :deep(.easy-map-ol) {
          .easy-map_ol-default-mouse-position, .easy-map_ol-default-zoom, .easy-map_ol-default-scaleLine {
            display: none;
          }
        }
      }
      .key-heart {
        flex: 1;
      }
    }
  }
}
</style>
