<template>
  <div id="editroute" class="app-container">
    <el-collapse v-model="activeNames">
      <el-collapse-item title="（一）基本信息" name="1" >
        <el-form ref="dataForm" :rules="rules" :model="routeForm" label-position="right" label-width="130px" style="padding-top:20px;padding-right: 40px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="路线描述" prop="routeName" >
                <el-input v-model.trim="routeForm.routeName" :disabled="dialogStatus=='detail'" :placeholder="dialogStatus=='detail'?'':'必填'" type="text"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="起点地址">
                <el-input v-model.trim="routeForm.startAddress" :disabled="dialogStatus=='detail'" :placeholder="dialogStatus=='detail'?'':'起点地址'" type="text"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="终点地址">
                <el-input v-model.trim="routeForm.endAddress" :disabled="dialogStatus=='detail'" :placeholder="dialogStatus=='detail'?'':'终点地址'" type="text"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="主要途径道路">
                <el-input v-model.trim="routeForm.mainRoad" :disabled="dialogStatus=='detail'" :placeholder="dialogStatus=='detail'?'':'主要途径道路'" type="text"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开始日期">
                <el-date-picker
                  v-model="routeForm.startDate"
                  :disabled="dialogStatus=='detail'"
                  :placeholder="dialogStatus=='detail'?'':'开始日期'"
                  style="width: 100%"
                  type="date"
                  value-format="yyyy-MM-dd"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="结束日期">
                <el-date-picker
                  v-model="routeForm.endDate"
                  :disabled="dialogStatus=='detail'"
                  :placeholder="dialogStatus=='detail'?'':'结束日期'"
                  style="width: 100%"
                  type="date"
                  value-format="yyyy-MM-dd"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="准行时间段">
                <el-checkbox-group v-model="accessTime">
                  <el-checkbox v-for="time in times" :label="time" :key="time" :disabled="dialogStatus=='detail'" style="width: 90px;line-height: 10px">{{ time }}:00</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model.trim="routeForm.remarks" :disabled="dialogStatus=='detail'" :placeholder="dialogStatus=='detail'?'':'备注'" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align:center">
          <el-button type="primary" style="width: 200px;font-size: 15px;font-weight: bold" @click="saveData">修改路线基本信息</el-button>
        </div>
      </el-collapse-item>
      <el-collapse-item title="（二）关联车辆" name="2">
        <el-tabs v-model="activeTab" style="padding-top: 10px;padding-left: 10px;padding-right: 10px" @tab-click="handleClick">
          <el-tab-pane label="解绑当前车辆" name="first">
            <div v-if="carlist.length>0" class="infinite-list-wrapper" style="overflow:auto;height: 100px;padding-left: 40px;padding-top: 20px">
              <el-checkbox-group v-model="removelist" class="checkbox">
                <el-checkbox v-for="item in carlist" :label="item.id" :key="item.id" style="width: 150px">{{ item.description }}</el-checkbox>
              </el-checkbox-group>
            </div>
            <div v-else style="margin-left: 40px;padding-top: 10px">
              暂无关联车辆
            </div>
            <div v-if="carlist.length>0" style="text-align:center;padding-top: 10px">
              <el-button type="primary" style="width: 200px;font-size: 15px;font-weight: bold" @click="removeCar">解绑车辆</el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane label="增加绑定车辆" name="second">
            <el-form ref="selectForm" :inline="true" :model="listQuery" class="form-container" style="padding-left: 20px">
              <el-form-item class="selectForm-container-item" prop="keywords">
                <el-input v-model.trim="listQuery.description" style="width: 180px" placeholder="车辆描述" clearable/>
              </el-form-item>
              <el-form-item class="selectForm-container-item" prop="keywords">
                <el-input v-model="listQuery.carCode" style="width: 180px" placeholder="车牌号" clearable/>
              </el-form-item>

              <el-form-item class="selectForm-container-item" prop="keywords">
                <el-select v-model="listQuery.carType" style="width: 180px" filterable placeholder="车辆类型" clearable value="" @change="search">
                  <el-option
                    v-for="item in cartypelist"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
              <el-form-item class="selectForm-container-item" prop="keywords">
                <dept-select v-if=" activeTab==='second'" v-model="listQuery.deptId" :dept-show="deptShow" style="width: 180px" placeholder="使用单位" clearable value=""/>
              </el-form-item>
              <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">查 询</el-button>
            </el-form>
            <div class="infinite-list-wrapper" style="overflow:auto;height: 100px;padding-left: 20px">
              <el-checkbox-group v-model="addlist" class="checkbox">
                <el-checkbox v-for="item in list" :label="item.id" :key="item.id" style="width: 150px">{{ item.description }}</el-checkbox>
              </el-checkbox-group>
            </div>
            <div style="text-align:center;padding-top: 10px">
              <el-button type="primary" style="width: 200px;font-size: 15px;font-weight: bold" @click="addCar">增加绑定车辆</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-collapse-item>
      <el-collapse-item title="（三）地图展示" name="3">
        <div id="map">
          <map-view ref="map" @ready="initMap">
            <l-polyline :lat-lngs="pathlist" />
            <l-marker
              v-for="(star,index) in pathlist"
              :icon="index==0?iconStart:index==(pathlist.length-1)?iconEnd:iconMiddle"
              :key="'star'+index"
              :lat-lng="star"
            />
          </map-view>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script>
