package com.web.controller.business;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.PageUtil;
import com.hai.common.utils.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonConfig;
import com.hai.entity.*;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.goods.model.GoodsModel;
import com.hai.goods.service.DeliveryAddressService;
import com.hai.goods.service.GoodsLogisticsService;
import com.hai.goods.service.GoodsOrderExtService;
import com.hai.goods.service.GoodsSkuService;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.order.model.ExportOrderMobileModel;
import com.hai.order.model.GoodsChildOrderExtModel;
import com.hai.order.model.GoodsOrderExtModel;
import com.hai.order.service.OrderService;
import com.hai.order.type.OrderPayType;
import com.hai.order.type.OrderStatus;
import com.hai.order.type.RechargePlatformType;
import com.hai.service.OutRechargeChildOrderService;
import com.hai.service.OutRechargeOrderService;
import com.web.config.SysConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "goodsOrder")
@Api(value = "实物商品业务")
public class GoodsOrderController {

    private static Logger log = LoggerFactory.getLogger(OrderMobileRechargeController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private OrderService orderService;

    @Resource
    private GoodsOrderExtService goodsOrderExtService;

    @Resource
    private GoodsLogisticsService goodsLogisticsService;

    @Resource
    private DeliveryAddressService deliveryAddressService;

    @Resource
    private RedisUtil redisUtil;

    @RequestMapping(value = "/getOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单列表")
    public ResponseData getOrderList(@RequestParam(name = "orderNo", required = false) String orderNo,
                                     @RequestParam(name = "memPhone", required = false) String memPhone,
                                     @RequestParam(name = "memCardNo", required = false) String memCardNo,
                                     @RequestParam(name = "payType", required = false) Integer payType,
                                     @RequestParam(name = "orderStatus", required = false) Integer orderStatus,
                                     @RequestParam(name = "companyId", required = false) Long companyId,
                                     @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                     @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                     @RequestParam(name = "refundTimeS", required = false) String refundTimeS,
                                     @RequestParam(name = "refundTimeE", required = false) String refundTimeE,
                                     @RequestParam(name = "payTimeS", required = false) Long payTimeS,
                                     @RequestParam(name = "payTimeE", required = false) Long payTimeE,
                                     @RequestParam(name = "productType", required = false) Integer productType,
                                     @RequestParam(name = "finishTimeS", required = false) Long finishTimeS,
                                     @RequestParam(name = "finishTimeE", required = false) Long finishTimeE,
                                     @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                     @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                     HttpServletRequest request) {
        try {

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String,Object> map = new HashMap<>();
            if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type0.getType())) {
                map.put("companyId" , companyId);
            } else if (userInfoModel.getSecUser().getObjectType().equals(UserObjectTypeEnum.type1.getType())) {
                map.put("companyId", userInfoModel.getBsCompany().getId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            map.put("createTimeS", createTimeS);
            map.put("createTimeE", createTimeE);
            map.put("payTimeS", payTimeS);
            map.put("payTimeE", payTimeE);
            map.put("finishTimeS", finishTimeS);
            map.put("finishTimeE", finishTimeE);
            map.put("refundTimeS" , refundTimeS);
            map.put("refundTimeE" , refundTimeE);
            map.put("orderNo", orderNo);
            map.put("memPhone", memPhone);
            map.put("memCardNo", memCardNo);
            map.put("productType", 12);
            map.put("orderStatus", orderStatus);
            map.put("payType", payType);

            List<HighOrder> list = orderService.getOrderList(map);

            List<GoodsOrderExtModel> goodsOrderExtModels = new ArrayList<>();

            GoodsOrderExtModel model;

            for (HighOrder order : list) {
                model = new GoodsOrderExtModel();
                BeanUtils.copyProperties(order, model);
                model.setLogisticsStatus(goodsOrderExtService.findGoodsOrder(order.getOrderNo()).getStatus());
                goodsOrderExtModels.add(model);
            }
            goodsOrderExtModels = goodsOrderExtModels.stream().sorted(Comparator.comparing(GoodsOrderExtModel::getLogisticsStatus)).collect(Collectors.toList());

            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum, goodsOrderExtModels.size(), pageSize, new PageInfo<>(goodsOrderExtModels)));

        } catch (Exception e) {
            log.error("OrderCouponController --> getOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }




    @RequestMapping(value="/getGoodsOrderDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单详情")
    public ResponseData getMobileOrderDetail(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("tradeOrder", orderService.getOrderDetailByNo(orderNo));
            GoodsOrder goodsOrder = goodsOrderExtService.findGoodsOrder(orderNo);
            map.put("goodsOrder", goodsOrder);
            if (goodsOrder.getLogisticsNo() != null) {
                GoodsLogistics logistics = (GoodsLogistics) goodsLogisticsService.getLogisticsMsg(goodsOrder.getLogisticsNo());
                map.put("logistics", logistics);
                JSONArray object = JSONArray.parseArray(logistics.getLogisticsTraceDetails());
                map.put("logisticsTraceDetails",  object);
            }

            return ResponseMsgUtil.success(map);

        } catch (Exception e) {
            log.error("OrderExtController -> getGasOrderDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/updateLogisticsNo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "更新物流订单号")
    public ResponseData updateLogisticsNo(@RequestParam(name = "orderNo", required = true) String orderNo,
                                          @RequestParam(name = "logisticsNo", required = true) String logisticsNo
                                          ) {
        try {

            GoodsOrder goodsOrder = goodsOrderExtService.findGoodsOrder(orderNo);

            if (goodsOrder == null) {
                throw ErrorHelp.genException(SysCode.System , ErrorCode.COMMON_ERROR , "信息错误！");
            }

            goodsOrder.setLogisticsNo(logisticsNo);
            goodsOrder.setUpdateTime(new Date());
            if (Objects.equals(goodsOrder.getStatus(), "1")) {
                goodsOrder.setStatus("2");
            }

            goodsOrderExtService.updateGoodsOrder(goodsOrder);

            return ResponseMsgUtil.success("更新成功！");

        } catch (Exception e) {
            log.error("OrderExtController -> getGasOrderDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/getOrderChildList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询子订单列表")
    public ResponseData getOrderChildList(@RequestParam(name = "orderNo", required = false) String orderNo,
                                          @RequestParam(name = "childOrderNo", required = false) String childOrderNo,
                                     @RequestParam(name = "memPhone", required = false) String memPhone,
                                     @RequestParam(name = "status", required = false) Integer status,
                                     @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                     @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                     @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                     @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                     HttpServletRequest request) {
        try {

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            Map<String,Object> map = new HashMap<>();

            map.put("createTimeS", createTimeS);
            map.put("createTimeE", createTimeE);
            map.put("orderNo", orderNo);
            map.put("secUserId", userInfoModel.getSecUser().getId());
            map.put("childOrderNo", childOrderNo);
            map.put("memPhone", memPhone);
            map.put("status", status);


            List<HighChildOrder> list = orderService.getChildOrderList(map);

            List<GoodsChildOrderExtModel> goodsChildOrderExtModels = new ArrayList<>();

            GoodsChildOrderExtModel model;

            for (HighChildOrder order : list) {
                model = new GoodsChildOrderExtModel();
                BeanUtils.copyProperties(order, model);
                GoodsLogistics logistics = goodsLogisticsService.findGoodsLogistics(order.getId());
                if (logistics != null) {
                    model.setLogisticsStatus(logistics.getLogisticsStatusDesc());
                    model.setLogisticsNo(logistics.getNumber());
                }
                GoodsOrder goodsOrder = goodsOrderExtService.findGoodsOrder(order.getOrderNo());
                GoodsDeliveryAddress deliveryAddress = deliveryAddressService.findDeliveryAddressById(goodsOrder.getDeliveryAddressId());
                model.setDeliveryAddressMsg(goodsOrder.getDeliveryAddress() + "-" +  deliveryAddress.getConsignee() + " " + deliveryAddress.getPhone());
                goodsChildOrderExtModels.add(model);
            }

            return ResponseMsgUtil.success(PageUtil.initPageInfoObj(pageNum, goodsChildOrderExtModels.size(), pageSize, new PageInfo<>(goodsChildOrderExtModels)));

        } catch (Exception e) {
            log.error("OrderCouponController --> getOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/editLogisticsNo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "录入运单号")
    public ResponseData editLogisticsNo(@RequestParam(name = "orderId", required = false) Long orderId,
                                        @RequestParam(name = "logisticsNo", required = false) String logisticsNo
                                        ) {
        try {

            UserInfoModel userInfoModel = userCenter.getSessionModel(UserInfoModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }

            JSONObject jsonObjects = CommonConfig.getLogisticsMsg(logisticsNo);

            jsonObjects.getJSONObject("data").put("orderId" , orderId);

            GoodsLogistics logistics = goodsLogisticsService.editLogistics(jsonObjects.getJSONObject("data"));

            redisUtil.set("logisticsMsg" + orderId , logistics ,21600);

            return ResponseMsgUtil.success("录入成功");

        } catch (Exception e) {
            log.error("OrderCouponController --> getOrderList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }



}
