
// /**分页查询接口重试日志 */
import request from '@/utils/request';

import { UPCLOUD_RDC_TMS_BUSINESS_SERVICE,UPCLOUD_RDC_TMS_MAINDATA_SERVICE } from '@/config/serviceSettings.js';

const serviceName = UPCLOUD_RDC_TMS_BUSINESS_SERVICE;
//quantity_statistics,querySysGroupShipbill
//'/pending_dispatch/goods_quantity_statistics',
//分组单查运单
export const group_shipbill_query = serviceName + "/pending_dispatch/sys_group_shipbill_query"
export const querySysGroupShipbill = (context, data) => {
  context.loading=true
  return request({
    url:group_shipbill_query,
    method: 'post',
    data,
  }).then((response) => {
    if (response.success) {
      return response.data
    } else {
      context.$exception(response);
      return null
    }
  }).finally((error) => {
      context.loading=false
    });
};


// 系统分组-查询
export const sys_group_query = (data) => {
  return request.post(serviceName + '/pending_dispatch/sys_group_query_new', data)
}

//查询承运商策略
export const query_dispatch_strategy = (data) => {
  return request.post(serviceName + '/pending_dispatch/query_dispatch_strategy', data)
}

export const getCarData = (context, plateNumber) => {
  return request({
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/vehicle/popup',
    method: 'post',
    data: {
      plateNumber,
      pageNum:1,pageSize:10

    },
  }).then((response) => {
    if (response.success) {
      return response.data?.list[0] ?? null
    } else {
      context.$exception(response);
      return null

    }
  })
    .finally((error) => {
    });
};

//加载 配载单信息（按线路&始发省分组）
/**
 * shipbillIdList
 *
 */
export const quantity_statistics = (context,shipbillIdList) => {
  context.loading = true;
  return request({
    url: serviceName + '/pending_dispatch/goods_quantity_statistics',
    method: 'post',
    data: {
      shipbillIdList
    },
  }).then((response) => {
    if (response.success) {
      return response.data;
    } else {
      context.$exception(response);
    }
  })
    .finally((error) => {
      context.loading = false;
    });
};

/**计算里程值
 *
 * //站点
      "shipperStationName": null,
      "consigneeStationName": null,
//保存
      "shippingOrder": null,
      "pickUpOrder": null,

//初始
      "shipperDeliveryOrder": null,
      "consigneeDeliveryOrder": null,
      "consigneeId": "1000000150",
      "shipperId": "1000000081"


 * @ApiModelProperty(value = "站点顺序")
	private Integer siteOrder;
	@ApiModelProperty(value = "站点名称")
	private String stationName;
	@ApiModelProperty(scName = "配载站点名称")
	private String scName;
 * @ApiModelProperty(groupItem = "分组信息")
  private Array groupItem;

   返回值
  @ApiModelProperty(value = "总里程数")
  private BigDecimal totalMileage;

  @ApiModelProperty(value = "配送线路")
  private String deliveryLines;
 */
export const calculate_mileage= (context, data) => {
  context.loading = true;
  return request({
    url: serviceName + '/pending_dispatch/calculate_mileage',
    method: 'post',
    data,
  }).then((response) => {
    if (response.success) {
      return response.data;
    } else {
      context.$exception(response);
    }
  })
    .finally((error) => {
      context.loading = false;
    });
};


///调度管理-待调度控制层/分组调度
export const dataSubmit = (_this, data) => {
  let confirmLoading = true
  return new Promise((resolve) => {
    _this.$confirm({
      title: '是否调度该配载单?',
      confirmLoading,
      onOk(clear) {
        confirmLoading = true
        return request({
          url: serviceName + '/pending_dispatch/group_dispatch',
          method: 'post',
          data,
        })
          .then((response) => {
            if (response.success) {
              _this.$message.success(response.message)
            } else {
              _this.$exception(response)
            }
            setTimeout(() => {
              confirmLoading = false
            }, 100)
            return resolve(response)
          })
          .catch((response) => {
            confirmLoading = false
          })
      },
    })
  })
}




///调度管理-待调度控制层/分组调度并审核

export const dataSubmitReview = (_this, data) => {
  let confirmLoading = true
  return new Promise((resolve) => {
    _this.$confirm({
      title: '是否调度并审核该配载单?',
      confirmLoading,
      onOk() {
        confirmLoading = true
        return request({
          url: serviceName + '/pending_dispatch/group_dispatch_review',
          method: 'post',
          data,
        })
          .then((response) => {
            if (response.success) {
              _this.$message.success(response.message)
            } else {
              _this.$exception(response)
            }
            setTimeout(() => {
              confirmLoading = false
            }, 100)
            return resolve(response)
          })
          .catch((response) => {
            confirmLoading = false
          })
      },
    })
  })
};

