/*
 *@description:分组地图
 *@author: hudw
 *@date: 2022-12-21 17:40:58
*/
<template>
  <p-card class="full-card-panel packetMap">
    <a-space slot="title">
      <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
      分组运单地图
    </a-space>
    <a-space slot="extra">
      <p-button type="primary" @click="onCalculateMileage()">路线自动规划</p-button>
      <p-button type="primary" @click="onSave">保存</p-button>
    </a-space>
    <a-row :gutter="16" style="height: 100%">
      <a-col :span="12" style="height: 100%">
        <a-spin :spinning="spinning" style="height: 100%">
          <div :id="'group-web-map-' + $route.meta.menuId" style="height: 100%"></div>
        </a-spin>
      </a-col>
      <a-col :span="12" class="dis-flex">
        <div class="line-content" v-if="contentList">
          <p-card class="full-card-panel" :title="'分组名称：' + contentList.loadingBillHeaderVO.groupName" size="small" style="width: 100%">
            <p-grid-form
              :span="6"
              :ref="contentList.loadingBillHeaderVO.key"
              class="p-grid-view"
              :labelCol="{ span: 10 }"
              :wrapperCol="{ span: 14 }"
              :items="formItem"
              style="margin-buttom: 10px"
            ></p-grid-form>
            <p-table
              :customScrollbar="true"
              :activeKey.sync="activeID"
              row-key="id"
              :dataSource="contentList.loadingBillDetailVO"
              @rowDragend="rowDragend"
              @clickRow="handleRowClick"
              :scroll="{ x: true, y: $parent.$el.offsetHeight - 305 }"
              autoColWidth
              dragle
              bordered
              rowDrag
              :hasRowCount="true"
              :rowSelectType="false"
              :pagination="false"
              :columns="columns"
            >
              <!-- <a-space slot="operation" slot-scope="text, record, index">
                  <p-button size="small" type="primary" :disabled="index === 0" @click.stop="() => onUp(record, index)">上移</p-button>
                  <p-button size="small" type="danger" :disabled="index === contentList.loadingBillDetailVO.length - 1" @click.stop="() => onDown(record, index)">下移</p-button>
                </a-space> -->
            </p-table>
            <!-- {{ contentList.loadingBillDetailVO }} -->
          </p-card>
        </div>
      </a-col>
    </a-row>
  </p-card>
