import { store } from '@/store'
import { defineStore } from 'pinia'
import { getTunnelDetail, getTunnelCameras, getEnableList } from '@/api/system'
import tunnelConfigs from '@/config/tunnel'

import {
  ROAD_MARK_TYPES,
  ROAD_LINE_TYPES,
  FACILITY_TYPES,
  EQUIPMENT_TYPES,
  EQUIPMENT_TUNNEL
} from '@/config/dict'

const getFormates = (makerlines, type) => {

  return makerlines.filter(item => item.type === type).map(item => {
    return item.mileList.map(inTerm => {

      const { mileStart, mileEnd } = inTerm

      const temp = {
        start: +mileStart,
        end: +mileEnd,
      }

      if (item.type === 'type_01') {
        temp.type = item.markerlineType === 'line_01' ? 'dash' : 'solid'
      }

      if (item.type === 'type_03') {
        temp.lane = 1
      }

      return temp
      
      
    })
  }).flat()
}

const cameraFormate = (cameras, direction, tunnel) => {

  return cameras.filter(item => {
    return tunnel.start <= item.mileStart && tunnel.end >= item.mileStart && item.cameraIndexCode
  }).map(item => {

    const num = item.mileStart
    
    const pileNumber = 'K' + (num - (num % 1000)) / 1000 + '+' + ('000' + num % 1000).slice(String(num % 1000).length)

    const distance = direction ? num - tunnel.start : tunnel.end - num
    const section = (distance - distance % tunnelConfigs.perSection) / tunnelConfigs.perSection + (distance % tunnelConfigs.perSection ? 1 : 0)
    // const section = (distance - distance % 300) / 300 + (distance % 300 ? 1 : 0)

    return {
      ...item,
      cameraIndexCode: item.cameraIndexCode,
      equipmentStation: +item.mileStart,
      pileNumber,
      section,
      distance: num - tunnel.start
    }
  }).sort((a, b) => a.distance - b.distance)

}

const sectionsCompute = (miles, section) => {

  const leftMiles = miles % section
  const completeSections = (miles - leftMiles) / section

  return (new Array(completeSections + (leftMiles > 0 ? 1 : 0))).fill(null).map((_, x) => {
    return {
      grow: x < completeSections ? 1 : leftMiles / section
    }
  })

}

interface TunnelInfo {
  tunnelId: string,
  init: boolean,
  setting: boolean,
  pmsStore: any,
  tunnel_01: {
    name: string,
    directionName: string,
    lines: any[],
    cameras: any[],
    packingLot: any[],
    roadArrows: any[],
    sections: any[],
    long: string,
    start: string,
    end: string,
    cameraSelected: any[]
  },
  tunnel_02: {
    name: string,
    directionName: string,
    lines: any[],
    cameras: any[],
    packingLot: any[],
    roadArrows: any[],
    sections: any[],
    long: string,
    start: string,
    end: string,
    cameraSelected: any[]
  },
  facilities: any[]
}

