package com.qs.mp.web.controller.api.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.admin.domain.Supplier;
import com.qs.mp.admin.domain.param.UserDeliverOrderQueryParam;
import com.qs.mp.admin.domain.param.UserDeliverOrderShipParam;
import com.qs.mp.admin.domain.param.UserDeliverOrderSmsParam;
import com.qs.mp.admin.service.ISupplierService;
import com.qs.mp.common.annotation.Log;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.BusinessType;
import com.qs.mp.common.enums.DeliverOrderStatusEnum;
import com.qs.mp.common.enums.DeliverTypeEnum;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.jsms.JSMSUtils;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.user.domain.UserDeliverOrder;
import com.qs.mp.user.domain.UserDeliverOrderItem;
import com.qs.mp.user.domain.excel.DeliverOrderExcel;
import com.qs.mp.user.domain.vo.OrderDeliverItemVO;
import com.qs.mp.user.domain.vo.UserDeliverOrderItemVO;
import com.qs.mp.user.domain.vo.UserDeliverOrderVO;
import com.qs.mp.user.service.IUserDeliverOrderItemService;
import com.qs.mp.user.service.IUserDeliverOrderService;
import com.qs.mp.utils.ExcelUtil;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/v1/mp/admin/deliver/order")
@Api(tags = "用户提货订单接口")
@AllArgsConstructor
public class UserDeliverOrderMgrController extends BaseApiController {

	@Autowired
	private IUserDeliverOrderService userDeliverOrderService;

	@Autowired
	private IUserDeliverOrderItemService userDeliverOrderItemService;

