package com.bweb.controller;

import com.alibaba.excel.EasyExcel;
import com.bweb.config.SysConst;
import com.bweb.model.ExportHighOrderModel;
import com.bweb.model.ExportHighPreOrderModel;
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.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.WxOrderConfig;
import com.hai.entity.HighChildOrder;
import com.hai.entity.HighGoodsType;
import com.hai.entity.HighOrder;
import com.hai.entity.HighOrderPre;
import com.hai.model.*;
import com.hai.service.HighOrderPreService;
import com.hai.service.HighOrderService;
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 javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Sum1Dream
 * @ClassName HighOrderPreController
 * @Description // 预约订单
 * @Date 2021/11/19 10:56 上午
 **/
@Controller
@RequestMapping(value = "/highOrderPre")
@Api(value = "预约订单接口")
public class HighOrderPreController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighOrderPreService highOrderPreService;

    @Resource
    private HighOrderService highOrderService;


    @RequestMapping(value = "/getListPreOrder", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取预约订单列表")
    public ResponseData getListGoodsType(@RequestParam(name = "companyId", required = false) Long companyId,
                                         @RequestParam(name = "merchantId", required = false) Long merchantId,
                                         @RequestParam(name = "orderNo", required = false) String orderNo,
                                         @RequestParam(name = "preOrderNo", required = false) String preOrderNo,
                                         @RequestParam(name = "merchantStoreId", required = false) Long merchantStoreId,
                                         @RequestParam(name = "userPhone", required = false) String userPhone,
                                         @RequestParam(name = "preUserName", required = false) String preUserName,
                                         @RequestParam(name = "goodsName", required = false) String goodsName,
                                         @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 {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String,Object> map = new HashMap<>();

            // 用户来源 0：超级管理员  1：公司  2：商户  3：门店 4. 代理商
            if(userInfoModel.getSecUser().getObjectType() == 0) {
                map.put("companyId", companyId);

            } else if (userInfoModel.getSecUser().getObjectType() == 1) {
                if (userInfoModel.getBsCompany().getId() == 3) {
                    map.put("companyId", 23);
                } else if (userInfoModel.getBsCompany().getId() == 2) {
                    map.put("companyId", null);
                }else {
                    map.put("companyId", userInfoModel.getBsCompany().getId());
                }

            } else if (userInfoModel.getSecUser().getObjectType() == 2) {
                merchantId = userInfoModel.getMerchant().getId();
            } else if (userInfoModel.getSecUser().getObjectType() == 3) {
                merchantStoreId = userInfoModel.getMerchantStore().getId();
            }

            map.put("merchantId", merchantId);
            map.put("merchantStoreId" , merchantStoreId);
            map.put("orderNo" , orderNo);
            map.put("preOrderNo" , preOrderNo);
            map.put("userPhone" , userPhone);
            map.put("preUserName" , preUserName);
            map.put("goodsName" , goodsName);
            map.put("status" , status);
            if (createTimeS != null) {
                map.put("createTimeS", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeS));
            }
            if (createTimeE != null) {
                map.put("createTimeE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeE));
            }

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highOrderPreService.getListOrderPre(map)));

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

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

            return ResponseMsgUtil.success(highOrderPreService.findByOrderId(id));

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

    @RequestMapping(value = "/preOrderSuccess", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "预约成功")
    public ResponseData preOrderSuccess(@RequestBody HighOrderPre highOrderPre, HttpServletRequest request) {
        try {
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();


            if (StringUtils.isBlank(highOrderPre.getPreUserRemark())
                    || highOrderPre.getReachTime() == null
                    || highOrderPre.getId() == null
                    || StringUtils.isBlank(highOrderPre.getReachAddress())
            ) {
                log.error("HighAgentController -> insertAgent() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighOrderPre highOrderPres = highOrderPreService.findByOrderId(highOrderPre.getId());

            // 校验订单是否合法
            if (highOrderPres == null || highOrderPres.getStatus() != 1) {
                log.error("HighGoodsTypeController --> preOrderSuccess() error!", "当前状态不合法");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

            highOrderPres.setUpdateTime(new Date());
            highOrderPres.setOpUserId(userInfoModel.getSecUser().getId());
            highOrderPres.setOpUserName(userInfoModel.getSecUser().getUserName());
            highOrderPres.setPreUserRemark(highOrderPre.getPreUserRemark());
            highOrderPres.setReachTime(highOrderPre.getReachTime());
            highOrderPres.setReachAddress(highOrderPre.getReachAddress());
            highOrderPres.setStatus(2);
            highOrderPreService.updateOrderPre(highOrderPres);

            return ResponseMsgUtil.success("预约成功");

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

    @RequestMapping(value = "/preOrderFail", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "预约失败")
    public ResponseData preOrderFail(@RequestBody HighOrderPre highOrderPre, HttpServletRequest request) {
        try {
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();


            if (StringUtils.isBlank(highOrderPre.getStatusFailDesc())
                    || highOrderPre.getId() == null
            ) {
                log.error("HighAgentController -> insertAgent() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighOrderPre highOrderPres = highOrderPreService.findByOrderId(highOrderPre.getId());

            // 校验订单是否合法
            if (highOrderPres == null && highOrderPres.getStatus() != 1) {
                log.error("HighGoodsTypeController --> preOrderSuccess() error!", "当前状态不合法");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

            highOrderPres.setUpdateTime(new Date());
            highOrderPres.setOpUserId(userInfoModel.getSecUser().getId());
            highOrderPres.setOpUserName(userInfoModel.getSecUser().getUserName());
            highOrderPres.setStatusFailDesc(highOrderPre.getStatusFailDesc());

            highOrderPres.setStatus(4);
            highOrderPreService.updateOrderPre(highOrderPres);

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

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

    @RequestMapping(value = "/exportListPreOrder", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出预约订单列表")
    public ResponseData exportListGoodsType(@RequestParam(name = "companyId", required = false) Long companyId,
                                         @RequestParam(name = "merchantId", required = false) Long merchantId,
                                         @RequestParam(name = "orderNo", required = false) String orderNo,
                                         @RequestParam(name = "preOrderNo", required = false) String preOrderNo,
                                         @RequestParam(name = "merchantStoreId", required = false) Long merchantStoreId,
                                         @RequestParam(name = "userPhone", required = false) String userPhone,
                                         @RequestParam(name = "preUserName", required = false) String preUserName,
                                         @RequestParam(name = "goodsName", required = false) String goodsName,
                                         @RequestParam(name = "status", required = false) Integer status,
                                         @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                         @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                         HttpServletRequest request) {
        try {

            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            Map<String,Object> map = new HashMap<>();

            // 用户来源 0：超级管理员  1：公司  2：商户  3：门店 4. 代理商
            if(userInfoModel.getSecUser().getObjectType() == 0) {
                map.put("companyId", companyId);

            } else if (userInfoModel.getSecUser().getObjectType() == 1) {
                if (userInfoModel.getBsCompany().getId() == 3) {
                    map.put("companyId", 23);
                } else if (userInfoModel.getBsCompany().getId() == 2) {
                    map.put("companyId", null);
                }else {
                    map.put("companyId", userInfoModel.getBsCompany().getId());
                }

            } else if (userInfoModel.getSecUser().getObjectType() == 2) {
                merchantId = userInfoModel.getMerchant().getId();
            } else if (userInfoModel.getSecUser().getObjectType() == 3) {
                merchantStoreId = userInfoModel.getMerchantStore().getId();
            }

            map.put("merchantId", merchantId);
            map.put("merchantStoreId" , merchantStoreId);
            map.put("orderNo" , orderNo);
            map.put("preOrderNo" , preOrderNo);
            map.put("userPhone" , userPhone);
            map.put("preUserName" , preUserName);
            map.put("goodsName" , goodsName);
            map.put("status" , status);
            if (createTimeS != null) {
                map.put("createTimeS", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeS));
            }
            if (createTimeE != null) {
                map.put("createTimeE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createTimeE));
            }

            String name = "/goodsOrder/预约商品订单" + System.currentTimeMillis() + ".xlsx";
            List<HighOrderPreModel> list = highOrderPreService.ExportPreOrderList(map);
            String fileName = SysConst.getSysConfig().getFileUrl() + name;
            EasyExcel.write(fileName, ExportHighPreOrderModel.class).sheet("预约商品订单").doWrite(list);
            return ResponseMsgUtil.success(name);

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

    @RequestMapping(value = "/orderToRefund", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "订单退款")
    public ResponseData orderToRefund(@RequestParam(name = "orderId", required = false) Long orderId,
                                      HttpServletRequest request) {
        try {

            HighOrderPre highOrderPre = highOrderPreService.findByOrderId(orderId);

            HighChildOrder highChildOrder = highOrderService.getChildOrderById(highOrderPre.getChildOrderId());

            HighOrder highOrder = highOrderService.getOrderById(orderId);

            if (highOrder == null) {
                log.error("orderToRefund error!", "未找到订单");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到订单");
            }

            if (highOrder.getOrderStatus() != 6) {
                log.error("orderToRefund error!", "无法退款，订单不处于退款中状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法退款，订单不处于退款中状态");
            }

            highOrderPreService.orderToRefund(highChildOrder , highOrder , highOrderPre);

            return ResponseMsgUtil.success("退款成功");

        }  catch (Exception e){
            throw new RuntimeException(e);
        }
    }

}
