<!--
@name: 线路管理-线路展示
@author: 张泽贤
@time: 2022-10-10
@doc: PROLOG_UPCloudSolutionForTMS__v1.2.1_PC+小程序优化版本_1.3.9_v3.doc
-->
<template>
  <p-card class="full-card-panel lineMap">
    <div slot="title" style="display: flex; align-items: center; cursor: pointer">
      <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
      线路地图
    </div>
    <a-space slot="extra" v-show="type !== 'view'">
      <p-button :disabled="spinning" type="primary" @click="onCalculation">计算里程</p-button>
      <p-button :disabled="spinning" type="primary" @click="onSave">保存</p-button>
    </a-space>
    <a-row :gutter="16" style="height: 100%">
      <a-col :span="12" style="height: 100%">
        <div id="dispatched_lineMap" style="height: 100%"></div>
      </a-col>
      <a-col :span="12" class="lineMap-table">
        <p-card style="margin-bottom: 10px" v-for="(item, index) in lineList" :key="index">
          <a-row slot="title">
            <a-col :span="12" :style="'color:' + colorList[index]">分组名称: {{ item.groupName }}</a-col>
            <a-col :span="12" :style="'color:' + colorList[index]">派车单号: {{ item.loadingBillNo }}</a-col>
          </a-row>
          <!-- <div slot="title" :style="'color:' + colorList[index]">线路名称: {{ item.lineName }}</div> -->
          <a-row>
            <a-col :span="6">总货主数: {{ item.cargoOwnerNumber }}</a-col>
            <a-col :span="6">总 单 数: {{ item.shipbillNumber }}单</a-col>
            <a-col :span="6">冷链单数: {{ item.coldShipbillNumber }}单</a-col>
            <a-col :span="6">紧急单数: {{ item.urgentShipbillNumber }}单</a-col>
          </a-row>
          <a-row>
            <a-col :span="6">总提货点数: {{ item.pickupStations }}</a-col>
            <a-col :span="6">总送货点数: {{ item.deliveryStations }}</a-col>
            <a-col :span="6">总站点数: {{ item.totalStations }}</a-col>
            <a-col :span="6">总 件 数: {{ item.totalPcs }}件</a-col>
          </a-row>
          <a-row>
            <a-col :span="6">总重量: {{ item.totalWeight }}kg</a-col>
            <a-col :span="6">总体积: {{ item.totalVolume }}m³</a-col>
            <a-col :span="6">总里程: {{ item.totalMileage }}公里</a-col>
          </a-row>
          <t-table dragle bordered row-key="stationOrder" :scroll="{ x: true, y: 300 }" :data-source="item.loadingBillDetailMapList" :rowSelectType="false" :autoLoad="false" :pagination="false">
            <t-table-column data-index="stationOrder" title="站点顺序" :width="120" />
            <t-table-column data-index="stationTypeName" title="站点类型" :width="120" />
            <t-table-column data-index="code" title="编码" :width="120" />
            <t-table-column data-index="name" title="名称" :width="120" />
            <t-table-column data-index="typeName" title="类型" :width="120" />
            <t-table-column data-index="address" title="详细地址" :width="120" />
            <t-table-column key="operation" title="操作" fixed="right" :width="180" v-if="type !== 'view'">
              <template slot-scope="text, record">
                <a-space>
                  <p-button size="small" type="primary" @click.stop="onUp(record.stationOrder - 1, index)" :disabled="record.stationOrder === 1">上移</p-button>
                  <p-button size="small" type="danger" @click.stop="onDown(record.stationOrder - 1, index)" :disabled="record.stationOrder === item.loadingBillDetailMapList.length">下移</p-button>
                </a-space>
              </template>
            </t-table-column>
          </t-table>
        </p-card>
      </a-col>
    </a-row>
  </p-card>
</template>

<script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>

<script>
import { mapView, mapSave } from '../js/api.js';

