
import { getToken } from '@/utils/auth'
import { ElMessageBox, ElLoading, ElMessage } from 'element-plus'
import { EventSourcePolyfill } from 'event-source-polyfill';
// import {listProfiles,profilesLoad,profilesDel} from '@map/api/profiles.js'
import * as profiles from '@map/api/profiles.js'
import {
  recognitionreload,
  pipelinereload,
  pipelineload,
  sseClose, writeCsv,
  layersList, recognitionload, recognitionList,
  recognUpdate,
  findSkeleton,
  pipelineUpdate
} from '@map/api/layer.js'

import { list, add, del } from '@map/api/layerPoint'
import home from '@map/assets/qdf.png'
import water from '@map/assets/water.png'
import device from '@map/assets/device.png'
import qdf from "@map/assets/qdf.png"
const useMapDataStore = defineStore(
  'mapData',
  {
    state: () => ({
      source:null,
      profilesList: [],
      profilesId: '',
      layerId: '',
      layerName: '',
      secen: '',
      actionList: [], //变更后的特征物数据
      house: [],
      road: [],
      river: [],
      station: [],
      lineArray: [],
      pointArray: [],
      maxPointIndex: '-1',
      setLineStyle: {
        '110': { styleId: '110', width: 1, color: [251, 213, 2, 200], label: '110管径', },
        '200': { styleId: '200', width: 3, color: [144, 238, 145, 200], label: '200管径', },
        '250': { styleId: '250', width: 3, color: [254, 3, 252, 200], label: '250管径', },
        '300': { styleId: '300', width: 4, color: [255, 194, 204, 200], label: '300管径', },
        '400': { styleId: '400', width: 5, color: [128, 2, 127, 200], label: '400管径', },
        '999': { styleId: '999', width: 4, color: [28, 181, 233, 200], label: '其他管径', },
      },
      setPointStyle: {
        'y': { styleId: 'y', size: '10px', color: [223, 131, 2, 255], label: '转接', visible: false, styleVal: '400', jpg: water, width: 10, height: 10, },
        'h': { styleId: 'h', size: '10px', color: [223, 3, 2, 255], label: '房屋', visible: true, styleVal: '200', jpg: home, width: 12, height: 12 },
        'x': { styleId: 'x', size: '14px', color: [7, 253, 253, 255], label: '井', visible: true, styleVal: '400', jpg: water, width: 14, height: 14 },
        's': { styleId: 's', size: '18px', color: [8, 240, 36, 255], label: '设备', visible: true, styleVal: '400', jpg: device, width: 20, height: 20 },
      },
      watertotal: '0',
      showCheck: false,
      checkedLegend: [],
      checkedpoint: [],
      sseData: [],
      clientId: '',
    }),
    actions: {
      getProfilesList(type) {
        return new Promise((resolve, reject) => {
          profiles[type ? type : this.secen + 'listProfiles']({ layersId: this.layerId }).then(res => {
            this.profilesList = res.data
            resolve()
          })

        })
      },

      getMylayerList() {
        return new Promise((resolve, reject) => {
          layersList().then(res => {
            if (res.data.length > 0) {

              this.layerId = res.data[0].id
            }
            resolve(res)
          })

        })

      },
      getSetlineStyle() {
        return new Promise((resolve, reject) => {
          let data = {
            line: this.setLineStyle,
            point: this.setPointStyle
          }
          resolve(data)

        })
      },
      //设置渲染值
      setMapData(override) {

        return new Promise((resolve, reject) => {
          if (override) {
            this.sseConfig('recognition').then(mapData => {
              this.secen = 'recognition'
              this.profilesId = mapData.Road[0].profilesId
              this.house = mapData['House'].map(item => {
                let arr = {
                  isExit: item.extend,
                  ...item,
                  ...item.extend
                }
                delete arr.extend
                return arr
              })

              this.road = mapData['Road'];
              this.river = mapData['River'];
              mapData.Station && (this.station = mapData['Station']);
              this.actionList = [];

              resolve()
            }).catch(err => {
              reject(err)
            })
          } else {
            recognitionload({ layersId: this.layerId, override }).then(res => {
              if (res.data) {
                this.secen = 'recognition'
                let mapData = res.data
                if (mapData) {
                  this.house = mapData['House'].map(item => {
                    let arr = {
                      isExit: item.extend && (item.extend.houseMaterial || item.extend.houseFloors),
                      ...item,
                      ...item.extend
                    }
                    delete arr.extend
                    return arr
                  })
                  this.road = mapData['Road'];
                  this.river = mapData['River'];
                  mapData.Station && (this.station = mapData['Station']);
                  this.actionList = [];
                  resolve()

                } else {
                  ElMessage({ message: '暂无数据，请重新识别', type: 'error' })
                  reject()
                }

              } else {
                ElMessage({ message: res.msg, type: 'error' })
                reject()
              }

            })
          }
        })
      },
      getProfileByLoad(id) {
        return profiles[this.secen + 'profilesLoad'](id)
      },
      setMapByHistry(id) {
        return new Promise(async (resolve, reject) => {

          let res = await this.getProfileByLoad(id)
          if (res.data) {
            this.profilesId = id
            this.secen = 'recognition'
            let mapData = res.data
            if (mapData) {
              this.house = mapData['House'].map(item => {
                let arr = {
                  isExit: item.extend && (item.extend.houseMaterial || item.extend.houseFloors),
                  ...item,
                  ...item.extend
                }
                delete arr.extend
                return arr
              })
              this.road = mapData['Road'];
              this.river = mapData['River'];
              mapData.Station && (this.station = mapData['Station']);
              this.actionList = [];
              resolve()

            } else {
              ElMessage({ message: '暂无数据，请重新识别', type: 'error' })
              reject()
            }

          } else {
            ElMessage({ message: res.msg, type: 'error' })
            reject()
          }



        })

      },
      delProfiles(id) {

        return new Promise((resolve, reject) => {
          if (id == this.profilesId) {
            ElMessage({ message: '当前档案已加载到页面，不可删除', type: 'warning' })
            reject()

          } else {
            ElMessageBox.confirm('是否删除当前项', '提示',
              {
                confirmButtonText: '确定', cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                profiles[this.secen + 'profilesDel'](id).then(res => {


                  if (res.code == 200) {
                    ElMessage({ message: '删除成功', type: 'success' })
                    resolve(id == this.profilesId)
                  } else {
                    ElMessage({ message: res.msg, type: 'error' })
                    reject()
                  }
                })



              }).catch(() => {

                reject()
              });

          }







        })

      },

      //修改特征物数据
      sethouseData(e) {
        console.log(e)
        let houseData = this.house.map(item => {
          if (item.id == e.id) {
            item = e
          }
          return item

        });
        this.house = houseData;
      },
      closeSse(){
        let self = this;
        sseClose(self.clientId).then(res=>{
           self.clientId = ''


        })
      },
      sseConfig(type) {
        let self = this;
        self.sseData = []
        if(self.clientId){
          this.closeSse()
        }

        return new Promise((resolve, reject) => {

          let base = '/map-api';
          let url = `${base}/sse/connect/`;

          self.source = new EventSourcePolyfill(url, {
            heartbeatTimeout: 10000000,
            headers: {
              Authorization: 'Bearer ' + getToken()
            },

          });

          self.source.onopen = function (event) {
            console.log("连接成功", event);

          };

          self.source.onmessage = function (event) {
            // to to something…
            console.log("接收信息", event);
            // console.log(event.data)
            let data = JSON.parse(event.data);

            switch (data.type) {
              case 'clientId': setRecogn(data.data); break;
              case 'text': self.sseData.push(data); break;
              case 'data': setdata(data.data); break;
              case 'error': errordata(data.data); break;
            }
          };
          function setRecogn(clientId) {
            if (!self.clientId) {
              self.clientId = clientId
              if (type == 'recognition') {
                recognitionreload({ layersId: self.layerId, clientId }).then(res=>{

                }).catch(err => {

                  self.closeSse()
                })

              } else {
                pipelinereload({ layersId: self.layerId, clientId })
              }

            }

          }
          function setdata(data) {
            let text = (type == 'recognition' ? '特征物识别' : '布线') + '结束,关闭并刷新？点击确定刷新，点击取消停留当前页面'
            ElMessageBox.confirm(text, '识别提示',
              { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
              self.closeSse()
                resolve(data)

              }).catch(() => {

                reject()
              });
          }
          function errordata(text){
            ElMessageBox.confirm(text, '错误提示',
              { confirmButtonText: '关闭',showCancelButton:false, type: 'warning' }).then(() => {
                   self.clientId=''
              });

          }

          self.source = function (error) {
            // 监听错误
            console.log("错误", error);
            self.clientId = ''
            // reject()
          };
        });


      },
      getType(type, width) {
        let setLineStyle = this.setLineStyle
        return setLineStyle[width]
      },
      returnlineData(mapData) {
        this.secen = 'pipeline'
        let lineArr = []
        let pointArr = []
        this.watertotal = mapData.water
        this.showCheck = true

        let pointSetArr = {};

        this.lineArray = mapData.pipeline.map(element => {
          element.path = element.path


          let leftId = element.startIndex
          let rightId = element.endIndex

          this.maxPointIndex = Math.max(this.maxPointIndex, leftId, rightId)
          if (pointSetArr[leftId]) {
            pointSetArr[leftId].endIndex = element.id
          } else {
            pointSetArr[leftId] = {
              pointId: leftId,
              endIndex: element.id,
              point: [element.path[0][0], element.path[0][1]],
              pointType: element.pointType,
              ...this.setPointStyle[element.pointType]
            }
          }

          if (pointSetArr[rightId]) {
            pointSetArr[rightId].startIndex = element.id
          } else {
            pointSetArr[rightId] = {
              pointId: rightId,
              startIndex: element.id,
              point: [element.path[1][0], element.path[1][1]],
              pointType: element.pointType,
              ...this.setPointStyle[element.pointType]
            }
          }
          return {
            ...element,
            ...this.getType(element, element.diameter)
          }
        });

        mapData.point.map(point => {
          point.point = [point.path[0][0], point.path[0][1]]
          console.log(point.startIndex)
          this.maxPointIndex = Math.max(this.maxPointIndex, point.startIndex)
          point.pointId = point.startIndex
          if (!pointSetArr[point.pointId]) {
            pointSetArr[point.pointId] = {
              ...point,
              startIndex: undefined,
              endIndex: undefined,
              ...this.setPointStyle[point.pointType]
            }
          } else {
            let data = { ...pointSetArr[point.point] }
            pointSetArr[point.pointId] = {
              ...data,
              ...point,
              ...this.setPointStyle[point.pointType]
            }
          }
        })

        let setlineArr = new Set();
        this.pointArray = []
        lineArr.forEach((item) => {
          item.forEach(element => {
            if (!setlineArr.has(element.id)) {
              this.setLineStyle[element.styleId].length++
              setlineArr.add(element.id)
              this.lineArray.push(element)
            }
          });
        })
        console.log(this.maxPointIndex)
        for (let i in pointSetArr) {
          this.pointArray.push(pointSetArr[i])
        }
        this.checkedLegend = []
        for (let i in this.setLineStyle) {
          this.checkedLegend.push(i)
        }

        this.checkedpoint = []
        for (let i in this.setPointStyle) {
          this.checkedpoint.push(i)
        }
      },
      setLineData(override) {
        let self = this;
        this.setMaxPointIndex(0)
        return new Promise((resolve, reject) => {

          if (override) {

            self.sseConfig('pipeline').then(res => {

              this.profilesId = res.pipeline[0].profilesId
              self.returnlineData(res)
              resolve()
            }).catch(data => {

              reject()
            })
          } else {
            pipelineload({ layersId: this.layerId }).then(res => {
              if (res.data) {
                self.returnlineData(res.data)
                resolve()
              } else {
                ElMessage({ message: res.msg, type: 'error' })
                reject()
              }

            }).catch((e) => {
              reject()
            })
          }
        })



      },
      setHisctoryByline(id) {


        return new Promise(async (resolve, reject) => {

          let res = await this.getProfileByLoad(id)
          this.profilesId = id
          if (res.data) {
            this.returnlineData(res.data)
            resolve()
          } else {
            ElMessage({ message: res.msg, type: 'error' })
            reject()
          }
        })
      },
      createcsvFile() {
        return new Promise((resolve, reject) => {
          writeCsv(this.layerId).then(res => {

            resolve()
          })

        })


      },
      //删除某项
      delData(data) {
        let val = data.geometryId

        if (data.action == 2) {
          this.actionList = this.actionList.filter(item => {
            return item.geometryId != data.geometryId
          })
        } else {
          data.action = 0
          data.path = data.path
          data.innerings = data.innerings
          this.actionList.push(data)
        }
        if (val) {
          let type = val.split(':')[0];
          type = type.toUpperCase().toLowerCase();
          this[type] = this[type].filter(res => {
            return res.geometryId != val
          })
        }

      },
      updateRecon(arr, deviceObj) {
        return new Promise((resolve, reject) => {
          let newArr = arr.filter(item => {
            if (item.action == 2) {
              this.actionList.forEach(data => {
                if (data.geometryId == item.geometryId) {
                  data.path = item.path
                  data.extend = {
                    households: data.households,
                    peopleNum: data.peopleNum,
                    houseMaterial: data.houseMaterial,
                    houseFloors: data.houseFloors,
                    area: data.area,
                    inWater: data.inWater,
                    outWater: data.outWater,
                  }
                }

              })
            }
            return item.action == 1 || item.type == 'Station'
          })
          let stationData = []
          if (this.station.length) {
            let deviceData = this.station[0]
            if (deviceObj.action == 0) {
              deviceData.action = 0
            } else {
              //新增
              deviceData.path = deviceObj.path;
              deviceData.action = 1

            }
            stationData.push(deviceData)
          } else {
            if (deviceObj.action != 0) {
              //新增
              deviceObj.action = 2
              stationData.push(deviceObj)
            }

          }
          let data = [...newArr, ...this.actionList, ...stationData]
          if (data.length > 0) {
            let params = {
              data,
              profilesId: this.profilesId
            }
            recognUpdate(params).then(res => {
              ElMessage({ message: res.msg, type: 'success' })
              this.actionList = [];
              this.station = []
              this.profilesId = res.data
              this.setMapByHistry(this.profilesId).then(res => {
                resolve()
              })
            })
          } else {
            ElMessage({ message: '请先编辑特侦物', type: 'warning' })
          }
        })
      },
      setMaxPointIndex(val) {
        if (val) {
          this.maxPointIndex += val
        } else {
          this.maxPointIndex = -1
        }
        return this.maxPointIndex
      },
      addPngStyle(point) {
        return new Promise((resolve, reject) => {
          let { x, y } = point
          let params = {
            "type": "1",
            "point": [x, y],
            "profilesId": this.profilesId
          }
          add(params).then(res => {
            resolve(res.data)
          })
        })
      },
      delPngTyle(id) {
        return new Promise((resolve, reject) => {
          del(id).then(res => {
            resolve()
          })
        })
      },
      getSetpointStyle() {
        return new Promise((resolve, reject) => {
          list({ type: '1', profilesId: this.profilesId }).then(res => {
            resolve({ data: res.data, img: qdf })
          })
        })
      },
      //更新值
      addByTypeData(type, data) {
        data.layersId = this.layerId
        type = type.toUpperCase().toLowerCase();
        this[type].push(data)
        this.actionList.push(data)
        console.log(this[type][this[type].length - 1])
        return this[type][this[type].length - 1]
      },
      //布线数据保存
      saveLine(data) {
        return new Promise((resolve, reject) => {
          data.profilesId = this.profilesId
          pipelineUpdate(data).then(res => {
            ElMessage({ message: '保存成功', type: 'success' })
            this.setHisctoryByline(res.data)
            resolve()
          })
        })
      },
      getfindSkeleton() {
        return new Promise((resolve, reject) => {
          if (this.profilesId) {
            findSkeleton(this.profilesId).then(res => {
              if (res.data) {
                resolve(res)
              } else {
                reject()
              }
            })

          } else {
            ElMessage({ message: '请先选择特征物数据', type: 'warning' })
            reject()
          }


        })

      },

    },
  }
)
export default useMapDataStore
