package com.web.controller;

import com.alibaba.excel.EasyExcel;
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.RedisUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.*;
import com.hai.enum_type.UserObjectTypeEnum;
import com.hai.goods.service.DeliveryAddressService;
import com.hai.goods.service.GoodsLogisticsService;
import com.hai.goods.service.GoodsOrderExtService;
import com.hai.model.GoodsOrderModel;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.order.model.CreateOrderChildModel;
import com.hai.order.model.CreateOrderModel;
import com.hai.order.model.ExportOrderMobileModel;
import com.hai.order.model.ExportOrderModel;
import com.hai.order.service.OrderService;
import com.hai.order.type.OrderChildGoodsType;
import com.hai.order.type.OrderPayType;
import com.hai.order.type.OrderStatus;
import com.hai.order.type.RechargePlatformType;
import com.hai.order.utils.OrderUtil;
import com.hai.service.HighOrderService;
import com.hai.service.HighUserService;
import com.web.config.SysConst;
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.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "")
@Api(value = "订单业务")
public class OrderController {

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

    @Resource
    private OrderService orderService;

    @Resource
    private UserCenter userCenter;

    @Resource
    private GoodsOrderExtService goodsOrderExtService;

    @Resource
    private DeliveryAddressService deliveryAddressService;

    @Resource
    private GoodsLogisticsService goodsLogisticsService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private HighUserService highUserService;

