<!--
@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 || distinguishType !== 1" 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="lineMap" style="height: 100%"></div>
      </a-col>
      <a-col :span="12">
        <p-card class="full-card-panel" style="margin-bottom: 10px" v-for="(item, index) in lineList" :key="index">
          <div slot="title" :style="'color:' + colorList[index]">线路名称: {{ item.lineName }}</div>
          <a-row>
            <a-col :span="12">提货点数: {{ item.pickUpSiteNumber }}</a-col>
            <a-col :span="12">送货点数: {{ item.deliverySiteNumber }}</a-col>
            <a-col :span="12">总 站 数: {{ item.siteDTOs.length }}</a-col>
            <a-col :span="12">总里程数: {{ item.totalMileage }} 千米</a-col>
          </a-row>
          <p-table dragle bordered row-key="siteOrder" :scroll="{ x: true, y: 300 }" :data-source="item.siteDTOs" :rowSelectType="false" :autoLoad="false" :pagination="false" @clickRow="tableClick">
            <p-table-column data-index="siteOrder" title="站点顺序" :width="120" />
            <p-table-column data-index="siteTypeName" title="站点类型" :width="120" />
            <p-table-column data-index="siteCode" title="编码" :width="120" />
            <p-table-column data-index="siteName" title="名称" :width="120" />
            <p-table-column data-index="typeName" title="类型" :width="120" />
            <p-table-column data-index="address" title="详细地址" :width="200" />
            <p-table-column data-index="shipperAgingTime" title="发货时间" :width="200" />
            <p-table-column data-index="consigneeAgingTime" title="到货时间" :width="200" />
            <p-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.siteOrder - 1, index)" :disabled="record.siteOrder === 1">上移</p-button>
                  <p-button size="small" type="danger" @click.stop="onDown(record.siteOrder - 1, index)" :disabled="record.siteOrder === item.siteDTOs.length">下移</p-button>
                  <p-button size="small" type="dashed" @click.stop="onMove(record, item.lineId)" v-show="lineList.length > 1">移动</p-button>
                </a-space>
              </template>
            </p-table-column>
          </p-table>
        </p-card>
      </a-col>
    </a-row>

    <p-search-modal v-bind="lineAttr" @ok="(...args) => onFormBlur('line', ...args)" @cancel="waybillDialog = false" v-show="false" :modalConfig="{ visible: waybillDialog }" />
  </p-card>
</template>

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

<script>
import * as $formItems from '../js/formConfig.js';
import { Move, new_selectMap, new_saveMap } from '../js/api.js';

function iconConfig(obj = {}) {
  return {
    // 图标尺寸
    size: new AMap.Size(28, 36),
    // 图标的取图地址
    image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
    // 图标所用图片大小
    imageSize: new AMap.Size(135, 40),
    // 图标取图偏移量
    ...obj,
  };
}
const startIcon = new AMap.Icon(iconConfig({ imageOffset: new AMap.Pixel(-5, -3) }));
const endIcon = new AMap.Icon(iconConfig({ imageOffset: new AMap.Pixel(-95, -3) }));

