package com.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.PageUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.common.utils.SignatureUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsOrder;
import com.hfkj.entity.BsOrderChild;
import com.hfkj.entity.BsOrderGoods;
import com.hfkj.entity.GoodsSpecs;
import com.hfkj.haioil.HaiOilService;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserSessionObject;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.goods.BsOrderGoodsService;
import com.hfkj.service.goods.GoodsSpecsService;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.service.order.impl.BsOrderChildServiceImpl;
import com.hfkj.service.pay.HuiPayService;
import com.hfkj.sysenum.UserStatusEnum;
import com.hfkj.sysenum.order.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @className: OrderController
 * @author: HuRui
 * @date: 2024/4/30
 **/
@Controller
@RequestMapping(value="/")
@Api(value="订单业务")
public class OrderController {

    Logger log = LoggerFactory.getLogger(OrderController.class);
    @Resource
    private UserCenter userCenter;
    @Resource
    private BsOrderService orderService;
    @Resource
    private BsOrderChildServiceImpl orderChildService;
    @Resource
    private GoodsSpecsService goodsSpecsService;
    @Resource
    private BsOrderGoodsService orderGoodsService;

    @RequestMapping(value="/create",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "创建订单")
    public ResponseData create(@RequestBody OrderModel body) {
        try {

            System.out.println("body" + body.toString());
            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);
            if (userSession == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            if (!userSession.getUser().getStatus().equals(UserStatusEnum.status1.getCode())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该账户已被禁用，无法进行交易");
            }
            if (body == null || body.getOrderChildList().isEmpty()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 子订单必填项校验
            for (OrderChildModel orderChild : body.getOrderChildList()) {
                if (orderChild.getProductType() == null
                  ) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                if ((orderChild.getProductType().equals(OrderChildProductTypeEnum.type1.getCode())
                        || orderChild.getProductType().equals(OrderChildProductTypeEnum.type2.getCode()))
                    && orderChild.getProductSpecId() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            }

            body.setUserId(userSession.getUser().getId());
            body.setUserName(userSession.getUser().getName());
            body.setUserPhone(userSession.getUser().getPhone());

            return ResponseMsgUtil.success(orderService.create(body));

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

    @RequestMapping(value="/cancel",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "取消订单")
    public ResponseData cancel(@RequestBody JSONObject body) {
        try {

            if (body == null|| StringUtils.isBlank(body.getString("orderNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            return ResponseMsgUtil.success(orderService.cancel(body.getString("orderNo"), false));

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

    @RequestMapping(value="/queryOrder",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询订单")
    public ResponseData queryOrder(@RequestParam(value = "orderNo" , required = true) String orderNo) {
        try {

            return ResponseMsgUtil.success(orderService.getDetail(orderNo));

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

    @RequestMapping(value="/queryUserOrder",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询用户订单")
    public ResponseData queryUserOrder(@RequestParam(value = "orderNo" , required = false) String orderNo,
                                       @RequestParam(value = "orderStatus" , required = false) Integer orderStatus,
                                       @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                       @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);
            if (userSession == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            Map<String,Object> param = new HashMap<>();
            param.put("userId", userSession.getUser().getId());
            param.put("orderNo", orderNo);
            param.put("orderStatus", orderStatus);

            PageHelper.startPage(pageNum, pageSize);
            PageInfo<BsOrder> pageInfo = new PageInfo<>(orderService.getOrderList(param));
            PageInfo<OrderModel> objectPageInfo = PageUtil.PageInfo2PageInfoVo(pageInfo);
            List<OrderModel> orderModelList = new ArrayList<>();
            for (BsOrder order : pageInfo.getList()) {
                orderModelList.add(orderService.getDetail(order.getOrderNo()));
            }
            objectPageInfo.setList(orderModelList);
            return ResponseMsgUtil.success(objectPageInfo);

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

    @RequestMapping(value="/queryOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询交易订单列表")
    public ResponseData queryOrderList(@RequestParam(value = "orderNo" , required = false) String orderNo,
                                       @RequestParam(value = "userPhone" , required = false) String userPhone,
                                       @RequestParam(value = "payChannel" , required = false) Integer payChannel,
                                       @RequestParam(value = "payType" , required = false) Integer payType,
                                       @RequestParam(value = "createTimeS" , required = false) Long createTimeS,
                                       @RequestParam(value = "createTimeE" , required = false) Long createTimeE,
                                       @RequestParam(value = "payTimeS" , required = false) Long payTimeS,
                                       @RequestParam(value = "payTimeE" , required = false) Long payTimeE,
                                       @RequestParam(value = "finishTimeS" , required = false) Long finishTimeS,
                                       @RequestParam(value = "finishTimeE" , required = false) Long finishTimeE,
                                       @RequestParam(value = "cancelTimeS" , required = false) Long cancelTimeS,
                                       @RequestParam(value = "cancelTimeE" , required = false) Long cancelTimeE,
                                       @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                       @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {

            Map<String,Object> param = new HashMap<>();
            param.put("orderNo", orderNo);
            param.put("userPhone", userPhone);
            param.put("payChannel", payChannel);
            param.put("payType", payType);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);
            param.put("payTimeS", payTimeS);
            param.put("payTimeE", payTimeE);
            param.put("finishTimeS", finishTimeS);
            param.put("finishTimeE", finishTimeE);
            param.put("cancelTimeS", cancelTimeS);
            param.put("cancelTimeE", cancelTimeE);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(orderService.getOrderList(param)));

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


    @RequestMapping(value="/orderNum",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "订单数量")
    public ResponseData orderNum() {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            Map<String , Object> map = new HashMap<>();
            map.put("userId" , userSession.getUser().getId());

            List<BsOrder> bsOrder = orderService.getOrderList(map);

            Map<Integer, List<BsOrder>> collect = bsOrder.stream().collect(Collectors.groupingBy(BsOrder::getOrderStatus));

            List<JSONObject> countRecords = collect.keySet().stream().map(key -> {
                JSONObject goodObject = new JSONObject(true);
                goodObject.put("name", OrderStatusEnum.getData(key).getName());
                goodObject.put("status", key);
                goodObject.put("num",collect.get(key).size());
                return goodObject;
            }).collect(Collectors.toList());

            return ResponseMsgUtil.success(countRecords);

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

    @RequestMapping(value="/deleteOrder",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除订单")
    public ResponseData deleteOrder(@RequestBody JSONObject body) {
        try {

            if (body == null|| StringUtils.isBlank(body.getString("orderNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsOrder bsOrder = orderService.getDetail(body.getString("orderNo"));

            if (bsOrder.getOrderStatus() != OrderStatusEnum.status5.getCode()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态不可删除！");
            }

            bsOrder.setOrderStatus(OrderStatusEnum.status0.getCode());
            bsOrder.setUpdateTime(new Date());

            orderService.deleteOrder(bsOrder);

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/completeActivation",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "完成激活")
    public ResponseData completeActivation(@RequestBody JSONObject body) {
        try {

            if (body == null|| StringUtils.isBlank(body.getString("childOrderNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsOrderChild bsOrderChild = orderChildService.getDetail(body.getString("childOrderNo"));

            if (bsOrderChild.getStatus() != OrderChildStatusEnum.status2.getCode()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前状态不可完成激活！");
            }
            // 子订单完成
            orderService.childOrderComplete(bsOrderChild.getChildOrderNo());

            // 赠送优惠券包
            GoodsSpecs goodsSpecs = goodsSpecsService.queryDetailByGoodsId(bsOrderChild.getProductSpecId());

            BsOrderGoods orderGoods = orderGoodsService.findGoodsOrderByChild(bsOrderChild.getChildOrderNo());

            Map<String , Object> map = new HashMap<>();
            map.put("discountPkNo" , goodsSpecs.getExt1());
            map.put("number" , bsOrderChild.getProductCount());
            map.put("phone" , orderGoods.getUserPhone());
            HaiOilService.pushPk(map);

            return ResponseMsgUtil.success("操作成功");

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

    @RequestMapping(value="/haiOilLogin",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "嗨加油登陆参数")
    public ResponseData haiOilLogin(@RequestBody JSONObject body) {
        try {

            if (body == null|| StringUtils.isBlank(body.getString("phone"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            Map<String , Object> map = new HashMap<>();
            map.put("appId" , CommonSysConst.getSysConfig().getHaiOilAppid());
            map.put("phone" , body.getString("phone"));
            map.put("sign" , SignatureUtil.createSign(map , CommonSysConst.getSysConfig().getHaiOilAppSecret()));

            return ResponseMsgUtil.success(map);

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

}