    @RequestMapping(value="/create",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "创建订单")
    public ResponseData create(@RequestBody CreateOrderModel body) {
        try {
            System.out.println("=================" + JSONObject.toJSONString(body));
            // 用户信息
            HighUserModel userModel = userCenter.getSessionModel(HighUserModel.class);
            if (userModel == null) {
                log.error("OrderController -> create() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USE_VISIT_ILLEGAL, "");
            }
            if (StringUtils.isBlank(userModel.getHighUser().getPhone())) {
                log.error("OrderController -> create() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NO_BIND_PHONE, "");
            }
            body.setMemId(userModel.getHighUser().getId());
            body.setMemName(userModel.getHighUser().getName());
            body.setMemPhone(userModel.getHighUser().getPhone());

            if (body.getChildOrderList() == null || body.getChildOrderList().size() == 0) {
                log.error("OrderController -> create() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            for (CreateOrderChildModel childModel : body.getChildOrderList()) {

                childModel.setMemId(body.getMemId());
                childModel.setMemName(body.getMemName());
                childModel.setMemPhone(body.getMemPhone());

                // 校验子订单参数
                if (childModel.getGoodsType() == null
                        || OrderChildGoodsType.getDataByType(childModel.getGoodsType()) == null
                        || childModel.getGoodsId() == null
                        || childModel.getSaleCount() == null) {
                    log.error("OrderController -> create() error!","");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }

                if (childModel.getGoodsType().equals(OrderChildGoodsType.TYPE1.getNumber())
                        || childModel.getGoodsType().equals(OrderChildGoodsType.TYPE8.getNumber())) {
                    if (childModel.getGoodsPrice() == null) {
                        log.error("OrderController -> create() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未填写充值金额");
                    }

                } else if (childModel.getGoodsType().equals(OrderChildGoodsType.TYPE3.getNumber())) {
                    if (childModel.getGoodsPrice() == null || childModel.getGasOilNo() == null || childModel.getGasGunNo() == null) {
                        log.error("OrderController -> create() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未填写加油信息；加油金额、油号、抢号");
                    }
                } else if (childModel.getGoodsType().equals(OrderChildGoodsType.TYPE6.getNumber())) {
                    if (childModel.getRechargeContent() == null) {
                        log.error("OrderController -> create() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请输入充值内容！");
                    }
                } else if (childModel.getGoodsType().equals(OrderChildGoodsType.TYPE4.getNumber()) || childModel.getGoodsType().equals(OrderChildGoodsType.TYPE9.getNumber())|| childModel.getGoodsType().equals(OrderChildGoodsType.TYPE10.getNumber())) {
                    if (childModel.getCustomerMobile() == null) {
                        log.error("OrderController -> create() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请输入下单手机号！");
                    }
                } else if (childModel.getGoodsType().equals(OrderChildGoodsType.TYPE11.getNumber())) {
                    if (childModel.getSkuId() == null) {
                        log.error("OrderController -> create() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请选择规格！");
                    }
                    if (body.getDeliveryAddressId() == null) {
                        log.error("OrderController -> create() error!","");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "请选择收货地址！");
                    }

                }
            }

            body.setOrderNo(OrderUtil.generateOrderNo());
            return ResponseMsgUtil.success(orderService.createOrder(body));

        } catch (Exception e) {
            log.error("OrderController -> create() 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.COMMON_ERROR, "未找到订单");
            }

            String orderNo = body.getString("orderNo");
            String remarks = body.getString("remarks");

            // 查询订单
            HighOrder order = orderService.getOrderDetailByNo(orderNo);
            if (order == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单");
            }
            return ResponseMsgUtil.success(orderService.cancelOrder(order, remarks));

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

    @RequestMapping(value="/getDetailByOrderNo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据订单号查询详情")
    public ResponseData getDetailByOrderNo(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {

            HighOrder highOrder = orderService.getOrderDetailByNo(orderNo);

            if (highOrder.getProductType() == 12) {


                // todo 临时代码

                for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {

                    GoodsLogistics logistics = goodsLogisticsService.findGoodsLogistics(childOrder.getId());
                    if (logistics != null) {
                        childOrder.setExt6(logistics.getLogisticsStatusDesc());
                        childOrder.setExt4(logistics.getNumber());
                    }

                }


                GoodsOrder order = goodsOrderExtService.findGoodsOrder(highOrder.getOrderNo());
                GoodsDeliveryAddress deliveryAddress = deliveryAddressService.findDeliveryAddressById(order.getDeliveryAddressId());

                GoodsOrderModel goodsOrderModel = new GoodsOrderModel();
                BeanUtils.copyProperties(highOrder , goodsOrderModel);
                goodsOrderModel.setGoodsOrder(order);
                goodsOrderModel.setGoodsDeliveryAddress(deliveryAddress);


                return ResponseMsgUtil.success(goodsOrderModel);

            }

            return ResponseMsgUtil.success(highOrder);

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

    @RequestMapping(value="/getUserOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户订单列表")
    public ResponseData getUserOrderList(@RequestParam(name = "title", required = false) String title,
                                         @RequestParam(name = "searchTitle", required = false) String searchTitle,
                                         @RequestParam(name = "orderNo", required = false) String orderNo,
                                         @RequestParam(name = "productType", required = false) Integer productType,
                                         @RequestParam(name = "status", required = false) Integer status,
                                         @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                         @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            HighUserModel userModel = userCenter.getSessionModel(HighUserModel.class);
            if (userModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.USE_VISIT_ILLEGAL, "");
            }
            
            Map<String, Object> param = new HashMap<>();
            param.put("userId", userModel.getHighUser().getId());
            param.put("title", title);
            param.put("searchTitle", searchTitle);
            param.put("orderNo", orderNo);
            param.put("productType", productType);
            param.put("orderStatus", status);

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

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

    @RequestMapping(value = "/orderCheck", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据订单号查看订单")
    public ResponseData orderCheck(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {

            orderService.orderCheck(orderNo);

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

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

    @RequestMapping(value="/getPopularizeUserOrderList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取推广用户订单列表")
    public ResponseData getPopularizeUserOrderList(@RequestParam(name = "promoteCode", required = true) String promoteCode) {
        try {

            Map<String, Object> param = new HashMap<>();
            param.put("promoteCode", promoteCode);
            param.put("orderStatus", 3);

            return ResponseMsgUtil.success(orderService.getOrderList(param));

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

    @RequestMapping(value = "/exportPopularizeUserOrderList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出推广用户订单")
    public ResponseData exportPopularizeUserOrderList(@RequestParam(name = "serialNumber", required = false) String serialNumber,
                                                      @RequestParam(name = "promoteCode", required = true) String promoteCode) {
        try {

            Map<String, Object> param = new HashMap<>();
            param.put("promoteCode", promoteCode);
            param.put("orderStatus", 3);

            // 查询数据
            List<HighOrder> order = orderService.getOrderList(param);

            List<ExportOrderModel> list = new ArrayList<>();

            // 配置初始化处理条数
            int i = 0;
            int percent;

            ExportOrderModel model;
            for (HighOrder highOrder : order) {

                i++;

                // 生成百分比
                percent = i*100/order.size();

                redisUtil.set(serialNumber , percent , 3600);

                model = new ExportOrderModel();

                HighUser user = highUserService.findByUserId(Long.valueOf(highOrder.getPromoteCode()));

                if (user != null) {
                    model.setUserName(user.getName());
                }

                model.setFinishTime(highOrder.getFinishTime());
                model.setMemPhone(highOrder.getMemPhone());
                model.setCreateTime(highOrder.getCreateTime());
                model.setTitle(highOrder.getTitle());
                model.setPayablePrice(highOrder.getPayablePrice());
                model.setPayPrice(highOrder.getPayPrice());
                model.setOrderNo(highOrder.getOrderNo());

                list.add(model);
            }

            String fileUrl = SysConst.getSysConfig().getFileUrl() + "temporary/";
            String pathName = System.currentTimeMillis()+".xlsx";
            File file = new File(fileUrl);
            if (!file.exists()) {
                file.mkdirs();
            }

            EasyExcel.write(fileUrl+pathName)
                    .head(ExportOrderModel.class)
                    .sheet("推广用户交易订单")
                    .doWrite(list);

            redisUtil.set(serialNumber + "download" , pathName , 60);
            return ResponseMsgUtil.success(pathName);

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


}