export const useTunnelStore = defineStore('tunnel', {

  state: (): TunnelInfo => ({
    tunnelId: '',
    init: false,
    setting: false,
    pmsStore: null,
    tunnel_01: {
      id: '',
      name: '',
      directionName: '',
      direct: '',
      lines: [],
      cameras: [],
      packingLot: [],
      roadArrows: [],
      sections: [],
      start: '',
      end: '',
      long: '',
      cameraSelected: [2, 10, 19, 27, 36]
    },
    tunnel_02: {
      id: '',
      name: '',
      directionName: '',
      direct: '',
      lines: [],
      cameras: [],
      packingLot: [],
      roadArrows: [],
      sections: [],
      start: '',
      end: '',
      long: '',
      cameraSelected: [35, 36, 37, 38, 39]
    },
    faclities: []
  }),

  getters: {

    getUpTunnel () {
      return this.tunnel_01
    },

    getDownTunnel () {
      return this.tunnel_02
    },

    getFacilities () {
      return this.faclities
    },

    getTunnelId () {
      return this.tunnelId
    }
  },

  actions: {

    async setCameras () {

      // console.log(this.tunnel_01.direct)

      // const res = await Promise.all([
      //   getTunnelCameras({ holdId: this.tunnel_01.id, deviceType: 'CAM' }),
      //   getTunnelCameras({ holdId: this.tunnel_02.id, deviceType: 'CAM' })
      // ])

      const res = await getTunnelCameras({ deviceType: 'CAM' })

      const useCameras = res.filter(item => !item.deviceName.includes('新洞'))

      // console.log(res)

      this.tunnel_01.cameras = cameraFormate(useCameras.filter(item => item.directionUpdown === '100700'), 0, this.tunnel_01)
      this.tunnel_02.cameras = cameraFormate(useCameras.filter(item => item.directionUpdown === '100701'), 1, this.tunnel_02)

      // console.log(res.filter(item => item.directionUpdown === '100700'))
      // console.log('cameras: ', this.tunnel_01.cameras)

    },

    async setTunnel (id) {

      const { tunnelBase, tunnelHoles, tunnelPassages } = await getTunnelDetail({ id })

      // console.log(tunnelHoles)

      if (tunnelHoles[0]) {
        this.tunnel_01.id = tunnelHoles[0].id
        this.tunnel_01.directionName = tunnelHoles[0].directionName
        this.tunnel_01.direct = tunnelHoles[0].directionUpdown

        this.tunnel_01.lines = getFormates(tunnelHoles[0].makerlines, 'type_01') // 虚实线
        this.tunnel_01.packingLot = getFormates(tunnelHoles[0].makerlines, 'type_02') // 停车带
        this.tunnel_01.roadArrows = getFormates(tunnelHoles[0].makerlines, 'type_03') // 方向标
        // this.tunnel_01.sections = sectionsCompute(+tunnelHoles[0].length, 300) // 段面计算
        this.tunnel_01.sections = sectionsCompute(+tunnelHoles[0].length, 100) // 段面计算

        this.tunnel_01.start = +tunnelHoles[0].mileStart
        this.tunnel_01.end = +tunnelHoles[0].mileEnd
        this.tunnel_01.long = +tunnelHoles[0].length
      }

      // console.log('-----------------------')
      // console.log(this.tunnel_01.lines)
      // console.log('-----------------------')

      if (tunnelHoles[1]) {
        this.tunnel_02.id = tunnelHoles[1].id
        this.tunnel_02.directionName = tunnelHoles[1].directionName
        this.tunnel_02.direct = tunnelHoles[1].directionUpdown

        this.tunnel_02.lines = getFormates(tunnelHoles[1].makerlines, 'type_01') // 虚实线
        this.tunnel_02.packingLot = getFormates(tunnelHoles[1].makerlines, 'type_02') // 停车带
        this.tunnel_02.roadArrows = getFormates(tunnelHoles[1].makerlines, 'type_03') // 方向标
        // this.tunnel_02.sections = sectionsCompute(+tunnelHoles[1].length, 300) // 段面计算
        this.tunnel_02.sections = sectionsCompute(+tunnelHoles[1].length, 100) // 段面计算

        this.tunnel_02.start = +tunnelHoles[1].mileStart
        this.tunnel_02.end = +tunnelHoles[1].mileEnd
        this.tunnel_02.long = +tunnelHoles[1].length
      }

      // this.tunnel_02.name = res.facilityName
      // this.tunnel_02.directionName = res.downlinkRoad.uplinkDirection,
      // this.tunnel_02.lines = getFormates(res.downlinkRoad, 'x0') // 虚实线
      // this.tunnel_02.packingLot = getFormates(res.downlinkRoad, 'x1') // 停车带
      // this.tunnel_02.roadArrows = getFormates(res.downlinkRoad, 'x2') // 方向标
      // this.tunnel_02.sections = sectionsCompute(+res.downlinkRoad.tunnelLength, 300) // 段面计算
      // this.tunnel_02.start = +res.downlinkRoad.startStation
      // this.tunnel_02.end = +res.downlinkRoad.endStation
      // this.tunnel_02.long = +res.downlinkRoad.tunnelLength

      // console.log('tunnelPassages: ', tunnelPassages)

      this.faclities = tunnelPassages.map(item => {

        const { leftHole, rightHole, type, width } = item
        const classMap = {
          x0: 'man-cross',
          x1: 'car-cross'
        }

        return {
          leftStart: +leftHole,
          rightStart: +rightHole,
          width: +width,
          type: classMap[type]
        }
        
      })

    },
    

    // d08071ebf16f0047ee5ff770bff1752f
    async tunnelInit (id = '35c9851e-6bd1-11ee-914b-3cd2e55ec834', reset?) {

      if ((!this.init || reset) && !this.setting) {

        let resolve = null
        
        this.pmsStore = new Promise(e => {
          resolve = e
        })

        this.setting = true
        
        const res = await getEnableList({
          deptId: id
        })

        if (res[0]) {
          id = res[0].id
        }

        this.tunnelId = id

        await this.setTunnel(id)
        await this.setCameras()

        this.init = true
        this.setting = false

        resolve(true)
        this.pmsStore = null
      }

    },

    async waitTunnel () {

      if (this.init) {
        return true
      }

      if (this.pmsStore) {
        await this.pmsStore
      } else {
        await this.tunnelInit()
      }
      
      return true

    }

  }

})

export const useTunnelStoreWithOut = () => {
  return useTunnelStore(store)
}