	@PostMapping("/sendSMS")
	@ApiOperation("发送短信")
	@PreAuthorize("@ss.hasPermi('order:deliver:sendSMS')")
	public AjaxResult sendSMS(@RequestBody List<UserDeliverOrderSmsParam> paramList) {
		for (UserDeliverOrderSmsParam userDeliverOrderSmsParam : paramList) {
			String orderNo = userDeliverOrderSmsParam.getOrderId()
				.substring(userDeliverOrderSmsParam.getOrderId().length() - 4);
			String mobile = userDeliverOrderSmsParam.getMobile();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < userDeliverOrderSmsParam.getGoodsNameList().size(); i++) {
				sb.append(userDeliverOrderSmsParam.getGoodsNameList().get(i));
				if (i != userDeliverOrderSmsParam.getGoodsNameList().size() - 1) {
					sb.append(",");
				}
			}
			// 截取最长长度
			String context = sb.substring(0, Math.min(sb.length(), 200));
			JSMSUtils.sendDeliverSMS(mobile, orderNo, context);
		}
		return AjaxResult.success();
	}


	/**
	 * 用户提货订单列表
	 */
	@PostMapping("/list")
	@ApiOperation(value = "用户提货订单列表", notes = "获取用户提货订单列表")
	@ApiResponses(
			@ApiResponse(code = 200, message = "OK", response = UserDeliverOrderVO.class)
	)
	@PreAuthorize("@ss.hasPermi('order:deliver:list')")
	public TableDataInfo list(@RequestBody UserDeliverOrderQueryParam queryParam) {
		startPage();
		QueryWrapper<UserDeliverOrder> queryWrapper = new QueryWrapper<UserDeliverOrder>();
		queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getOrderId()), "t1.order_id", queryParam.getOrderId());
		queryWrapper.eq(null != queryParam && null != queryParam.getStatus(), "t1.`status`", queryParam.getStatus());
		queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getTel()) , "t1.`tel`", queryParam.getTel());
		queryWrapper.eq(null != queryParam && null != queryParam.getResource(), "t1.`resource`", queryParam.getResource());
		queryWrapper.ge(null != queryParam && null != queryParam.getStartTime(), "t1.created_time", queryParam.getStartTime());
		queryWrapper.le(null != queryParam && null != queryParam.getEndTime(), "t1.created_time", queryParam.getEndTime());
		queryWrapper.eq(null != queryParam && null != queryParam.getSupplierId(), "t3.supplier_id", queryParam.getSupplierId());
		queryWrapper.like(null != queryParam && StringUtils.isNotBlank(queryParam.getNickName()), "t2.nick_name", queryParam.getNickName());
		queryWrapper.like(null != queryParam && StringUtils.isNotBlank(queryParam.getTitle()), "t3.title", queryParam.getTitle());
		queryWrapper.orderByDesc("t1.order_id");
		List<UserDeliverOrderVO> userDeliverOrderVOList = userDeliverOrderService.selectUserDeliverOrderVoList(queryWrapper);
		for (UserDeliverOrderVO userDeliverOrderVO : userDeliverOrderVOList) {
			QueryWrapper<UserDeliverOrderItemVO> userDeliverOrderItemVOQueryWrapper = new QueryWrapper<>();
			userDeliverOrderItemVOQueryWrapper.eq("t1.order_id", userDeliverOrderVO.getOrderId());
			userDeliverOrderItemVOQueryWrapper.eq(null != queryParam && null != queryParam.getSupplierId(), "t1.supplier_id", queryParam.getSupplierId());
			List<UserDeliverOrderItemVO> orderItems = userDeliverOrderItemService.selectUserDeliverOrderItemVOListByQueryWrapper(userDeliverOrderItemVOQueryWrapper);
			userDeliverOrderVO.setItems(orderItems);
		}
		TableDataInfo rspData = getDataTable(userDeliverOrderVOList);
		return rspData;
	}

	/**
	 * 订单详情
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "订单详情", notes = "在订单列表页面查看详情")
	@ApiResponses(
			@ApiResponse(code = 200, message = "OK", response = UserDeliverOrderVO.class)
	)
	@PreAuthorize("@ss.hasPermi('order:deliver:query')")
	public AjaxResult query(@RequestBody UserDeliverOrder order) {
		if (null == order || StringUtils.isBlank(order.getOrderId())) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		UserDeliverOrderVO userDeliverOrderVO = userDeliverOrderService.selectUserDeliverOrderVo(order.getOrderId());
		if (null == userDeliverOrderVO || StringUtils.isBlank(userDeliverOrderVO.getOrderId())) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		List<UserDeliverOrderItemVO> orderItems = userDeliverOrderItemService.selectUserDeliverOrderItemVOList(userDeliverOrderVO.getOrderId());
		userDeliverOrderVO.setItems(orderItems);
		// 获取物流详情
		userDeliverOrderVO.setDeliverList(userDeliverOrderItemService.getDeliverItemList(order.getOrderId(), orderItems));
		return AjaxResult.success(userDeliverOrderVO);
	}



	/**
	 * 订单发货
	 */
	@Log(title = "用户提货订单发货", businessType = BusinessType.UPDATE)
	@PostMapping("/ship")
	@ApiOperation(value = "订单发货", notes = "在订单发货页面提交")
	@PreAuthorize("@ss.hasPermi('order:deliver:ship')")
	public AjaxResult ship(@RequestBody UserDeliverOrderShipParam shipParam) {
		if (null == shipParam || StringUtils.isBlank(shipParam.getOrderId())) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}

		Integer deliveryType = shipParam.getDeliveryType();
		if (null == deliveryType) {
			deliveryType = 1;
		}

		if (DeliverTypeEnum.DELIVER.getValue().equals(deliveryType)) {
			if (Objects.isNull(shipParam.getDeliveryId())) {
				return AjaxResult.error("快递公司不能为空");
			}
			if (StringUtils.isBlank(shipParam.getDeliveryFlowId())) {
				return AjaxResult.error("快递单号不能为空");
			}
		}

		List<UserDeliverOrderItem> itemList = new ArrayList<UserDeliverOrderItem>();
		if (null != shipParam && null != shipParam.getItemIds() && shipParam.getItemIds().size() > 0) {
			Date deliveryTime = new Date();
			for (String itemId : shipParam.getItemIds()) {
				if (StringUtils.isNotBlank(itemId)) {
					UserDeliverOrderItem item = new UserDeliverOrderItem();

					if (DeliverTypeEnum.NO_DELIVER.getValue().equals(deliveryType)) {
						// 无需物流，设置发货时间为当前时间
						item.setItemId(itemId);
						item.setDeliveryTime(deliveryTime);

					} else if (DeliverTypeEnum.DELIVER.getValue().equals(deliveryType)) {
						// 快递发货，设置物流信息
						item.setItemId(itemId);
						item.setDeliveryId(shipParam.getDeliveryId());
						item.setDeliveryFlowId(shipParam.getDeliveryFlowId());
						item.setDeliveryTime(deliveryTime);
					}
					itemList.add(item);
				}
			}
		}
		if (null != itemList && itemList.size() > 0) {
			boolean rtn = userDeliverOrderService.userDeliverOrderShip(shipParam.getOrderId(), itemList);
			return rtn ? AjaxResult.success() : AjaxResult.error("发货失败");
		}

		return AjaxResult.error("发货失败");
	}

	/**
	 * 订单发货修改
	 */
	@Log(title = "用户提货订单发货单号修改", businessType = BusinessType.UPDATE)
	@PostMapping("/ship/update")
	@ApiOperation(value = "订单发货修改", notes = "在订单发货页面提交")
	@ApiResponses(
			@ApiResponse(code = 200, message = "success", response = AjaxResult.class)
	)
	@PreAuthorize("@ss.hasPermi('order:deliver:ship')")
	public AjaxResult updateShipInfo(@RequestBody UserDeliverOrderShipParam shipParam) {
		if (null == shipParam || StringUtils.isBlank(shipParam.getOrderId())
				|| CollectionUtils.isEmpty(shipParam.getItemIds())) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}

		Integer deliveryType = shipParam.getDeliveryType();
		if (null == deliveryType) {
			shipParam.setDeliveryType(1);
		}

		if (DeliverTypeEnum.DELIVER.getValue().equals(shipParam.getDeliveryType())) {
			if (Objects.isNull(shipParam.getDeliveryId())) {
				return AjaxResult.error("快递公司不能为空");
			}
			if (StringUtils.isBlank(shipParam.getDeliveryFlowId())) {
				return AjaxResult.error("快递单号不能为空");
			}
		}


		// 修改物流信息
		boolean res = userDeliverOrderService.updateShipInfo(shipParam);


		return res ? AjaxResult.success() : AjaxResult.error("消息修改失败");
	}


	@PostMapping("/batchShip")
	@PreAuthorize("@ss.hasPermi('order:deliver:ship')")
	@ApiOperation(value = "批量发货")
	public AjaxResult batchShip(MultipartFile file) {
		// 获取文件内的提货订单数据列表
		try {
			ExcelUtil<DeliverOrderExcel> util = new ExcelUtil<DeliverOrderExcel>(DeliverOrderExcel.class);
			List<DeliverOrderExcel> deliverOrderExcelList = util.importExcel(file.getInputStream());
			if(null == deliverOrderExcelList || deliverOrderExcelList.size() == 0) {
				return AjaxResult.error("导入失败，选择的导入文件中没有有效的数据");
			}
			// 过滤没有快递信息的数据
			List<DeliverOrderExcel> deliverOrderList  = new ArrayList<>();
			for (DeliverOrderExcel deliverOrderExcel : deliverOrderExcelList) {
				if (StringUtils.isNotBlank(deliverOrderExcel.getDeliveryFlowId()) && StringUtils.isNotBlank(deliverOrderExcel.getCompanyName())) {
					deliverOrderList.add(deliverOrderExcel);
				}
			}
			if (CollectionUtils.isEmpty(deliverOrderList)) {
				return AjaxResult.error("导入失败，选择的导入文件中没有有效的数据");
			}

			String content = userDeliverOrderService.batchShip(deliverOrderList);
			return AjaxResult.success("success", content);
		} catch (Exception e) {
			return AjaxResult.error("导入失败，请联系管理员");
		}
	}


	@Log(title = "提货订单导出", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	@ApiOperation("提货订单导出")
	@PreAuthorize("@ss.hasPermi('order:deliver:export')")
	public AjaxResult export(@RequestBody UserDeliverOrderQueryParam queryParam) {


		if (queryParam == null
				|| queryParam.getStatus() == null
				|| (!DeliverOrderStatusEnum.NOT_DELIVER.getValue().equals(queryParam.getStatus())
				&& !DeliverOrderStatusEnum.PART_DELIVER.getValue().equals(queryParam.getStatus()))) {

			// 导出时间范围限制校验
			Date startTime = queryParam.getStartTime();
			Date endTime = queryParam.getEndTime();
			if (startTime == null || endTime == null) {
				return AjaxResult.error("导出数据必须设置日期范围");
			}
			if (DateUtils.diff(startTime, endTime) > 30) {
				return AjaxResult.error("导出的数据不能超过31天");
			}
		}

		List<DeliverOrderExcel> excelList = new ArrayList<DeliverOrderExcel>();
		List<UserDeliverOrderVO> listAll = new ArrayList<UserDeliverOrderVO>();
		// 首先查询要导出的数据总数
		QueryWrapper<UserDeliverOrder> queryWrapper = new QueryWrapper<UserDeliverOrder>();
		queryWrapper.eq(null != queryParam && StringUtils.isNotBlank(queryParam.getOrderId()), "t1.order_id", queryParam.getOrderId());
		queryWrapper.eq(null != queryParam && null != queryParam.getStatus(), "t1.`status`", queryParam.getStatus());
		queryWrapper.eq(null != queryParam && null != queryParam.getResource(), "t1.`resource`", queryParam.getResource());
		queryWrapper.eq(null != queryParam && null != queryParam.getSupplierId(), "t3.supplier_id", queryParam.getSupplierId());
		queryWrapper.ge(null != queryParam && null != queryParam.getStartTime(), "t1.created_time", queryParam.getStartTime());
		queryWrapper.le(null != queryParam && null != queryParam.getEndTime(), "t1.created_time", queryParam.getEndTime());
		queryWrapper.like(null != queryParam && StringUtils.isNotBlank(queryParam.getNickName()), "t2.nick_name", queryParam.getNickName());
		queryWrapper.like(null != queryParam && StringUtils.isNotBlank(queryParam.getTitle()), "t3.title", queryParam.getTitle());
		queryWrapper.orderByDesc("t1.order_id");
		int totalSize = userDeliverOrderService.selectUserDeliverOrderCount(queryWrapper);
		if (totalSize == 0) {
			return AjaxResult.error("没有符合条件的用户提货订单");
		}
		int pageSize = 2000;
		if (totalSize > pageSize) {
			int totalPage = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1;
			for (int i = 0; i < totalPage; i++) {
				queryWrapper.last("limit " + (i * pageSize) + ", " + pageSize);
				List<UserDeliverOrderVO> userDeliverOrderVOList = userDeliverOrderService.selectUserDeliverOrderVoList(queryWrapper);
				for (UserDeliverOrderVO userDeliverOrderVO : userDeliverOrderVOList) {
					QueryWrapper<UserDeliverOrderItemVO> userDeliverOrderItemVOQueryWrapper = new QueryWrapper<>();
					userDeliverOrderItemVOQueryWrapper.eq("t1.order_id", userDeliverOrderVO.getOrderId());
					userDeliverOrderItemVOQueryWrapper.eq(null != queryParam && null != queryParam.getSupplierId(), "t1.supplier_id", queryParam.getSupplierId());
					List<UserDeliverOrderItemVO> orderItems = userDeliverOrderItemService.selectUserDeliverOrderItemVOListByQueryWrapper(userDeliverOrderItemVOQueryWrapper);
					userDeliverOrderVO.setItems(orderItems);
				}
				if (null != userDeliverOrderVOList && userDeliverOrderVOList.size() > 0) {
					listAll.addAll(userDeliverOrderVOList);
				}
			}
		} else {
			listAll = userDeliverOrderService.selectUserDeliverOrderVoList(queryWrapper);
			for (UserDeliverOrderVO userDeliverOrderVO : listAll) {
				QueryWrapper<UserDeliverOrderItemVO> userDeliverOrderItemVOQueryWrapper = new QueryWrapper<>();
				userDeliverOrderItemVOQueryWrapper.eq("t1.order_id", userDeliverOrderVO.getOrderId());
				userDeliverOrderItemVOQueryWrapper.eq(null != queryParam && null != queryParam.getSupplierId(), "t1.supplier_id", queryParam.getSupplierId());
				List<UserDeliverOrderItemVO> orderItems = userDeliverOrderItemService.selectUserDeliverOrderItemVOListByQueryWrapper(userDeliverOrderItemVOQueryWrapper);
				userDeliverOrderVO.setItems(orderItems);
			}
		}

		if (null != listAll && listAll.size() > 0) {
			// listAll.sort(Comparator.comparing(UserDeliverOrderVO::getOrderId));
			for (UserDeliverOrderVO deliverOrder : listAll) {
				if (null != deliverOrder && StringUtils.isNotBlank(deliverOrder.getOrderId())
						&& StringUtils.isNotBlank(deliverOrder.getReceiver())
						&& StringUtils.isNotBlank(deliverOrder.getTel())
						&& StringUtils.isNotBlank(deliverOrder.getProvince())
						&& StringUtils.isNotBlank(deliverOrder.getCity())
						&& StringUtils.isNotBlank(deliverOrder.getArea())
						&& StringUtils.isNotBlank(deliverOrder.getAddress()) && null != deliverOrder.getItems()
						&& deliverOrder.getItems().size() > 0) {
					for (UserDeliverOrderItemVO userDeliverOrderItem : deliverOrder.getItems()) {
						if (null != userDeliverOrderItem) {
							DeliverOrderExcel deliverOrderExcel = new DeliverOrderExcel();
							// 设置商品id
							deliverOrderExcel.setGoodsId(userDeliverOrderItem.getGoodsId());
							// 设置商品编号
							if (Objects.isNull(userDeliverOrderItem.getSkuId())) {
								deliverOrderExcel.setCode(userDeliverOrderItem.getGoodsCode());
							} else {
								deliverOrderExcel.setCode(userDeliverOrderItem.getSkuCode());
							}

							deliverOrderExcel.setItemId(userDeliverOrderItem.getItemId());
							deliverOrderExcel.setTitle(userDeliverOrderItem.getTitle());
							deliverOrderExcel.setProperties(userDeliverOrderItem.getProperties());
							deliverOrderExcel.setGoodsNum(userDeliverOrderItem.getGoodsNum());
							deliverOrderExcel.setCreatedTime(deliverOrder.getCreatedTime());
							deliverOrderExcel.setOrderId(deliverOrder.getOrderId());
							deliverOrderExcel.setResource(deliverOrder.getResource().getDesc());
							deliverOrderExcel.setMemo(deliverOrder.getMemo());
							deliverOrderExcel.setSupplierName(userDeliverOrderItem.getSupplierName());
							deliverOrderExcel.setShoppingLink(userDeliverOrderItem.getShoppingLink());
							deliverOrderExcel.setReceiver(deliverOrder.getReceiver());
							deliverOrderExcel.setTel(deliverOrder.getTel());
							deliverOrderExcel.setDeliveryFlowId(userDeliverOrderItem.getDeliveryFlowId());
							deliverOrderExcel.setCompanyName(userDeliverOrderItem.getCompanyName());


							int cost = 0;
							Integer skuCost = userDeliverOrderItem.getSkuCost();
							Integer goodsCost = userDeliverOrderItem.getGoodsCost();
							if (skuCost != null) {
								cost = skuCost;
							} else if (goodsCost != null){
								cost = goodsCost;
							}
							deliverOrderExcel.setGoodsCost(BigDecimal.valueOf(cost).divide(BigDecimal.valueOf(100),2, RoundingMode.HALF_UP));

							String address = deliverOrder.getProvince() + deliverOrder.getCity()
									+ deliverOrder.getArea() + deliverOrder.getAddress();
							deliverOrderExcel.setAddress(address);
							deliverOrderExcel.setStatus(deliverOrder.getStatus().getDesc());
							deliverOrderExcel.setItemStatus(
									StringUtils.isNotBlank(userDeliverOrderItem.getDeliveryFlowId()) ? "已发货" : "未发货");
							excelList.add(deliverOrderExcel);
						}
					}
				}
			}
		}
		ExcelUtil<DeliverOrderExcel> util = new ExcelUtil<DeliverOrderExcel>(DeliverOrderExcel.class);
		return util.exportExcel(excelList, "商品提货订单导出", false);
	}
}