//处理运单数据，返回排序站点
export const resultSortMethod = (loadingBillDetailVO) => {
  let arr = [],arr2 = [],cObj = {},j = -1; //去重存id
  let _enum = {
      //提货顺序
      pickUpOrder: {
        id(item) {
          return 'pickUpOrder_' + item.shipperId;
        },
        siteOrder(item,i) {
          if (item.pickUpOrder === null) {
//            item.shipperDeliveryOrder=99999
            return 99999- ~~i
          } else {

            return item.pickUpOrder;

          }

        },
       stationName(item) {
        return item.shipperStationName;
        },
        oid(item) {
          return item.shipperId;
        },
        siteType() {
          return '提货';
        },
        code(item) {
          return item.shipperCode;
        },
        name(item) {
          return item.shipperName;
        },
        scName(item) {
          return item.shipperName;
        },
        type(item) {
          return item.shipperTypeName;
        },
        address(item) {
          return item.shipperProvinceCityDistrict + '-' + item.shipperAddress;
        },
        points({ shipperProvinceName, shipperAddress }) {
          return { keyword: shipperAddress, city: shipperProvinceName };
        },
        position(item, Obj) {
          const { shipperLongitude, shipperLatitude } = item;
          if (!shipperLongitude || !shipperLatitude) {
            new AMap.Geocoder().getLocation(item.shipperProvinceCityDistrict + '' + item.shipperAddress, (status, result) => {
              if (status === 'complete' && result.geocodes) {
                item.shipperLongitude = result.geocodes[0].location.lng;
                item.shipperLatitude = result.geocodes[0].location.lat;
                Obj.position = [item.shipperLongitude, item.shipperLatitude];
              }
            });
          } else {
            return [item.shipperLongitude, item.shipperLatitude];
          }
        },
      },
      // 配送顺序
      shippingOrder: {
        id(item) {
          return 'shippingOrder_' + item.consigneeId;
        },
        siteOrder(item,i) {
          if (item.shippingOrder === null) {
            return 999999- ~~i;
          } else {

            return item.shippingOrder;

          }


        },
        siteType() {
          return '配送';
        },
        stationName(item) {
          return item.consigneeStationName;
          },
        oid(item) {
          return item.consigneeId;
        },
        code(item) {
          return item.consigneeCode;
        },
        name(item) {
          return item.consigneeName;
        },
        scName(item) {
          return item.consigneeName;
        },
        type(item) {
          return item.consigneeTypeName;
        },
        address(item) {
          return item.consigneeProvinceCityDistrict + '-' + item.consigneeAddress;
        },
        points({ consigneeProvinceName, consigneeAddress }) {
          return { keyword: consigneeAddress, city: consigneeProvinceName };
        },
        position(item, Obj) {
          const { consigneeLongitude, consigneeLatitude } = item;
          if (!consigneeLongitude || !consigneeLatitude) {
            new AMap.Geocoder().getLocation(item.consigneeProvinceCityDistrict + '' + item.consigneeAddress, (status, result) => {
              if (status === 'complete' && result.geocodes) {
                item.consigneeLongitude = result.geocodes[0].location.lng;
                item.consigneeLatitude = result.geocodes[0].location.lat;
                Obj.position = [item.consigneeLongitude, item.consigneeLatitude];
              }
            });
          } else {
            return [item.consigneeLongitude, item.consigneeLatitude];
          }
        },
      },
  };
  let len = loadingBillDetailVO.length - 1;
  const { pickUpOrder, shippingOrder } = _enum;

    for (let i = len; i > -1; i--) {
      let o_1 = {},
        o_2 = {},
        element = loadingBillDetailVO[i];
      for (let key in pickUpOrder) {
        o_1[key] = pickUpOrder[key](element, o_1);
      }
      for (let key in shippingOrder) {
        o_2[key] = shippingOrder[key](element, o_2,i);
      }
      if (j > -1) {
        //去重逻辑
        //与上一个对象去对比
        if (!cObj[o_1.id]) {
          cObj[o_1.id] = true;
          arr.push(o_1);
        }
        if (!cObj[o_2.id]) {
          cObj[o_2.id] = true;
          arr2.push(o_2);
        }
      } else {
        cObj[o_1.id] = true;
        cObj[o_2.id] = true;
        arr.push(o_1);
        arr2.push(o_2);
      }
      j++;
    }


    arr = arr.concat(arr2);
    arr.sort((a, b) => {
      return ~~a.siteOrder - ~~b.siteOrder;
    });

    for (let i = arr.length - 1; i > -1; i--) {
      let item = arr[i];
      item.siteOrder = i + 1;
    }
    return arr
}