export default {
  props: {
    type: {
      type: String,
      default: '',
    },
    selectLineIdList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      spinning: false,
      colorList: [
        '#3366cc',
        '#dc3912',
        '#ff9900',
        '#109618',
        '#990099',
        '#0099c6',
        '#dd4477',
        '#66aa00',
        '#b82e2e',
        '#316395',
        '#994499',
        '#22aa99',
        '#aaaa11',
        '#6633cc',
        '#e67300',
        '#8b0707',
        '#651067',
        '#329262',
        '#5574a6',
        '#3b3eac',
      ],
      myMap: null,
      routeLine: [],
      waybillDialog: false,
      selectLineIdListNoThis: [],
      selectPointData: {},

      lineList: [
        // {
        //   lineId: '10000072',
        //   lineCode: 'xl01',
        //   lineName: '一号显示',
        //   startLineType: null,
        //   startLineCode: 'ck01',
        //   startLineName: '神像仓库',
        //   endLineType: 1,
        //   endLineCode: 'NC001',
        //   endLineName: '南昌仓',
        //   startLineLongitude: 121.471076,
        //   startLineLatitude: 31.270513,
        //   endLineLongitude: 0,
        //   endLineLatitude: 0,
        //   totalMileage: 1066.9,
        //   terminalNumber: 5,
        //   memo: '',
        //   loadingBillDetailMapList: [
        //     {
        //       lineId: '10000072',
        //       lineName: '一号显示',
        //       customerId: '1000000075',
        //       customerCode: 'KH003',
        //       customerName: '神像专用客户',
        //       consigneeId: '1000000076',
        //       consigneeCode: '01',
        //       consigneeName: '收货方一号',
        //       consigneeContact: '1',
        //       consigneePhoneNumber: '1',
        //       consigneeAddress: '西沽街道水竹花园',
        //       consigneeMemo: null,
        //       deliveryOrder: 1,
        //       longitude: 117.156229,
        //       latitude: 39.162221,
        //     },
        //     {
        //       lineId: '10000072',
        //       lineName: '一号显示',
        //       customerId: '1000000049',
        //       customerCode: 'KH002',
        //       customerName: '格力手机',
        //       consigneeId: '1000000058',
        //       consigneeCode: 'SHF002',
        //       consigneeName: '江西南昌分店',
        //       consigneeContact: '1',
        //       consigneePhoneNumber: '1',
        //       consigneeAddress: '3333',
        //       consigneeMemo: null,
        //       deliveryOrder: 2,
        //       longitude: 116.418614,
        //       latitude: 39.908417,
        //     },
        //     {
        //       lineId: '10000072',
        //       lineName: '一号显示',
        //       customerId: '1000000036',
        //       customerCode: 'KH007',
        //       customerName: '格力电器',
        //       consigneeId: '1000000054',
        //       consigneeCode: 'SHF002',
        //       consigneeName: '珠海分部',
        //       consigneeContact: '1',
        //       consigneePhoneNumber: '1',
        //       consigneeAddress: '河北街道001',
        //       consigneeMemo: null,
        //       deliveryOrder: 3,
        //       longitude: 116.43584,
        //       latitude: 39.908839,
        //     },
        //   ],
        //   tmsShipperByMapDTOs: null,
        // },
        // {
        //   lineName: '青浦线',
        //   data2: '',
        //   data3: '',
        //   data4: '',
        //   loadingBillDetailMapList: [
        //     { id: 1, code: '硚口松江分院1', name: '硚口市松江区1', longitude: 116.471105, latitude: 39.992111 },
        //     { id: 2, code: '硚口松江分院2', name: '硚口市松江区2', longitude: 116.472219, latitude: 39.994225 },
        //     { id: 3, code: '硚口松江分院3', name: '硚口市松江区3', longitude: 116.473322, latitude: 39.996339 },
        //     { id: 4, code: '硚口松江分院4', name: '硚口市松江区4', longitude: 116.474432, latitude: 39.998449 },
        //     { id: 5, code: '硚口松江分院5', name: '硚口市松江区5', longitude: 116.475548, latitude: 39.990555 },
        //   ],
        // },
        // {
        //   lineName: '黄浦线',
        //   data2: '',
        //   data3: '',
        //   data4: '',
        //   loadingBillDetailMapList: [
        //     { id: 1, code: '上海松江分院1', name: '上海市松江区1', longitude: 116.498612, latitude: 40.022208 },
        //     { id: 2, code: '上海松江分院2', name: '上海市松江区2', longitude: 116.492849, latitude: 40.031344 },
        //     { id: 3, code: '上海松江分院3', name: '上海市松江区3', longitude: 116.492763, latitude: 40.024772 },
        //     { id: 4, code: '上海松江分院4', name: '上海市松江区4', longitude: 116.488557, latitude: 40.018725 },
        //     { id: 5, code: '上海松江分院5', name: '上海市松江区5', longitude: 116.494394, latitude: 40.017871 },
        //   ],
        // },
      ],
    };
  },
  mounted() {
    // 注册地图
    this.myMap = new AMap.Map('dispatched_lineMap', {
      resizeEnable: true,
      center: [116.397428, 39.90923],
      zoom: 10,
      mapStyle: 'amap://styles/light',
    });

    this.mapView();
  },
  methods: {
    // 返回
    back() {
      this.$emit('mapBack', this.lineList[0]);
    },
    mapUpdate(list) {
      this.lineList = list.map((item) => {
        if (item.loadingBillDetailMapList && item.loadingBillDetailMapList.length) {
          item.loadingBillDetailMapList = item.loadingBillDetailMapList.sort(this.compare('stationOrder'));
          item.loadingBillDetailMapList.forEach((item2, index) => {
            item2.stationOrder = index + 1;
          });
        } else {
          item.loadingBillDetailMapList = [];
        }
        return item;
      });

      console.log(this.lineList);

      this.myMap.clearMap();
      this.initPage();
      this.initPageLine();
    },
    // 画点
    initPage() {
      let _this = this;
      this.lineList.forEach((item, index) => {
        item.loadingBillDetailMapList &&
          item.loadingBillDetailMapList.forEach((item2, index) => {
            let marker;
            if (index === 0 && item2.longitude && item2.latitude) {
              marker = new AMap.Marker({
                position: [item2.longitude, item2.latitude],
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
                map: _this.myMap,
              });
            } else if (index === item.loadingBillDetailMapList.length - 1 && item2.longitude && item2.latitude) {
              marker = new AMap.Marker({
                position: [item2.longitude, item2.latitude],
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
                map: _this.myMap,
              });
            } else if (item2.longitude && item2.latitude) {
              marker = new AMap.Marker({
                position: [item2.longitude, item2.latitude],
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mid.png',
                map: _this.myMap,
              });
            }
            // 点点击事件
            marker.on('click', function () {
              _this.infoWindow(item2, item, index);
            });
          });
      });
    },
    // 点击弹窗
    infoWindow(markerInfo, lineInfo, markerIndex) {
      let infoBody = '<div>线路：' + (markerInfo.lineName || '') + '</div><br/>';
      infoBody += '<div>第' + (markerIndex + 1) + '站(' + markerInfo.stationTypeName + ')</div><br/>';
      infoBody += '<div>发货地：' + (markerInfo.shipperName || '') + '</div><br/>';
      infoBody += '<div>收货方：' + (markerInfo.consigneeUnitName || '') + '</div><br/>';
      infoBody += '<div>收货地址：' + (markerInfo.address || '') + '</div>';

      let infoWindow = new AMap.InfoWindow({
        content: infoBody,
        offset: new AMap.Pixel(0, -31),
      });
      infoWindow.open(this.myMap, [markerInfo.longitude, markerInfo.latitude]);
    },

    // 画线
    initPageLine() {
      let _this = this;
      AMap.plugin(['AMap.Driving'], function () {
        _this.lineList.forEach((item, index) => {
          let driving = new AMap.Driving({
            // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
            policy: AMap.DrivingPolicy.LEAST_TIME,
            // map: _this.myMap,
            // outlineColor: _this.colorList[index],
          });
          let start,
            end,
            wayList = [],
            waypoints = [];
          for (let index1 = 0; index1 < item.loadingBillDetailMapList.length; index1++) {
            const ele = item.loadingBillDetailMapList[index1];
            if (ele.longitude && ele.latitude) {
              wayList.push({ longitude: ele.longitude, latitude: ele.latitude });
            }
          }
          wayList.forEach((ele, index2) => {
            if (index2 === 0) {
              start = new AMap.LngLat(ele.longitude, ele.latitude);
            } else if (index2 == wayList.length - 1) {
              end = new AMap.LngLat(ele.longitude, ele.latitude);
            } else {
              waypoints.push([ele.longitude, ele.latitude]);
            }
          });
          driving.search(start, end, { waypoints }, function (status, result) {
            if (status === 'complete') {
              if (result.routes && result.routes.length) {
                // 绘制第一条路线，也可以按需求绘制其它几条路线
                _this.drawRoute(result.routes[0], index);
                item.totalMileage = parseFloat(_this.BigJs(result.routes[0].distance).div(1000));
              }
            } else {
            }
          });
        });
      });
      // 调整视野达到最佳显示区域
      setTimeout(() => {
        _this.myMap.setFitView();
      }, 1000);
    },
    drawRoute(route, index) {
      var path = this.parseRouteToPath(route);

      var routeLine = new AMap.Polyline({
        path: path,
        isOutline: true,
        showDir: true,
        outlineColor: this.colorList[index % 20],
        // outlineColor: '#ffeeee',
        borderWeight: 2,
        strokeWeight: 5,
        strokeColor: this.colorList[index % 20],
        lineJoin: 'round',
      });

      this.routeLine.push(routeLine);
      routeLine.setMap(this.myMap);
    },
    parseRouteToPath(route) {
      var path = [];

      for (var i = 0, l = route.steps.length; i < l; i++) {
        var step = route.steps[i];

        for (var j = 0, n = step.path.length; j < n; j++) {
          path.push(step.path[j]);
        }
      }

      return path;
    },

    // 计算里程
    onCalculation() {
      this.myMap.clearMap();
      this.initPage();
      this.initPageLine();
    },

    // 保存
    onSave() {
      if (this.type === 'list') {
        this.mapSave();
      } else {
        this.$emit('mapBack', this.lineList[0]);
      }
    },

    // 上移
    onUp(index, arrayIndex) {
      let newArray = this.lineList[arrayIndex].loadingBillDetailMapList.map((item) => {
        return { ...item };
      });
      [newArray[index].stationOrder, newArray[index - 1].stationOrder] = [newArray[index - 1].stationOrder, newArray[index].stationOrder];
      [newArray[index], newArray[index - 1]] = [newArray[index - 1], newArray[index]];
      this.lineList[arrayIndex].loadingBillDetailMapList = newArray;
    },
    // 下移
    onDown(index, arrayIndex) {
      let newArray = this.lineList[arrayIndex].loadingBillDetailMapList.map((item) => {
        return { ...item };
      });
      [newArray[index].stationOrder, newArray[index + 1].stationOrder] = [newArray[index + 1].stationOrder, newArray[index].stationOrder];
      [newArray[index], newArray[index + 1]] = [newArray[index + 1], newArray[index]];
      this.lineList[arrayIndex].loadingBillDetailMapList = newArray;
    },

    // 排序
    compare(p) {
      return function (m, n) {
        var a = m[p];
        var b = n[p];
        return a - b; //升序
      };
    },

    // 移动后更新页面
    mapView() {
      mapView([...this.selectLineIdList])
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.mapUpdate(res.data);
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {});
    },

    // 保存
    mapSave() {
      this.spinning = true;
      mapSave(this.lineList)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.$emit('mapBack');
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
  },
};
</script>

<style lang="less">
.lineMap {
  .lineMap-table {
    height: 100%;
    overflow-y: auto;
  }
}
</style>
