/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<!--渠化绘制功能-->
<template>
  <div class="custom-cross" v-if="visible">
    <ImportDialog ref="importDialog" @loadSvgString="loadSvgString" @loadMapSize="loadMapSize" />
    <Messagebox :visible="canclesettingvisible" :text="$t('openatccomponents.channelizationmap.canclesetting')" @cancle="cancleSetting" @ok="completeSetting"/>
    <div class="custom-main" ref="custommain">
      <div class="custom-group drawPanelAnimation" ref="customGroup">
        <!-- 绘制功能 -->
        <div class="draw-function">
          <div class="again-import">
            <el-dropdown @command="handleChangeCrossShapes">
              <el-button type="primary" class="cross-shapes-btn">
                {{$t('openatccomponents.channelizationmap.importcrosspicture')}}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="101">{{$t('openatccomponents.importTemp.crossShapes.crossroads')}}</el-dropdown-item>
                <el-dropdown-item command="100">{{$t('openatccomponents.importTemp.crossShapes.tjunction')}}</el-dropdown-item>
                <el-dropdown-item command="103">{{$t('openatccomponents.importTemp.crossShapes.rampintersection2')}}</el-dropdown-item>
                <el-dropdown-item command="104">{{$t('openatccomponents.importTemp.crossShapes.pedestriancrossing2')}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              class="again-import-btn"
              type="primary"
              :disabled="!isSeletable"
              @click="clickOpen"
            >{{$t('openatccomponents.channelizationmap.againimport')}}</el-button>
             <el-tooltip
              :content="!isLockedCrossMap ? $t('openatccomponents.channelizationmap.lockMap') : $t('openatccomponents.channelizationmap.unlockMap')"
              placement="bottom"
              effect="dark"
            >
              <i class="lock-map el-icon-unlock" v-if="!isLockedCrossMap" @click="handleLockCrossMap()"></i>
              <i class="lock-map el-icon-lock" v-if="isLockedCrossMap" @click="handleLockCrossMap()"></i>
            </el-tooltip>
          </div>

          <div class="draw-to-sketchpad">
            <div class="drawtip">{{$t('openatccomponents.channelizationmap.drawtips')}}</div>
            <div class="draw-operation">
              <!-- <el-button
                type="primary"
                :disabled="!isSeletable"
                @click="addText"
              >添加text</el-button>-->
              <el-button
                v-for="editbtn in editBtnGroup"
                :key="editbtn.type"
                class="edit-icon-btn"
                @click="handleAddIcon(editbtn)"
              >
                <LaneIconSvg :laneicon="editbtn"/>
                <div
                  class="btn-label"
                  :class="{'highlightColor': editbtn.active === true, 'defaultColor': editbtn.active === false}"
                >{{editbtn.label}}</div>
              </el-button>
            </div>
          </div>
        </div>
        <!-- 画板区域 -->
        <div class="sketchpad-area" id="sketchpadgroup" ref="sketchpadgroup">
            <ChannelizationElements
              id="channelizationElements"
              :allitem="allitem"
              :CrossMapVisible="CrossMapVisible"
              :CrossMapData="CrossMapData"
              :isSeletable="isSeletable"
              :pointchange="pointchange"
              @changeCrossMap="changeCrossMap"
              :Motorways="Motorways"
              :curChooseIconIndex="curChooseIconIndex"
              @changeMotorwayItem="changeMotorwayItem"
              @handleSelectIcon="handleSelectIcon"
              :Countdown="Countdown"
              :CountdownList="phaseCountdownMock"
              @changeTimeItem="changeTimeItem"
              :Pedwalk="Pedwalk"
              @changePedItem="changePedItem"
              :Detector="Detector"
              @changeDetectorItem="changeDetectorItem"
              :DetectorChart="DetectorChart"
              :CurChooseIcon="curChooseIcon"
              @changeDetectorChartItem="changeDetectorChartItem"
              :isLockedCrossMap="isLockedCrossMap"
            />
        </div>
        <div class="draw-end-function">
          <el-button type="primary" @click="handleReset()">{{$t('openatccomponents.button.reset')}}</el-button>
          <!-- <el-button type="primary" @click="cancledraw()">{{$t('openatccomponents.button.Cancel')}}</el-button> -->
          <el-button type="primary" @click="savedraw()">{{$t('openatccomponents.button.save')}}</el-button>
          <el-button type="primary" @click="importFromFile()">{{$t('openatccomponents.main.import')}}</el-button>
          <el-button type="primary" @click="exportToFile()">{{$t('openatccomponents.channelizationmap.exportFile')}}</el-button>
          <el-switch
            v-model="isDefaultShowQuhua"
            :active-text="$t('openatccomponents.channelizationmap.defaultShowQuhua')">
          </el-switch>
        </div>
      </div>
      <div class="custom-edit" ref="customEdit">
        <LaneEditPanel
          :Data="curChooseIcon"
          :choosedirections="curChooseIcon.direction"
          :Motorways="Motorways"
          @handleChooseDire="handleChooseDire"
          @handleChoosePed="handleChoosePed"
          @deleteItem="deleteItem"
          @cloneItem="cloneItem"
          @changeIconDataByType="changeIconDataByType"
          @handleDisassociatePhase="handleDisassociatePhase"
        />
      </div>
    </div>
    <!-- <el-row>
      <div class="phase-table">
        <PhaseTable
          :customlist="customlist"
          @changeText="changeText"
          @deleteItem="deleteItem"
          @changeMotorwayItem="changeMotorwayItem"
          @changeIconDataByType="changeIconDataByType"
        />
      </div>
    </el-row> -->
    <!-- 从文件导入弹窗 -->
    <el-dialog
      :title="$t('openatccomponents.main.tip')"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <input
        type="file"
        id="file"
      />
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">{{$t('openatccomponents.common.cancel')}}</el-button>
        <el-button
          type="primary"
          @click="readAsText"
        >{{$t('openatccomponents.common.confirm')}}</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
import ChannelizationElements from './channelizationElements'

import LaneEditPanel from './laneEditPanel'

import PhaseTable from './table'
import PhaseDataModel from './utils/phaseDataModel.js'
import LaneIconSvg from './iconSvg/laneIcon'

import ImportDialog from './importDialog'
import Messagebox from '../../MessageBox/index'

import { mapState } from 'vuex'

import { saveChannelizatonChart } from '../../../../api/cross'
import { getMessageByCode } from '../../../../utils/responseMessage.js'

import axios from 'axios'

export default {
  name: 'draw-channelization',
  components: {
    Messagebox,
    ImportDialog,
    ChannelizationElements,
    PhaseTable,
    LaneIconSvg,
    LaneEditPanel
  },
  computed: {
    ...mapState({
      phaseList: state => state.globalParam.tscParam.phaseList
    })
  },
  props: {
    loadedChannelizatonData: {
      type: Object
    },
    AgentId: {
      type: String,
      default: '0'
    }
  },
  watch: {
    AgentId: {
      handler: function (val) {
        // 平台设备切换时，清空上一个渠化配置
        this.handleReset()
      },
      deep: true
    },
    loadedChannelizatonData: {
      handler: function (val) {
        // 平台设备切换时，重载当前路口保存的渠化配置
        this.LoadedChannelizatonData = JSON.parse(JSON.stringify(val))
        this.load('all')
      },
      deep: true
    }
  },
  data () {
    return {
      visible: true,
      canclesettingvisible: false,

      isSeletable: true, // 元素是否可以编辑
      index: 0,
      motorid: 1, // 车道id
      pedid: 1, // 人行道id
      detectorcoilid: 1, // 检测器线圈id（非关联检测器id）
      Motorways: [], // 管理所有自定义机动车图标数据
      customlist: [], // 所有自定义的图标列表
      Texts: [], // 管理所有自定义文字数据
      Pedwalk: [], // 管理所有人行横道
      Detector: [], // 管理所有检测器
      DetectorChart: [], // 管理所有检测器统计图
      motorwayicon: '',
      IconLengh: 33,
      IconWdith: 109,
      textareaW: 200,
      textareaH: 100,
      pedW: 206,
      pedH: 22,
      MapW: 800,
      MapH: 200,
      detectorW: 20,
      detectorH: 20,
      detectorchartW: 70,
      detectorchartH: 100,
      isLockedCrossMap: true, // 底图是否是锁定状态
      CrossMapData: {
        index: -2,
        icontype: 'crossmap',
        x: 400,
        y: 100,
        w: 800,
        h: 200,
        angle: 0,
        svgstr: '',
        imgfilesrc: ''
      }, // 管理底图数据
      allitem: {
        x: 435,
        y: 325,
        w: 870,
        h: 650,
        angle: 0
      },
      countdownW: 140,
      countdownH: 140,
      Countdown: [], // 管理倒计时图标
      phaseCountdownMock: [
        {
          id: 2,
          phaseCountdown: 59,
          phaseCountdownColor: '#fff'
        },
        {
          id: 5,
          phaseCountdown: 32,
          phaseCountdownColor: '#fff'
        }
      ], // 倒计时动态数据模拟
      svgvisible: false,
      pointchange: false, // 控制选中时光标样式
      CrossMapVisible: true, // 控制底图显示隐藏

      curChooseIconIndex: -1, // 底图暂用-2代替，别的图标与递增的index相关
      curChooseIcon: {},
      editBtnGroup: [
        {
          label: this.$t('openatccomponents.channelizationmap.motorway'),
          type: 'motorway',
          active: false,
          width: '16px',
          height: '16px'
        },
        {
          label: this.$t('openatccomponents.channelizationmap.pedcrossing'),
          type: 'pedcrossing',
          active: false,
          width: '16px',
          height: '16px'
        },
        {
          label: this.$t('openatccomponents.channelizationmap.countdown'),
          type: 'countdown',
          active: false,
          width: '16px',
          height: '16px'
        },
        {
          label: this.$t('openatccomponents.channelizationmap.detector'),
          type: 'detector',
          active: false,
          width: '16px',
          height: '16px'
        }
      ],
      AddType: '', // 正在添加的图标类型

      dirNameMap: new Map([
        [1, '直行'],
        [2, '左转'],
        [3, '右转'],
        [4, '掉头']
      ]),
      phaseAssociatedMap: new Map(), // 关联相位Map: key 是相位ID， value 是车道数据包含direction
      dialogVisible: false,
      LoadedChannelizatonData: {}, // 从接口获取到的渠化参数，用于作为加载数据，从文件导入可修改
      isDefaultShowQuhua: true // 控制总览是否默认显示渠化图的开关
    }
  },
  methods: {
    clickOpen () {
      this.$refs.importDialog.clickOpen()
    },

    // 改变鼠标样式
    changeMouse () {
      if (!this.isSeletable) return
      document.getElementById('sketchpadArea').style.cursor =
        'url(resource/pic/icons/magnifier3.cur) 12 12,pointer'
      this.pointchange = true
    },

    // 根据类型，表格编辑后，修改数据策略
    changeIconDataByType (iconObj, changefield) {
      this.curChooseIcon = JSON.parse(JSON.stringify(iconObj))
      // 根据数据类型改变数据
      switch (iconObj.icontype) {
        case 'text':
          this.changeText(iconObj, changefield)
          break
        case 'vehile':
          this.changeMotorwayItem(iconObj, changefield)
          break
        case 'ped':
          this.changePedItem(iconObj, changefield)
          break
        case 'countdown':
          this.changeTimeItem(iconObj, changefield)
          break
        case 'detector':
          this.changeDetectorItem(iconObj, changefield)
          break
        case 'crossmap':
          this.changeCrossMap(iconObj, changefield)
      }
      // console.log('this.customlist', this.customlist)
    },

    // 被删除的相位所关联的车道，解除相位关联
    handleDisassociatePhase (deletePhaseid) {
      for (let i = 0; i < this.Motorways.length; i++) {
        if (this.Motorways[i].phaseid === deletePhaseid) {
          this.Motorways[i].phaseid = undefined
          this.Motorways[i].phaselabel = ''
          this.Motorways[i].phasetype = undefined
        }
      }
      for (let i = 0; i < this.Pedwalk.length; i++) {
        if (this.Pedwalk[i].phaseid === deletePhaseid) {
          this.Pedwalk[i].phaseid = undefined
          this.Pedwalk[i].phaselabel = ''
          this.Pedwalk[i].phasetype = undefined
        }
      }
    },

    // 添加不同类型的车道图标
    handleAddIcon (editbtn) {
      // 按钮及图标高亮效果实现
      this.editBtnGroup = this.editBtnGroup.map(btn => {
        btn.active = false
        return btn
      })
      for (let i = 0; i < this.editBtnGroup.length; i++) {
        if (this.editBtnGroup[i].type === editbtn.type) {
          this.editBtnGroup[i].active = true
        }
      }
      this.changeMouse()
      this.AddType = editbtn.type
    },

    addMotorwayIcon () {
      this.PhaseDataModel = new PhaseDataModel()
      let defaultMotorwayParam = {
        x: this.setLeft,
        y: this.setTop,
        w: this.IconLengh,
        h: this.IconWdith,
        angle: 0
      }
      this.IconLengh = 33
      this.IconWdith = 109
      let Motorwaysitem = {
        index: this.index,
        id: this.motorid,
        keyid: this.motorid, // 后端需要的id，默认指取索引，可修改
        laneid: undefined, // 全息需要车道id
        icontype: 'vehile',
        icondireid: [1], // 前端区分箭头方向的标识
        icondirename: [this.PhaseDataModel.getPhase(1).name],
        lanePosition: 1,
        controltype: 0,
        phasetype: undefined,
        phaseid: undefined,
        phaselabel: '',
        direction: [], // 值为1-16，对应16个方向
        flip: false, // 车道类型是否翻转显示
        ...defaultMotorwayParam
      }
      this.curChooseIconIndex = Motorwaysitem.index
      this.curChooseIcon = JSON.parse(JSON.stringify(Motorwaysitem))
      this.Motorways.push(Motorwaysitem)
      this.customlist.push(Motorwaysitem)
      this.index = this.increaseId(this.customlist, 'index')
      this.motorid = this.increaseId(this.Motorways, 'id')
    },
    changeMotorwayItem (MotorwayItem, fields) {
      this.changeItem(MotorwayItem, fields, this.Motorways)
      this.changeCustomItem(MotorwayItem, fields)
    },

    // 选中图标
    handleSelectIcon (iconobj, isCrossMap) {
      // console.log('选中的图标', iconobj)
      if (isCrossMap === 'crossmap') {
        this.curChooseIconIndex = -2
      } else {
        this.curChooseIconIndex = iconobj.index
      }
      this.curChooseIcon = JSON.parse(JSON.stringify(iconobj))
    },
    // 根据多选的车道，修改车道图标
    handleChooseDire (iconObj) {
      this.curChooseIcon = JSON.parse(JSON.stringify(iconObj))
      let editDirections = iconObj.icondireid
      if (
        this.curChooseIcon.icontype === 'vehile'
      ) {
        this.curChooseIcon.icondireid = editDirections
        this.curChooseIcon.icondirename = editDirections.map(dir =>
          this.dirNameMap.get(dir)
        )
        this.changeMotorwayItem(this.curChooseIcon, [
          'icondireid',
          'icondirename'
        ])
      }
    },

    addPedwalkIcon () {
      let defaulPedParam = {
        x: this.setLeft,
        y: this.setTop,
        w: this.pedW,
        h: this.pedH,
        angle: 0,
        viewbox: [0, 0, 206, 22]
      }
      this.pedW = 206
      this.pedH = 22
      let peditem = {
        index: this.index,
        id: this.pedid,
        keyid: this.pedid, // 后端需要的id，默认指取索引，可修改
        icontype: 'ped',
        iconpedtypeid: 1,
        iconpedposition: 1,
        phasetype: undefined,
        phaseid: undefined,
        phaselabel: '',
        ...defaulPedParam
      }
      this.curChooseIconIndex = peditem.index
      this.curChooseIcon = JSON.parse(JSON.stringify(peditem))
      this.Pedwalk.push(peditem)
      this.customlist.push(peditem)
      this.index = this.increaseId(this.customlist, 'index')
      this.pedid = this.increaseId(this.Pedwalk, 'id')
    },
    changePedItem (PedItem, fields) {
      this.changeItem(PedItem, fields, this.Pedwalk)
      this.changeCustomItem(PedItem, fields)
    },

    handleChoosePed (pediconobj) {
      this.curChooseIcon = JSON.parse(JSON.stringify(pediconobj))
      if (this.curChooseIcon.icontype === 'ped') {
        this.curChooseIcon.iconpedtypeid = pediconobj.iconpedtypeid
        this.curChooseIcon.iconpedposition = pediconobj.iconpedposition
        this.changePedItem(this.curChooseIcon, ['iconpedtypeid', 'iconpedposition'])
      }
      console.log(this.curChooseIcon)
    },

    addTimer () {
      let defaultCountParam = {
        x: this.setLeft,
        y: this.setTop,
        w: this.countdownW,
        h: this.countdownH,
        angle: 0
      }
      this.countdownW = 140
      this.countdownH = 140
      let countdownitem = {
        index: this.index,
        icontype: 'countdown',
        ...defaultCountParam
      }
      this.curChooseIconIndex = countdownitem.index
      this.curChooseIcon = JSON.parse(JSON.stringify(countdownitem))
      this.Countdown.push(countdownitem)
      this.customlist.push(countdownitem)
      this.index = this.increaseId(this.customlist, 'index')
    },
    changeTimeItem (timeItem, fields) {
      this.changeItem(timeItem, fields, this.Countdown)
      this.changeCustomItem(timeItem, fields)
    },

    addAllDetector () {
      // 统计图暂留
      this.addDetector()
      // this.addDetectorChart()
      this.detectorcoilid = this.increaseId(this.Detector, 'id')
    },
    addDetector () {
      let defaultDetectorParam = {
        x: this.setLeft,
        y: this.setTop,
        w: this.detectorW,
        h: this.detectorH,
        angle: 0
      }
      this.detectorW = 20
      this.detectorH = 20
      let detectoritem = {
        index: this.index,
        id: this.detectorcoilid,
        icontype: 'detector',
        detailtype: 'detector',
        detectortype: 1, // 检测器类型： 1 车辆检测器 2 行人检测器
        detectorid: undefined,
        occupancythreshold: 80,
        minflowsaturationthreshold: 30,
        maxflowsaturationthreshold: 70,
        associatedlaneid: '', // 检测器关联的车道索引
        ...defaultDetectorParam
      }
      this.curChooseIconIndex = detectoritem.index
      this.curChooseIcon = JSON.parse(JSON.stringify(detectoritem))
      this.Detector.push(detectoritem)
      this.customlist.push(detectoritem)
      this.index = this.increaseId(this.customlist, 'index')
    },
    changeDetectorItem (detectorItem, fields) {
      this.changeItem(detectorItem, fields, this.Detector)
      this.changeCustomItem(detectorItem, fields)
    },
    addDetectorChart () {
      let defaultDetectorParam = {
        x: this.setLeft,
        y: this.setTop - 100, // 偏移到检测器正上方150
        w: this.detectorchartW,
        h: this.detectorchartH,
        angle: 0
      }
      this.detectorchartW = 70
      this.detectorchartH = 100
      let detectoritem = {
        index: this.index,
        id: this.detectorcoilid,
        icontype: 'detector',
        detailtype: 'detectorChart',
        ...defaultDetectorParam
      }
      this.curChooseIconIndex = detectoritem.index
      this.curChooseIcon = JSON.parse(JSON.stringify(detectoritem))
      this.DetectorChart.push(detectoritem)
      this.customlist.push(detectoritem)
      this.index = this.increaseId(this.customlist, 'index')
    },
    changeDetectorChartItem (detectorItem, fields) {
      this.changeItem(detectorItem, fields, this.DetectorChart)
      this.changeCustomItem(detectorItem, fields)
    },

    // 添加文字
    addText () {
      let defaultTextParam = {
        x: this.textareaW / 2,
        y: this.textareaH / 2,
        w: this.textareaW,
        h: this.textareaH,
        angle: 0
      }
      this.textareaW = 200
      this.textareaH = 100
      let textitem = {
        index: this.index,
        icontype: 'text',
        text: '',
        ...defaultTextParam
      }
      this.Texts.push(textitem)
      this.customlist.push(textitem)
      this.index = this.increaseId(this.customlist, 'index')
    },
    changeText (textobj, fields) {
      this.changeItem(textobj, fields, this.Texts)
      this.changeCustomItem(textobj, fields)
    },

    changeCustomItem (row, fields) {
      this.changeItem(row, fields, this.customlist)
    },
    changeItem (row, fieldarr, data) {
      for (let item of data) {
        if (item.index === row.index) {
          for (let field of fieldarr) {
            item[field] = row[field]
          }
        }
      }
    },
    deleteItem (row) {
      let index = row.index
      // let id = row.id
      this.customlist = this.customlist.filter(ele => ele.index !== index)
      switch (row.icontype) {
        // case 'text':
        //   this.Texts = this.Texts.filter(ele => ele.index !== index)
        //   break
        case 'vehile':
          this.Motorways = this.Motorways.filter(ele => ele.index !== index)
          this.motorid = this.increaseId(this.Motorways, 'id')
          this.deleteLaneAssociatedDetector(row.id)
          break
        case 'ped':
          this.Pedwalk = this.Pedwalk.filter(ele => ele.index !== index)
          this.pedid = this.increaseId(this.Pedwalk, 'id')
          break
        case 'countdown':
          this.Countdown = this.Countdown.filter(ele => ele.index !== index)
          break
        case 'detector':
          this.Detector = this.Detector.filter(ele => ele.index !== index)
          // this.DetectorChart = this.DetectorChart.filter(ele => ele.id !== id)
          this.detectorcoilid = this.increaseId(this.Detector, 'id')
      }
      this.curChooseIconIndex = -1
      this.curChooseIcon = {}
    },
    deleteLaneAssociatedDetector (dellaneid) {
      // 删除关联车道的检测器的历史关联关系
      for (let i = 0; i < this.Detector.length; i++) {
        let curDetc = this.Detector[i]
        if (curDetc.associatedlaneid === dellaneid) {
          curDetc.associatedlaneid = undefined
        }
      }
    },
    cloneItem (row) {
      // 克隆元素
      let cloneObj = {
        ...row,
        index: this.index,
        x: 435,
        y: 325
      }
      switch (row.icontype) {
        case 'vehile':
          cloneObj.id = this.motorid
          this.Motorways.push(cloneObj)
          this.motorid = this.increaseId(this.Motorways, 'id')
          this.customlist.push(cloneObj)
          break
        case 'ped':
          cloneObj.id = this.pedid
          this.Pedwalk.push(cloneObj)
          this.pedid = this.increaseId(this.Pedwalk, 'id')
          this.customlist.push(cloneObj)
          break
        // case 'countdown':
        //   this.Countdown.push(cloneObj)
        //   this.customlist.push(cloneObj)
        //   break
        case 'detector':
          cloneObj.id = this.detectorcoilid
          this.Detector.push(cloneObj)
          this.customlist.push(cloneObj)
          // 同时克隆统计图
          // this.index = this.increaseId(this.customlist, 'index')
          // let curchartobj = JSON.parse(JSON.stringify(this.DetectorChart)).filter(ele => ele.id === row.id)[0]
          // curchartobj.index = this.index
          // curchartobj.id = this.detectorcoilid
          // curchartobj.x = 435
          // curchartobj.y = 325 - 100
          // this.DetectorChart.push(curchartobj)
          // this.customlist.push(curchartobj)
          this.detectorcoilid = this.increaseId(this.Detector, 'id')
      }
      this.curChooseIconIndex = this.index
      this.curChooseIcon = JSON.parse(JSON.stringify(cloneObj))
      this.index = this.increaseId(this.customlist, 'index')
    },

    loadSvgString (type, imgstr) {
      // 加载用户上传的底图svg字符串
      if (type === 'vectorgraph') {
        // 导入矢量图
        // this.getCrossMapViewbox(imgstr)
        this.CrossMapData = {
          ...this.CrossMapData,
          type,
          svgstr: imgstr
        }
      }
      if (type === 'picture') {
        // 导入图片
        this.CrossMapData = {
          ...this.CrossMapData,
          type,
          imgfilesrc: imgstr
        }
      }
    },
    loadMapSize (type, mapsize) {
      this.CrossMapData = {
        ...this.CrossMapData,
        angle: 0,
        x: Math.round(mapsize.width / 2),
        y: Math.round(mapsize.height / 2),
        w: Math.round(mapsize.width),
        h: Math.round(mapsize.height)
      }
      this.MapW = mapsize.width
      this.MapH = mapsize.height
    },

    getCrossMapViewbox (svgstr) {
      // 获取户上传svg的viewBox属性的大小
      let arr = svgstr.split('"')
      let index, viewBox
      for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i].indexOf('viewBox') !== -1) {
          index = i
        }
      }
      if (index) {
        viewBox = arr[index + 1]
      }
      this.MapW = Number(viewBox.split(' ')[2])
      this.MapH = Number(viewBox.split(' ')[3])
    },
    changeCrossMap (mapdata, fields) {
      this.changeItem(mapdata, fields, [this.CrossMapData])
    },

    // 重置
    handleReset () {
      this.customlist = []
      this.Texts = []
      this.Motorways = []
      this.Countdown = []
      this.Pedwalk = []
      this.Detector = []
      this.DetectorChart = []
      // this.CrossMapData = {
      //   index: -2, // 暂定为-2，用于复用图标判断逻辑
      //   icontype: 'crossmap',
      //   x: this.MapW / 2,
      //   y: this.MapH / 2,
      //   w: this.MapW,
      //   h: this.MapH,
      //   angle: 0,
      //   svgstr: '',
      //   imgfilesrc: ''
      // }
      this.index = 0
      this.curChooseIcon = {}
      this.reloadDefaultCrossMap('CrossRoad.svg')
    },
    // 取消
    cancledraw () {
      this.canclesettingvisible = true
    },
    completeSetting () {
      this.canclesettingvisible = false
      this.$router.push('/overview/index')
    },
    cancleSetting () {
      this.canclesettingvisible = false
    },
    handleSaveParams () {
      let temp = {}
      console.log(this.customlist)
      for (const item of this.customlist) {
        if (temp.hasOwnProperty(item.icontype)) {
          temp[item.icontype].push(item)
        } else {
          temp[item.icontype] = [item]
        }
      }
      if (this.CrossMapData.svgstr !== '' || this.CrossMapData.imgfilesrc !== '') {
        temp.crossMap = this.CrossMapData
      }
      return temp
    },
    // 保存
    savedraw () {
      let temp = {}
      temp = {
        ...this.handleSaveParams(),
        isDefaultShowQuhua: this.isDefaultShowQuhua
      }
      this.saveChannelizatonChart(temp)
    },
    // 加载
    load (type) {
      this.curChooseIconIndex = -1
      let savedTemp = JSON.parse(JSON.stringify(this.LoadedChannelizatonData))
      let arr = []
      this.isDefaultShowQuhua = savedTemp.isDefaultShowQuhua
      delete savedTemp.isDefaultShowQuhua
      for (const [key, value] of Object.entries(savedTemp)) {
        if (key === 'vehile') {
          this.Motorways = value
        }
        if (key === 'text') {
          this.Texts = value
        }
        if (key === 'ped') {
          this.Pedwalk = value
        }
        if (key === 'countdown') {
          this.Countdown = value
        }
        if (key === 'detector') {
          this.Detector = value.filter(ele => ele.detailtype === 'detector')
          // this.DetectorChart = value.filter(ele => ele.detailtype === 'detectorChart')
        }
        if (key === 'crossMap') {
          this.CrossMapData = JSON.parse(JSON.stringify(value))
          if (value.icontype === undefined) {
            this.CrossMapData.icontype = 'crossmap'
          }
        } else {
          if (value.length > 1) {
            arr = [...arr, ...value]
          } else {
            arr.push(value[0])
          }
        }
      }
      this.customlist = JSON.parse(JSON.stringify(arr))
      if (this.customlist.length > 0) {
        this.index = this.increaseId(this.customlist, 'index')
      }
      if (this.Motorways.length > 0) {
        this.motorid = this.increaseId(this.Motorways, 'id')
      }
      if (this.Pedwalk.length > 0) {
        this.pedid = this.increaseId(this.Pedwalk, 'id')
      }
      if (this.Detector.length > 0) {
        this.detectorcoilid = this.increaseId(this.Detector, 'id')
      }
    },
    increaseId (arr, field) { // 实现field对应的index或者id, 在arr的基础上寻找最小的
      let List = arr.map(ele => ele[field])
      let i = List.length - 1
      if (i >= 0) {
        for (let j = 1; j <= 200; j++) {
          if (!List.includes(j)) {
            return j
          }
        }
      } else {
        return 1
      }
    },

    exitEdit () {
      this.isSeletable = !this.isSeletable
    },

    resetAddParams () {
      this.AddType = ''
      this.editBtnGroup = this.editBtnGroup.map(btn => {
        btn.active = false
        return btn
      })
    },
    saveChannelizatonChart (ChannelizatonData) {
      // let agentid = getIframdevid()
      let params = {
        agentid: this.AgentId,
        data: ChannelizatonData
      }
      if (ChannelizatonData.crossMap && ChannelizatonData.crossMap.type === 'vectorgraph') {
        ChannelizatonData.crossMap.imgfilesrc = ''
      }
      if (ChannelizatonData.crossMap && ChannelizatonData.crossMap.type === 'picture') {
        ChannelizatonData.crossMap.svgstr = ''
      }
      saveChannelizatonChart(params).then(data => {
        this.$emit('saveCallback', data)
        if (!data.data.success) {
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror)
            }
          } else {
            this.$message.error(parrenterror)
          }
          return
        }
        let msg = this.$t('openatccomponents.common.savesuccess')
        this.$message({
          message: msg,
          type: 'success',
          duration: 1 * 1000
        })
      })
    },
    handleClickSketchpad () {
      // 监听画板区域点击事件，改变图标放置的位置
      let sketchpadArea = document.getElementById('sketchpadArea')
      let _this = this
      sketchpadArea.addEventListener('click', function (e) {
        if (_this.pointchange) {
          document.getElementById('sketchpadArea').style.cursor =
          'url(resource/pic/icons/magnifier3.cur) 12 12,default'
          _this.pointchange = false
          let boundingClientLeft = document.getElementById('channelizationElements').getBoundingClientRect().left
          let boundingClientTop = document.getElementById('channelizationElements').getBoundingClientRect().top
          _this.setLeft = Math.round(e.clientX - boundingClientLeft) // 四舍五入
          _this.setTop = Math.round(e.clientY - boundingClientTop)
          if (_this.AddType === '') return
          switch (_this.AddType) {
            case 'motorway':
              _this.addMotorwayIcon()
              break
            case 'pedcrossing':
              _this.addPedwalkIcon()
              break
            case 'countdown':
              _this.addTimer()
              break
            case 'detector':
              _this.addAllDetector()
          }
          _this.resetAddParams()
        }
      })
    },
    handleLockCrossMap () {
      this.isLockedCrossMap = !this.isLockedCrossMap
      if (!this.isLockedCrossMap) {
        this.curChooseIconIndex = -2
      } else {
        this.curChooseIconIndex = -1
      }
    },
    importFromFile () {
      this.dialogVisible = true
    },
    readAsText () {
      let _this = this
      var file = document.getElementById('file').files[0]
      var reader = new FileReader()
      reader.async = true
      // 将文件以文本形式读入页面
      reader.readAsText(file)
      reader.onload = function (f) {
        setTimeout(() => {
          _this.LoadedChannelizatonData = {}
          _this.handleReset()
          _this.dialogVisible = false
          _this.LoadedChannelizatonData = JSON.parse(this.result)
          _this.load()
          _this.$alert(_this.$t('openatccomponents.channelizationmap.importfilesuccess'), { type: 'success' })
        }, 50)
      }
    },
    async exportToFile () {
      let tscParam = this.handleSaveParams()
      let content = new Blob([JSON.stringify(tscParam)])
      // 生成url对象
      let urlObject = window.URL || window.webkitURL || window
      let url = urlObject.createObjectURL(content)
      // 生成<a></a>DOM元素
      let el = document.createElement('a')
      // 链接赋值
      el.href = url
      el.download = 'ChanelizationParam.json'
      // 必须点击否则不会下载
      el.click()
      // 移除链接释放资源
      urlObject.revokeObjectURL(url)
    },
    handleChangeCrossShapes (shape) {
      switch (shape) {
        case '100':
          this.reloadDefaultCrossMap('TCrossRoad.svg')
          break
        case '101':
          this.reloadDefaultCrossMap('CrossRoad.svg')
          break
        case '103':
          this.reloadDefaultCrossMap('RampRoad.svg')
          break
        case '104':
          this.reloadDefaultCrossMap('PedCrossingRoad.svg')
          break
      }
    },
    reloadDefaultCrossMap (imgname) {
      axios.get(`./img/${imgname}`).then((val) => {
        if (!val.data || val.data === '') return
        this.CrossMapData = {
            index: -2,
            icontype: 'crossmap',
            x: 435,
            y: 325,
            w: 870,
            h: 650,
            angle: 0,
            imgfilesrc: '',
            svgstr: val.data,
            type: 'vectorgraph'
        }
        if (!this.isLockedCrossMap) {
          this.curChooseIconIndex = -1
          this.$nextTick(() => {
            this.curChooseIconIndex = -2
          })
        }
      })
    }
  },
  mounted () {
    this.handleClickSketchpad()
  }
}
</script>

<style lang="css" rel="stylesheet/scss" scoped>
.cross-shapes-btn {
  height: 32PX;
  width: 90PX;
  line-height: 32PX;
  padding: 0;
}
</style>