import { getDictByType } from '@/api/common'
import { updateRouteInfo, listUnbindCar, bindCar, unbindCar, getRouteInfo } from '@/api/sanitation/route'
import DeptSelect from '@/components/DeptSelect'
import MapView from '../mapViews/mapView'
import * as L from 'leaflet'
import { LMarker, LPolyline } from 'vue2-leaflet'
import {getConstant} from '@/utils/routeutils'
import { getPathBounds, getCenterByBounds, getZoomByBounds } from '@/utils/maputils'

export default {
  name: 'EditRoute',
  components: { MapView, DeptSelect, LMarker, LPolyline  },
  data() {
    const routeConstant = getConstant()
    return {
      dialogStatus: 'edit', // 对话框类型：create,update
      activeNames: ['1', '2', '3'],
      activeTab: 'first',
      deptShow: true,
      paramsdata: null,
      routeId: '',
      map: null,
      list: [],
      alarmlist: [],
      cartypelist: [],
      accessTime: [],
      carlist: [],
      addlist: [],
      removelist: [],
      pathlist: [],
      baselayer: [],
      markerlayer: null,
      addCarForm: {
        routeId: '',
        carIds: []
      },
      removeCarForm: {
        routeId: '',
        carIds: []
      },
      listQuery: {
        sys: '1',
        routeId: '',
        description: '',
        carCode: '',
        carType: '',
        deptId: ''
      },
      routeForm: {
        id: '',
        routeName: '',
        alarmType: '',
        alarmDistance: '',
        startAddress: '',
        endAddress: '',
        mainRoad: '',
        startDate: '',
        endDate: '',
        accessTime: '',
        remarks: ''
      }, // 表单
      times: routeConstant.times, // 所有时间列表
      options: routeConstant.timeSelectOptions, // 允许通行时间下拉选项
      rules: {
        routeName: [{ required: true, message: '路线描述不能为空', trigger: ['blur', 'change'] }],
        alarmType: [{ required: true, message: '报警类型必选', trigger: ['blur', 'change'] }],
        alarmDistance: [{ required: true, message: '偏离报警距离不能为空', trigger: ['blur', 'change'] }]
      },
      iconStart: L.icon({
        iconUrl: require('../../assets/icons/start.png'),
        iconSize: [45, 45], // 图片大小
        iconAnchor: [22, 35] // 偏移x,y，针对图片的左上角
      }), // 开始图标
      iconEnd: L.icon({
        iconUrl: require('../../assets/icons/end.png'),
        iconSize: [45, 45], // 图片大小
        iconAnchor: [22, 35] // 偏移x,y，针对图片的左上角
      }), // 结束图标
      iconMiddle: L.divIcon({
        className: 'my-div-icon', // 自定义icon css样式
        iconSize: [15, 15]// 点大小
      }) // 中间图标
    }
  },
  activated() {
    this.initdata()
  },
  mounted() {
    getDictByType('routeAlarmType').then(response => {
      this.alarmlist = response.data
    })
    getDictByType('carType').then(response => {
      this.cartypelist = response.data
    })
    this.initdata()
  },
  methods: {
    // 初始化地图
    initMap() {
      this.map = this.$refs.map.map
    },
    // 初始化基础数据
    initdata() {
      if (this.$route.query) {
        this.routeId = this.$route.query.id
        this.listQuery.routeId = this.$route.query.id
        this.routeForm = {
          id: this.$route.query.id,
          routeName: this.$route.query.routeName,
          alarmType: this.$route.query.alarmType,
          alarmDistance: this.$route.query.alarmDistance,
          startAddress: this.$route.query.startAddress,
          endAddress: this.$route.query.endAddress,
          mainRoad: this.$route.query.mainRoad,
          startDate: this.$route.query.startDate,
          endDate: this.$route.query.endDate,
          accessTime: this.$route.query.accessTime,
          remarks: this.$route.query.remarks
        }
        if (this.routeForm.accessTime.length !== 0) {
          var accesslist = this.routeForm.accessTime.split(',')
          this.accessTime = []
          for (var i = 0; i < accesslist.length; i++) {
            this.accessTime.push(Number(accesslist[i]))
          }
        }
      }
      // 获取路线详情
      getRouteInfo(this.routeId).then(response => {
        this.carlist = response.data.carList// 车辆列表
        this.removelist = []
        for (var i = 0; i < this.carlist.length; i++) {
          this.removelist.push(this.carlist[i].id)
        }
        this.pathlist = []
        for (i = 0; i < response.data.pathList.length; i++) {
          var item = [Number(response.data.pathList[i].startLat), Number(response.data.pathList[i].startLng)]
          this.pathlist.push(item)
          if (i === response.data.pathList.length - 1) {
            item = [Number(response.data.pathList[i].endLat), Number(response.data.pathList[i].endLng)]
            this.pathlist.push(item)
          }
        }
        if (this.pathlist.length !== 0) {
          this.setZoom(this.pathlist)
        }
      })
      this.search()
    },
    // 获取车辆绑定情况
    handleClick() {
      getRouteInfo(this.routeId).then(response => {
        this.carlist = response.data.carList
        this.addlist = []
        this.removelist = []
        for (var i = 0; i < this.carlist.length; i++) {
          this.removelist.push(this.carlist[i].id)
        }
        this.search()
      })
    },
    // 查询未绑定车辆
    search() {
      listUnbindCar(this.listQuery).then(response => {
        this.list = response.data
      })
    },
    // 绑定车辆
    addCar() {
      if (this.addlist.length === 0) {
        this.$message.warning('请至少选择一辆车')
      } else {
        this.addCarForm.routeId = this.routeId
        this.addCarForm.carIds = []
        for (var i = 0; i < this.addlist.length; i++) {
          this.addCarForm.carIds.push(Number(this.addlist[i]))
        }
        bindCar(this.addCarForm).then(response => {
          if (response.code === 200) {
            this.$message.success('绑定车辆信息成功！')
          }
        })
      }
    },
    // 移除车辆
    removeCar() {
      if (this.removelist.length === 0) {
        this.$message.warning('请至少选择一辆车解绑')
      } else {
        this.removeCarForm.routeId = this.routeId
        this.removeCarForm.carIds = []
        for (var i = 0; i < this.removelist.length; i++) {
          this.removeCarForm.carIds.push(Number(this.removelist[i]))
        }
        console.log(this.removeCarForm)
        unbindCar(this.removeCarForm).then(response => {
          if (response.code === 200) {
            this.$message.success('解绑车辆成功！')
            this.handleClick()
          }
        })
      }
    },
    // 修改路线基本信息
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.routeForm.startDate > this.routeForm.endDate) {
            this.$message.warning('请确认输入正确起止时间')
          } else {
            this.routeForm.accessTime = this.accessTime[0]
            for (var i = 1; i < this.accessTime.length; i++) {
              this.routeForm.accessTime += (',' + this.accessTime[i])
            }
            updateRouteInfo(this.routeForm).then(response => {
              if (response.code === 200) {
                this.$message.success('修改规划路线基本信息成功！')
              }
            })
          }
        }
      })
    },
    // 计算并设置地图缩放边界
    setZoom(points) {
      if (points.length > 0) {
        // 计算边界
        const { maxLng, minLng, maxLat, minLat } = getPathBounds(points)
        // 计算中心点
        const { cenLat, cenLng } = getCenterByBounds({ maxLng, minLng, maxLat, minLat })
        // 计算缩放
        const zoom = getZoomByBounds({ maxLng, minLng, maxLat, minLat })
        this.map.setView({ lat: cenLat, lng: cenLng }, zoom)
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  /*#editroute . {*/
    /*font-size: 15px ;*/
    /*font-weight: bold;*/
  /*}*/
  #editroute .el-checkbox__label {
    font-size: 15px ;
    font-weight: bold;
  }
  #editroute .el-form-item {
    margin-bottom: 18px;
  }
  #map {
    width:100%;
    height:50vh;
  }
  .my-div-icon {
    width: 10px;
    height: 10px;
    background-color: orange;
    border-radius: 50%;
  }
</style>