</template>
<script>
import { setColumns } from './js/tableConfig.js';
import { setFormItem } from './js/formConfig.js';
import { calculate_mileage, resultSortMethod } from '@/blocks/components/scheduling/packetScheduling/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) }));
export default {
  props: {
    dataSource: {
      /**loadingBillHeaderVO, loadingBillDetailVO */
      type: Object,
    },
    type: {
      type: null,
    },
  },
  data() {
    return {
      columns: setColumns(this),
      formItem: setFormItem(this),
      contentList: null,
      spinning: false,
      lineArr: [],
      activeID: '',
      selectIndex: -1,
      SimpleMarker: '',
      SimpleInfoWindow: '',
      pathSimplifierIns: '',
      PathSimplifier: '',
      currentMarker: null,
      geocoder: null,
      myMap: null,
      polyline: null,
      driving: null,
      drivingList: [],

      zindex: 100,
    };
  },
  mounted() {},
  watch: {
    activeID(value) {
      this.currentMarker && this.myMap.remove(this.currentMarker);
      this.myMap?.clearInfoWindow();
      if (!value) return;
      const { loadingBillDetailVO } = this.contentList;
      let row = loadingBillDetailVO.find((item) => {
        return item.id === value && item;
      });

      this.openInfo(row);
    },
    type(value) {
      if (value == 'groupMap') {
        this.init();

        this.resultData().then((loadingBillDetailVO) => {
          setTimeout(() => {
            this.paintingMap(loadingBillDetailVO);
          }, 100);
        });
      } else {
      }
    },
  },
  created() {
    this.useMap();
  },
  methods: {
    handleRowClick(event, key, data) {
      if (data) {
        //   data?.m.setzIndex(+new Date())
      }
    },

    rowDragend(event, res) {
      const { currentRecord, currentRowNode, handleResult } = res;
      let data = this.contentList.loadingBillDetailVO;
      handleResult(data);
      let prevId = currentRecord.id;

      this.$nextTick(() => {
        data.forEach((item) => {
          item.siteOrder = item._row_count;
        });

        this.paintingMap(data, () => {
          this.activeID = prevId;
        });
      });
    },
    onUp(record, index) {
      this.myMap?.clearInfoWindow();

      let prv = record.siteOrder;
      let prevId = record.id;

      let data = this.contentList.loadingBillDetailVO;
      record.siteOrder = data[index - 1].siteOrder;
      data[index - 1].siteOrder = prv;
      data.sort((a, b) => {
        return a.siteOrder - b.siteOrder;
      });
      this.paintingMap(data, () => {
        this.activeID = prevId;
      });
    },
    // 下移
    onDown(record, index) {
      this.myMap?.clearInfoWindow();

      let data = this.contentList.loadingBillDetailVO;
      let prv = record.siteOrder;
      let prevId = record.id;
      record.siteOrder = data[index + 1].siteOrder;
      data[index + 1].siteOrder = prv;
      data.sort((a, b) => {
        return a.siteOrder - b.siteOrder;
      });
      this.paintingMap(data, () => {
        this.activeID = prevId;
      });
    },
    openInfo(data) {
      let infoWindow = new AMap.InfoWindow({
        content: `
                <div class="info">
                  <div class="info-item">
                    <label>${data.type}名称:</label>
                    <div class="wrapper">${data.scName}</div>
                  </div>
                  <div class="info-item">
                    <label>站点:</label>
                    <div class="wrapper">${data.stationName || '无'}</div>
                  </div>
                  <div class="info-item">
                    <label>站点类型:</label>
                    <div class="wrapper">${data.siteType}</div>
                  </div>
                  <div class="info-item">
                    <label>详细地址:</label>
                    <div class="wrapper"> ${data.address}</div>
                  </div>

                 </div>
                `,
        offset: new AMap.Pixel(0, -35),
      });
      infoWindow.open(this.myMap, data.position);
      this.myMap.setCenter(data.position, true);
      this.zindex += 1;
      data.m && data.m.setzIndex(this.zindex);
    },

    useMap() {
      let _this = this;
      //简单标注
      AMapUI.loadUI(['overlay/SimpleMarker', 'overlay/SimpleInfoWindow'], (SimpleMarker, SimpleInfoWindow) => {
        //启动页面
        this.SimpleMarker = SimpleMarker;
        this.SimpleInfoWindow = SimpleInfoWindow;
      });
      AMap.plugin(['AMap.PlaceSearch', 'AMap.Driving', 'AMap.TruckDriving'], () => {
        //异步同时加载多个插件
        _this.placeSearch = new AMap.PlaceSearch({
          map: _this.myMap,
        });
      });
      this.geocoder = new AMap.Geocoder();
    },
    onSave() {
      let loadingBillDetailVO = this.dataSource.loadingBillDetailVO;
      let loadingBillHeaderVO = this.contentList.loadingBillHeaderVO;
      const { groupItem } = loadingBillHeaderVO;
      let tableData = this.contentList.loadingBillDetailVO;
      let map = {};
      let params = [];

      tableData.map((o) => {
        map[o.id] = o;
        params.push({
          siteOrder: o._row_count,
          stationName: o.stationName,
          scName: o.scName || null,
          groupItem,
        });
      });

      //计算里程
      calculate_mileage(this, params).then((data) => {
        if (data) {
          loadingBillHeaderVO = { ...loadingBillHeaderVO, ...this.$refs[loadingBillHeaderVO.key].form.getFieldsValue(), ...data };
        }

        loadingBillDetailVO.forEach((item, index) => {
          //提货
          let shipper = map['pickUpOrder_' + item.shipperId];
          item.pickUpOrder = shipper._row_count;
          // item.consigneeDeliveryOrder=item.pickUpOrder
          //配送
          let consignee = map['shippingOrder_' + item.consigneeId];
          item.shippingOrder = consignee._row_count;
          // item.shipperDeliveryOrder=item.shippingOrder

          console.log(index, '提货:' + item.pickUpOrder, '配送:' + item.shippingOrder);
        });

        this.drivingList = [];
        this.myMap?.destroy();
        this.myMap = null;
        this.$emit('save', {
          loadingBillHeaderVO,
          loadingBillDetailVO,
        });
      });
    },
    back() {
      this.drivingList = [];
      this.myMap?.destroy();
      this.myMap = null;
      this.$emit('back', 'sys');
    },
    //处理排序
    resultSortMethod,
    resultData() {
      return new Promise((resolve) => {
        const { loadingBillHeaderVO, loadingBillDetailVO } = this.dataSource;
        this.$nextTick(() => {
          this.$refs[loadingBillHeaderVO.key].form.setFieldsValue(loadingBillHeaderVO);
        });
        let arr = this.resultSortMethod(loadingBillDetailVO);
        this.contentList = {
          loadingBillHeaderVO,
          loadingBillDetailVO: arr,
        };

        return resolve(arr);
      });
    },
    //绘制地图轨迹
    paintingMap(loadingBillDetailVO, callback) {
      let _this = this;
      let totalMileageMap = 0;
      if (!loadingBillDetailVO) {
        loadingBillDetailVO = this.contentList.loadingBillDetailVO;
      }
      let form = this.$refs[this.contentList.loadingBillHeaderVO.key].form;
      if (loadingBillDetailVO?.length > 0) {
        for (let i = 0; i < loadingBillDetailVO.length; i++) {
          let item = loadingBillDetailVO[i],
            index = i;
          const { position } = item;
          item.siteOrder = item._row_count;
          item?.driving?.clear?.();

          if (position) {
            item.LngLat = new AMap.LngLat(position[0], position[1]);
            item.m && item.m.remove();
            if (index === 0) {
              item.m = new AMap.Marker({
                map: _this.myMap,
                topWhenClick: false,
                extData: item,
                icon: startIcon,
                position,
                offset: new AMap.Pixel(-13, -26),
                // anchor: 'bottom-center',
              });
            } else if (index == loadingBillDetailVO.length - 1) {
              item.m = new AMap.Marker({
                map: _this.myMap,
                topWhenClick: false,
                extData: item,
                icon: new AMap.Icon(
                  iconConfig({
                    imageOffset: new AMap.Pixel(-95, -3),
                  })
                ),
                offset: new AMap.Pixel(-13, -30),
                position: position,
              });
            } else {
              item.m = new AMap.Marker({
                map: _this.myMap,
                extData: item,
                topWhenClick: true,
                content: `<i class="icon-jing">${item.siteOrder}</i>`,
                position,
                anchor: 'bottom-center',
              });
            }
            item.m.on('click', () => {
              _this.openInfo(item);
            });

            item.driving=this.createDriving()
            let curLngLat = item.LngLat;
            let nextItem = loadingBillDetailVO[i + 1];
            if (nextItem) {
              nextItem.LngLat = new AMap.LngLat(nextItem.position[0], nextItem.position[1]);
              item.driving.search(
                curLngLat,
                nextItem.LngLat,
                function (status, result) {
                  this.result = null;
                  if (status === 'complete') {
                    let r = result.routes[0];
                    callback && callback();
                    totalMileageMap = totalMileageMap + r.distance;
                    form.setFieldsValue({
                      totalMileageMap: parseFloat(_this.BigJs(totalMileageMap).div(1000)),
                    });
                  } else {
                    return this.$exception({
                      message: '绘制地图线路失败',
                    });
                  }
                }.bind(item)
              );
            }
          }
        }
      }

      return this.myMap?.clearInfoWindow();

    },
    onCalculateMileage() {
      this.myMap.clearMap();

      let loadingBillDetailVO = this.contentList.loadingBillDetailVO;
      let _this = this;
      let complete = 0;
      for (let i = 1; i < loadingBillDetailVO.length; i++) {
        let state = loadingBillDetailVO[0];
        let item = loadingBillDetailVO[i];
        state?.driving?.clear()
        item?.driving?.clear()

        state.distance = 0;
        state.time = 0;
        item.i = i;
        item.driving=this.createDriving()
        item.driving.search(state.LngLat,item.LngLat,
          function (status, result) {
            if (status === 'complete') {
              complete++;
              let r = result.routes[0];
              this.time = r.time;
              this.distance = r.distance;
              console.log(this.distance);
            }

            if (complete === loadingBillDetailVO.length - 1) {
              loadingBillDetailVO.sort(function (a, b) {
                if (a.distance && b.distance) {
                  return (a.distance+a.time) - (b.distance+b.time)
                }
              });
              _this.$nextTick(() => {
                _this.paintingMap();
              });
            }
          }.bind(item)
        );
      }
    },
    currying(arr = []) {
      return function (driving) {
        if (typeof driving == 'object') {
          return arr.push(driving);
        } else {
          arr.forEach((item) => item.clear());
        }
      };
    },
    createDriving() {
      return new AMap.Driving({
              hideMarkers: true,
              showTraffic: false,
              map: this.myMap,
              policy: AMap.DrivingPolicy.LEAST_TIME,
            });
    },
    init() {
      let _this = this;
      this.myMap = new AMap.Map('group-web-map-' + _this.$route.meta.menuId, {
        scrollWheel: true,
        zoom: 13,
        // features: ['bg', 'road'],
        resizeEnable: true,
        viewMode: '2D', // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D',
        mapStyle: 'amap://styles/light',
        // center: [116.397428, 39.90923], //初始化地图中心点
      });
      // let toolBar = new AMap.ToolBar({
      //   position: {
      //     bottom: '20px',
      //     right: '20px',
      //   },
      // });
      //this.myMap.addControl(toolBar);
      // this.driving = new AMap.Driving({
      //   hideMarkers: true,
      //   showTraffic: false,
      //   map: this.myMap,
      //   //  panel: "panel",
      //   policy: AMap.DrivingPolicy.LEAST_TIME,
      // });
    },
  },
};
</script>
<style lang='less'>
.packetMap {
  .ant-spin-container {
    height: 100%;
  }
  .amap-icon img {
    width: 25px;
    height: 34px;
  }

  .info {
    padding: 5px;
    position: relative;
    white-space: normal;
    width: 300px;
    line-height: 1.8;
  }
  .info-item {
    display: flex;
    label {
      width: 70px;
      color: #333;
      text-align: right;
    }
    .wrapper {
      flex: 1;
    }
  }
  .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;
  }
  #panel {
    position: absolute;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
  }
  #panel .amap-call {
    background-color: #009cf9;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }
  #panel .amap-lib-driving {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow: hidden;
  }
  .dis-flex {
    height: 100%;
    display: flex;
    flex-direction: column;

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

      .line {
        list-style: none;
        padding: 10px;
      }

      .line.selected {
        border: 1px solid #333;
        box-sizing: border-box;
      }

      .form_title {
        text-align: center;
        height: 40px;
        line-height: 40px;
        color: #f56c6c;
        font-weight: 700;
      }
    }
  }
}
</style>