<!--
@name: 待调度-运单地图
@author: 张泽贤
@time: 2022-04-13
-->
<template>
  <div style="height: 100%">
    <p-card class="full-card-panel waybillMap" v-show="!editType">
      <a-space slot="title">
        <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
        运单地图
        <a-radio-group button-style="solid" v-model="pattern">
          <a-radio-button value="line">线路模式</a-radio-button>
          <a-radio-button value="heat" v-action:heat>热力图模式</a-radio-button>
        </a-radio-group>
      </a-space>
      <a-space slot="extra" v-if="isPacketScheduling">
        <a-dropdown-button type="primary" @click="handleSystemGroupClick">
          {{ defaultGroupName ? '"' + defaultGroupName + '"默认' : '暂无默认分组' }}
          <a-radio-group slot="overlay">
            <a-menu class="dropdown-mini-menu" mode="inline">
              <a-sub-menu key="sub1">
                <span slot="title">分组配置</span>
                <a-menu-item v-for="item in options.GROUP_CONFIG" :key="item.groupName">
                  <a-checkbox :name="item.groupName" @change="handleMenuClick($event, 'sub1')" :checked="groupName === item.groupName"> {{ item.groupName }}</a-checkbox>
                </a-menu-item>
              </a-sub-menu>
              <a-sub-menu key="sub2">
                <span slot="title">类型条件</span>
                <a-menu-item v-for="item in options.GROUP_DISPATCH_NEW" :key="item.value">
                  <a-checkbox :checked="groupDimensionList.includes(item.value)" @change="handleMenuClick($event, 'sub2', item.value)">{{ item.label }}</a-checkbox>
                </a-menu-item>
              </a-sub-menu>
              <a-menu-item style="margin-bottom: 6px; padding-left: 8px">
                <a-space>
                  <a-button @click.stop="settingGroupClick">设置</a-button>
                  <a-button type="primary" @click.stop="onSystemGroup" :disabled="!groupDimensionList.length && !groupName">确定</a-button>
                </a-space>
              </a-menu-item>
            </a-menu>
          </a-radio-group>
        </a-dropdown-button>
      </a-space>
      <a-row :gutter="16" style="height: 100%" v-show="pattern === 'line'">
        <a-col :span="12" style="height: 100%">
          <div id="waybillMap_line" style="height: 100%"></div>
        </a-col>
        <a-col :span="12" class="dis-flex">
          <a-tabs default-active-key="1">
            <a-tab-pane key="1" tab="运单货量">
              <p-form-model :model="form" :label-col="{ span: 18 }" :wrapper-col="{ span: 6 }" :span="12" class="plg-grid-from">
                <a-row>
                  <a-col :span="12">
                    <p-form-model-item label="货主数">{{ form.cargoOwnerQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="运单数量(单)">{{ form.shipbillQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="冷链 运单数量(单)">{{ form.coldChainShipbillQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="紧急、加急 运单数量(单)">{{ form.urgentShipbillQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="收货方数">{{ form.consigneeQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="总提货点数量">{{ form.totalPickUpSiteQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="总配送点数量">{{ form.totalDeliverySiteQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="总站点数量">{{ form.totalSitQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="商品/包裹 总件数">{{ form.totalPieceQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="商品/包裹 总重量">{{ form.totalWeightQty }}</p-form-model-item>
                  </a-col>
                  <a-col :span="12">
                    <p-form-model-item label="商品/包裹 总体积">{{ form.totalVolumeQty }}</p-form-model-item>
                  </a-col>
                </a-row>
              </p-form-model>
            </a-tab-pane>

            <a-tab-pane key="2" tab="线路货量" force-render>
              <div class="line-content">
                <div v-for="(item, index) in lineList" :key="index" :class="['line', selectIndex === index ? 'selected' : '']" @click="lineDataChlick(index)">
                  <p-form-model :model="item" :label-col="{ span: 18 }" :wrapper-col="{ span: 6 }" :span="12" class="plg-grid-from">
                    <a-row>
                      <a-col :span="24">
                        <p-form-model-item label="线路名称" :label-col="{ span: 9 }" :wrapper-col="{ span: 15 }">
                          <div :style="'color:' + item.lineColor">{{ item.lineName }}</div>
                        </p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="货主数">{{ item.cargoOwnerQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="运单数量(单)">{{ item.shipbillQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="冷链 运单数量(单)">{{ item.coldChainShipbillQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="紧急、加急 运单数量(单)">{{ item.urgentShipbillQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="收货方数">{{ item.consigneeQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="总提货点数量">{{ item.totalPickUpSiteQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="总配送点数量">{{ item.totalDeliverySiteQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="总配送点数量">{{ item.totalDeliverySiteQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="总站点数量">{{ item.totalSitQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="商品/包裹 总件数">{{ item.totalPieceQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="商品/包裹 总重量">{{ item.totalWeightQty }}</p-form-model-item>
                      </a-col>
                      <a-col :span="12">
                        <p-form-model-item label="商品/包裹 总体积">{{ item.totalVolumeQty }}</p-form-model-item>
                      </a-col>
                    </a-row>
                  </p-form-model>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-col>
      </a-row>

      <a-row :gutter="16" style="height: 100%" v-show="pattern === 'heat'">
        <a-col :span="24" style="height: 100%">
          <div id="waybillMap_heat" style="height: 100%"></div>
        </a-col>
      </a-row>
    </p-card>

    <!-- 分组调度 -->
    <packetScheduling
      :SELECT_GROUP_CONFIG="SELECT_GROUP_CONFIG"
      :sysList="sysList"
      v-if="editType === 'packetScheduling'"
      :orderList="orderList"
      :mextendedField_list="mextendedField_list"
      :options="options"
      :selectSystemGroup="groupDimensionList"
      :groupDimensionLabel="groupName || groupDimensionLabel"
      @back="editType = ''"
      @updateGroupList="updateGroupList"
    >
    </packetScheduling>

    <settingGroudModal
      :fieldOptions="options.GROUP_DISPATCH_NEW"
      @update="
        (data, name) => {
          options.GROUP_CONFIG = data;
          defaultGroupName = name;
        }
      "
      :visible.sync="visibleSystemGroup"
    />
  </div>
</template>

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

<script>
import packetScheduling from '@/blocks/components/scheduling/packetScheduling/index.vue';
import settingGroudModal from './settingGroudModal';

import { shipbill_map, shipbill_hot_map, sys_group_query } from '../js/api';
import { heatmapData } from '../js/data.js';

import img_song from '@/assets/imgs/img_song.png';
import img_ti from '@/assets/imgs/img_ti.png';
import img_kong from '@/assets/imgs/img_kong.png';

export default {
  components: { packetScheduling, settingGroudModal },
  props: {
    searchData: {
      type: Object,
      default: {},
    },
    options: {
      type: Object,
      default: () => ({}),
    },
    shipbillIdList: {
      type: Array,
      default: () => [],
    },
    orderList: {
      type: Array,
      default: () => [],
    },
    mextendedField_list: {
      type: Array,
      default: () => [],
    },
    isPacketScheduling: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    // 页面权限
    operations() {
      const { currentOperations, currentPageElements } = this.$store.getters;
      const operations = currentOperations.concat(currentPageElements);
      return operations;
    },
  },
  data() {
    return {
      pattern: 'line', // 模式
      selectIndex: -1,
      colorList: [
        '#3366cc',
        '#dc3912',
        '#ff9900',
        '#109618',
        '#990099',
        '#0099c6',
        '#dd4477',
        '#66aa00',
        '#b82e2e',
        '#316395',
        '#994499',
        '#22aa99',
        '#aaaa11',
        '#6633cc',
        '#e67300',
        '#8b0707',
        '#651067',
        '#329262',
        '#5574a6',
        '#3b3eac',
      ],
      colorObj: {},
      myMap_line: null,
      myMap_heat: null,

      SimpleMarker: '',
      SimpleInfoWindow: '',
      pathSimplifierIns: '',
      PathSimplifier: '',

      form: {},

      lineList: [],
      linemapList: [],
      routeLine: [],

      heatmapData,

      // 分组调度
      defaultGroupName: '',
      groupDimensionList: [],
      groupDimensionLabel: '',
      visibleSystemGroup: false,
      groupName: '',
      SELECT_GROUP_CONFIG: null,
      sysList: [],
      editType: '',
    };
  },
  mounted() {
    // 注册地图
    this.myMap_line = new AMap.Map('waybillMap_line', {
      resizeEnable: true,
      center: [116.397428, 39.90923],
      zoom: 10,
      mapStyle: 'amap://styles/light',
    });
    this.shipbill_map();

    if (this.operations.includes('heat')) {
      this.myMap_heat = new AMap.Map('waybillMap_heat', {
        resizeEnable: true,
        center: [116.397428, 39.90923],
        zoom: 5,
        mapStyle: 'amap://styles/light',
      });
      this.shipbill_hot_map();
    }
  },
  methods: {
    // 返回
    back() {
      this.$emit('back');
    },

    // 画点
    initPage(markerInfo, lineInfo, markerIndex) {
      if (markerInfo.longitude && markerInfo.latitude) {
        let _this = this,
          imgUrl;
        if (markerInfo.isLineSite === '0') {
          // 游离点
          imgUrl = img_kong;
        } else if (markerInfo.siteTypeName === '提') {
          // 提
          imgUrl = img_ti;
        } else if (markerInfo.siteTypeName === '送') {
          // 送
          imgUrl = img_song;
        }
        let icon = new AMap.Icon({
          imageSize: [20, 31],
          image: imgUrl,
        });
        let marker = new AMap.Marker({
          position: [markerInfo.longitude, markerInfo.latitude],
          icon,
          map: _this.myMap_line,
          offset: new AMap.Pixel(-10, -31),
        });

        // 点点击事件
        marker.on('click', function () {
          _this.infoWindow(markerInfo, lineInfo, markerIndex);
        });
      }
    },
    // 点击弹窗
    infoWindow(markerInfo, lineInfo, markerIndex) {
      let infoBody = '<div>线路：' + (lineInfo.lineName || '') + '</div><br/>';
      infoBody += '<div>第' + (markerIndex + 1) + '站</div><br/>';
      infoBody += '<div>发货地：' + (markerInfo.branchName || '') + '</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_line, [markerInfo.longitude, markerInfo.latitude]);
    },

    // 画线
    initPageLine(lineData) {
      let lineColor = this.colorObj[lineData.lineId];
      let _this = this;
      AMap.plugin(['AMap.Driving'], function () {
        let driving = new AMap.Driving({
          // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
          policy: AMap.DrivingPolicy.LEAST_TIME,
          // map: _this.myMap_line,
          // outlineColor: _this.colorList[index],
        });
        let start,
          end,
          waypoints = [],
          siteDTOs = [];

        for (let index = 0; index < lineData.siteDTOs.length; index++) {
          const ele = lineData.siteDTOs[index];
          // isLineSite 是否匹配到线路 1是 0否
          if (ele.isLineSite === '1' && ele.latitude && ele.longitude) {
            siteDTOs.push(ele);
          }
        }
        if (siteDTOs.length > 1) {
          for (let index = 0; index < siteDTOs.length; index++) {
            const ele = siteDTOs[index];
            if (ele.longitude && ele.latitude) {
              if (index == 0) {
                start = new AMap.LngLat(ele.longitude, ele.latitude);
              } else if (index == siteDTOs.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], lineColor, lineData);
              }
            } else {
            }
          });
        }
      });
    },
    drawRoute(route, lineColor, lineData) {
      let _this = this;
      var path = this.parseRouteToPath(route);
      var routeLine = new AMap.Polyline({
        path: path,
        isOutline: true,
        showDir: true,
        outlineColor: lineColor,
        borderWeight: 2,
        strokeWeight: 5,
        strokeColor: lineColor,
        lineJoin: 'round',
      });
      this.routeLine.push(routeLine);
      routeLine.setMap(this.myMap_line);
      routeLine.on('click', function () {
        _this.lineClick(lineData);
      });
    },
    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;
    },
    // 线点击
    lineClick(lineData) {
      this.selectIndex = this.lineList.findIndex((item) => item.lineId === lineData.lineId);
      this.mapUpdate();
    },

    // 线路数据点击
    lineDataChlick(index) {
      this.selectIndex = this.selectIndex === index ? -1 : index;
      this.mapUpdate();
    },

    // 地图信息查询
    shipbill_map() {
      shipbill_map(this.searchData).then((res) => {
        if (res.success) {
          // 运单货量统计信息
          this.form = { ...res.data.shipbillQtyDTO };

          // 线路货量统计信息
          this.lineList = res.data.shipbillQtyByLineDTOS.map((item, index) => {
            item.lineColor = this.colorList[index % 20];
            this.colorObj[item.lineId] = item.lineColor;
            return item;
          });

          // 调度前运单地图站点信息
          if (res.data.lineSiteMapDTOS) {
            this.linemapList = [...res.data.lineSiteMapDTOS];
            this.linemapList.forEach((item1) => {
              this.initPageLine(item1);
              item1.siteDTOs.forEach((item2, index2) => {
                this.initPage(item2, item1, index2);
              });
            });
            // 调整视野达到最佳显示区域
            setTimeout(() => {
              this.myMap_line.setFitView();
            }, 2000);
          }
        } else {
          this.$exception(res);
        }
      });
      // 调整视野达到最佳显示区域
      setTimeout(() => {
        this.myMap_line.setFitView();
      }, 2000);
    },

    // 地图信息查询
    shipbill_hot_map() {
      shipbill_hot_map(this.searchData).then((res) => {
        if (res.success) {
          this.heatmapData = res.data.map((item) => {
            return {
              lat: item.lat,
              lng: item.lng,
              count: item.sameSiteNum,
            };
          });
          console.log(this.heatmapData);
          this.heatInit();
        } else {
          this.$exception(res);
        }
      });
    },

    // 地图更新
    mapUpdate() {
      this.myMap_line.clearMap();
      let list = [...this.linemapList];
      if (this.selectIndex > -1) {
        list = [{ ...this.linemapList.find((item) => item.lineId === this.lineList[this.selectIndex].lineId) }];
      }
      if (list[0].lineId) {
        list.forEach((item1) => {
          this.initPageLine(item1);
          item1.siteDTOs.forEach((item2, index2) => {
            this.initPage(item2, item1, index2);
          });
        });
        // 调整视野达到最佳显示区域
        setTimeout(() => {
          this.myMap_line.setFitView();
        }, 1000);
      }
    },

    // 热力图
    heatInit() {
      let heatmap,
        _this = this;
      AMap.plugin(['AMap.HeatMap'], function () {
        //初始化heatmap对象
        heatmap = new AMap.HeatMap(_this.myMap_heat, {
          // radius: 25, //给定半径
          opacity: [0.5, 1],
          // gradient: {
          //   0.5: 'blue',
          //   0.65: 'rgb(117,211,248)',
          //   0.7: 'rgb(0, 255, 0)',
          //   0.9: '#ffea00',
          //   1.0: 'red',
          // },
        });
        //设置数据集：该数据为北京部分“公园”数据
        heatmap.setDataSet({
          data: _this.heatmapData,
          max: 100,
        });
      });

      // 调整视野达到最佳显示区域
      setTimeout(() => {
        this.myMap_heat.setFitView();
      }, 2000);
    },

    // 分组调度
    handleSystemGroupClick() {
      if (this.defaultGroupName) {
        let params = {
          groupDimensionList: [],
          shipbillIdList: this.shipbillIdList,
          groupName: this.defaultGroupName,
        };
        this.sys_group_query(params);
      } else {
        this.visibleSystemGroup = true;
      }
    },
    sys_group_query(params) {
      this.spinning = true;
      sys_group_query({ ...params, ...this.searchData })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.sysList = res.data.groupQueryDTOS;
            this.SELECT_GROUP_CONFIG = res.data.groupCfgDTOS;
            this.onSchedule('packetScheduling');
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },
    handleMenuClick(event, type, value) {
      event.preventDefault();
      event.stopPropagation();
      const { checked, name } = event.target;
      if (type == 'sub1') {
        this.groupDimensionList = [];
        this.groupName = checked ? name : '';
      } else if (type == 'sub2') {
        this.groupName = '';
        if (checked) {
          this.groupDimensionList.push(value);
        } else {
          this.groupDimensionList = this.groupDimensionList.filter((str) => value !== str);
        }
      }
    },
    settingGroupClick() {
      this.visibleSystemGroup = true;
    },
    onSystemGroup() {
      let params = {
        groupDimensionList: this.groupDimensionList,
        shipbillIdList: this.shipbillIdList,
        groupName: this.groupName,
      };
      this.sys_group_query(params);
    },
    onSchedule(editType) {
      let groupDimensionLabelList = [];
      this.options.GROUP_DISPATCH_NEW.forEach((item) => {
        if (this.groupDimensionList.includes(item.value)) {
          groupDimensionLabelList.push(item.label);
        }
      });
      this.groupDimensionLabel = groupDimensionLabelList.join(',');
      this.editType = editType;
    },
    updateGroupList(filterShipbillId) {
      let params = {
        groupDimensionList: this.groupDimensionList,
        shipbillIdList: this.shipbillIdList.filter((id) => !filterShipbillId.includes(id)) || [],
      };

      if (!params.shipbillIdList.length) {
        return (this.sysList = []);
      }
      return sys_group_query(params).then((res) => {
        if (res.success) {
          this.sysList = res.data;
        } else {
          this.$exception(res);
        }
      });
    },
  },
};
</script>

<style lang="less">
.waybillMap {
  .dis-flex {
    height: 100%;
    display: flex;
    flex-direction: column;

    .ant-tabs-content {
      height: 100%;
    }

    .line-content {
      flex: 1;
      overflow-y: auto;
      height: 100%;

      .line {
        background: #eee;
        margin: 10px 0;
        list-style: none;
        padding: 0;
        padding: 10px;
        cursor: pointer;
      }

      .line.selected {
        background: #e892a2;

        label,
        span {
          color: #fff;
        }
      }
    }
  }
}
</style>