export default {
  props: {
    type: {
      type: String,
      default: '',
    },
    distinguishType: {
      // 划分类型
      type: Number,
      default: null,
    },
    waypoint_dataSource: {
      type: Array,
      default: () => [],
    },
    selectLineIdList: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    lineAttr() {
      let lineAttr = $formItems.lineAttr;
      return Object.assign({ remoteData: { lineIds: this.selectLineIdListNoThis } }, lineAttr);
    },
  },
  watch: {
    waypoint_dataSource: {
      handler(val) {
        this.mapUpdate(val);
      },
    },
  },
  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: [],
      $formItems,
      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: '',
        //   siteDTOs: [
        //     {
        //       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: '',
        //   siteDTOs: [
        //     { 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: '',
        //   siteDTOs: [
        //     { 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 },
        //   ],
        // },
        // {
        //   lineId: 1,
        //   lineName: '',
        //   pickUpSiteNumber: 1,
        //   deliverySiteNumber: 1,
        //   totalMileage: '',
        //   siteDTOs: [
        //     { id: 1, siteOrder: 1, siteCode: '110101', siteName: '东城区', siteTypeName: '提货', typeName: '行政区域', _row_count: 1 },
        //     { id: 2, siteOrder: 2, siteCode: '110102', siteName: '西城区', siteTypeName: '送货', typeName: '行政区域', _row_count: 2 },
        //   ],
        // },
      ],

      districtSearch: null,
      zindex: 100,
    };
  },
  mounted() {
    let _this = this;
    // 注册地图
    this.myMap = new AMap.Map('lineMap', {
      resizeEnable: true,
      center: [116.397428, 39.90923],
      zoom: 10,
      mapStyle: 'amap://styles/light',
    });
    AMap.plugin('AMap.DistrictSearch', function () {
      _this.districtSearch = new AMap.DistrictSearch({
        extensions: 'all',
        // 设置查询行政区级别为 区
        level: 'district',
      });
    });
    this.initDistrict();
  },
  methods: {
    // 返回
    back() {
      this.$emit('mapBack', this.lineList[0]);
    },
    mapUpdate(list) {
      this.lineList = list.map((item) => {
        item.siteDTOs = item.siteDTOs.sort(this.compare('siteOrder'));
        item.siteDTOs.forEach((item2, index) => {
          item2.siteOrder = index + 1;
        });
        return item;
      });

      this.myMap.clearMap();
      if (this.distinguishType === 1) {
        this.initPage();
        this.initPageLine();
      } else if (this.distinguishType === 2) {
        this.initDistrict();
      }
    },
    // 画点
    initPage() {
      let _this = this;
      this.lineList.forEach((item, index) => {
        item.siteDTOs.forEach((item2, index2) => {
          console.log(item2.longitude, item2.latitude);
          if (item2.longitude && item2.latitude) {
            if (index2 === 0) {
              item2.marker = new AMap.Marker({
                position: [item2.longitude, item2.latitude],
                icon: startIcon,
                map: _this.myMap,
                offset: new AMap.Pixel(-10, -31),
              });
            } else if (index2 === item.siteDTOs.length - 1) {
              item2.marker = new AMap.Marker({
                position: [item2.longitude, item2.latitude],
                icon: endIcon,
                map: _this.myMap,
                offset: new AMap.Pixel(-10, -31),
              });
            } else {
              item2.marker = new AMap.Marker({
                position: [item2.longitude, item2.latitude],
                content: `<i class="icon-jing">${index2 + 1}</i>`,
                map: _this.myMap,
                offset: new AMap.Pixel(-10, -31),
              });
            }

            // 点点击事件
            item2.marker.on('click', function () {
              _this.infoWindow(item2, index2 + 1);
            });
          }
        });
      });
    },
    // 点击弹窗
    infoWindow(markerInfo, markerIndex) {
      let infoBody = '<div>第' + markerIndex + '站</div><br/>';
      infoBody += '<div>' + (markerInfo.siteTypeName || '') + '</div><br/>';
      infoBody += '<div>编码：' + (markerInfo.siteCode || '') + '</div><br/>';
      infoBody += '<div>名称：' + (markerInfo.siteName || '') + '</div><br/>';
      infoBody += '<div>地址：' + (markerInfo.address || '') + ' km/h</div>';

      let infoWindow = new AMap.InfoWindow({
        content: infoBody,
        offset: new AMap.Pixel(0, -31),
      });
      infoWindow.open(this.myMap, [markerInfo.longitude, markerInfo.latitude]);
      this.myMap.setCenter([markerInfo.longitude, markerInfo.latitude], true);
      this.zindex += 1;
      markerInfo.marker && markerInfo.marker.setzIndex(this.zindex);
    },
    // 画线
    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,
            // showTraffic: false,
            // hideMarkers: true,
            // outlineColor: _this.colorList[index],
          });
          let start,
            end,
            wayList = [],
            waypoints = [];
          for (let index = 0; index < item.siteDTOs.length; index++) {
            const ele = item.siteDTOs[index];
            if (ele.longitude && ele.latitude) {
              wayList.push({ longitude: ele.longitude, latitude: ele.latitude });
            }
          }
          wayList.forEach((ele, index) => {
            if (index === 0) {
              start = new AMap.LngLat(ele.longitude, ele.latitude);
            } else if (index == wayList.length - 1) {
              end = new AMap.LngLat(ele.longitude, ele.latitude);
            } else {
              waypoints.push([ele.longitude, ele.latitude]);
            }
          });
          if (start && end) {
            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));
                }
              }
            });
          }
        });
      });
      // 调整视野达到最佳显示区域
      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.new_saveMap();
      } else {
        this.$emit('mapBack', this.lineList[0]);
      }
    },

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

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

    // 移动
    onMove(record, lineId) {
      this.selectPointData = { ...record };
      let list = [];
      this.selectLineIdList.forEach((item) => {
        if (item !== lineId) {
          list.push(item);
        }
      });
      this.selectLineIdListNoThis = [...list];
      this.waybillDialog = true;
    },

    onFormBlur(name, ...args) {
      if (name === 'line') {
        let lineData = { ...args[2][0] };
        if (this.selectPointData.siteTypeName === '送货' && lineData.distinguishType !== 1) {
          this.$message.error('目标线路的划分类型为行政区域，不能移动');
          return false;
        }
        if (this.selectPointData.siteTypeName === '提货' && lineData.startLineType !== 1) {
          this.$message.error('目标线路的线路起点类型为行政区域，不能移动');
          return false;
        }

        let request = {
          sourceLineMoveSiteVO: { ...this.selectPointData, siteLongitude: this.selectPointData.longitude, siteLatitude: this.selectPointData.latitude, marker: null },
          targetLineCode: lineData.lineCode,
          targetLineId: lineData.lineId,
          targetLineName: lineData.lineName,
        };
        Move(request).then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.waybillDialog = false;
            this.new_selectMap();
          } else {
            this.$exception(res);
          }
        });
      }
    },

    // 移动后更新页面
    new_selectMap() {
      let list = this.selectLineIdList.map((item) => {
        return { lineId: item };
      });
      new_selectMap(list)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.mapUpdate(res.data);
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {});
    },

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

    // 画行政区域
    initDistrict() {
      let _this = this;
      this.lineList.forEach((item) => {
        item.siteDTOs.forEach((item2, index) => {
          if (!item2.siteCode.includes('0000') && !item2.siteCode.includes('00')) {
            _this.districtSearch.search(item2.siteCode, function (status, result) {
              if (status === 'complete') {
                item2.center = result.districtList[0].center;
                _this.getData(result.districtList[0], item2);
              }
            });
          }
        });
      });
      setTimeout(() => {
        _this.myMap.setFitView(); //地图自适应
      }, 1000);
    },
    getData(data, directivesData) {
      let _this = this;
      let bounds = data.boundaries;
      let strokeColor = directivesData.siteTypeName === '提货' ? '#0091ea' : '#F56C6C';
      let fillColor = directivesData.siteTypeName === '提货' ? '#80d8ff' : '#fcd3d3';
      if (bounds) {
        for (var i = 0, l = bounds.length; i < l; i++) {
          var polygon = new AMap.Polygon({
            map: _this.myMap,
            strokeWeight: 1,
            strokeColor: strokeColor,
            fillColor: fillColor,
            fillOpacity: 0.2,
            path: bounds[i],
          });
          // polygons.push(polygon);
        }
        polygon.on('click', (e) => {
          _this.showInfoC([e.lnglat.getLng(), e.lnglat.getLat()], directivesData);
        });
      }
    },
    showInfoC(lnglat, directivesData) {
      let infoBody = '<div>第' + directivesData.siteOrder + '站</div><br/>';
      infoBody += '<div>编码：' + directivesData.siteCode + '</div><br/>';
      infoBody += '<div>地址：' + directivesData.address + '</div><br/>';

      let infoWindow = new AMap.InfoWindow({
        content: infoBody,
        offset: new AMap.Pixel(0, 0),
      });
      infoWindow.open(this.myMap, lnglat);
    },

    // 行点击
    tableClick(event, activeID, rowRecord) {
      if (rowRecord.typeName.includes('行政区')) {
        this.showInfoC([rowRecord.center.lng, rowRecord.center.lat], rowRecord);
      } else {
        this.infoWindow(rowRecord, rowRecord.siteOrder);
      }
    },
  },
};
</script>

<style lang="less">
.icon-jing {
  // width: 32px;
  // height: 46px;
  width: 25px;
  height: 34px;
  display: block;
  text-align: center;
  color: #fff;
  padding-top: 3px;
  font-weight: bold;
  background: url('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png') no-repeat center center;
  background-size: contain;
}
</style>
