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.ResponseMsgUtil;
import com.hfkj.entity.BsOrderAfterSalesApply;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.model.UserSessionObject;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.order.BsOrderAfterSalesApplyService;
import com.hfkj.service.order.BsOrderAfterSalesOpRecordService;
import com.hfkj.service.order.BsOrderChildService;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.UserStatusEnum;
import com.hfkj.sysenum.order.OrderAfterSalesApplyTypeEnum;
import com.hfkj.sysenum.order.OrderChildProductTypeEnum;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: OrderAfterSalesApplyController
 * @author: HuRui
 * @date: 2024/5/15
 **/
@Controller
@RequestMapping(value="/afterSales")
@Api(value="订单售后业务")
public class OrderAfterSalesApplyController {
    Logger log = LoggerFactory.getLogger(OrderAfterSalesApplyController.class);
    @Resource
    private UserCenter userCenter;
    @Resource
    private BsOrderAfterSalesApplyService orderAfterSalesApplyService;
    @Resource
    private BsOrderAfterSalesOpRecordService orderAfterSalesOpRecordService;
    @Resource
    private BsOrderChildService orderChildService;

    @RequestMapping(value="/calculate",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "计算预计退款金额")
    public ResponseData calculate(@RequestParam(value = "childOrderNo" , required = true) String childOrderNo,
                                  @RequestParam(value = "productCount" , required = true) Integer productCount) {
        try {
            // 查询子订单
            OrderChildModel orderChild = orderChildService.getDetail(childOrderNo);
            if (orderChild == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商品订单");
            }
            if (productCount > orderChild.getSurplusRefundCount()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "数量超过子订单可退数量");
            }
            Map<String,Object> param = new HashMap<>();
            if (orderChild.getSurplusRefundCount().equals(productCount)) {
                // 全部退款
                param.put("refundPrice", orderChild.getSurplusRefundPrice());
                param.put("refundIntegral", orderChild.getSurplusRefundIntegral());
            } else {
                // 部分退款
                // 计算单价
                BigDecimal unitPrice = orderChild.getSurplusRefundPrice().divide(new BigDecimal(orderChild.getProductCount().toString()), 2, BigDecimal.ROUND_DOWN).setScale(2);
                BigDecimal unitPriceIntegral = new BigDecimal(orderChild.getSurplusRefundIntegral().toString()).divide(new BigDecimal("100"))
                        .divide(new BigDecimal(orderChild.getProductCount().toString()), 2, BigDecimal.ROUND_DOWN).setScale(2);
                param.put("refundPrice", unitPrice.multiply(new BigDecimal(productCount.toString())));
                param.put("refundIntegral", unitPriceIntegral.multiply(new BigDecimal("100")).longValue());
            }
            return ResponseMsgUtil.success(param);

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


    @RequestMapping(value="/apply",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "申请")
    public ResponseData apply(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || body.getInteger("type") == null
                    || StringUtils.isBlank(body.getString("childOrderNo"))
                    || body.getInteger("productCount") == null
                    || StringUtils.isBlank(body.getString("remarks"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 申请类型
            OrderAfterSalesApplyTypeEnum applyType = OrderAfterSalesApplyTypeEnum.getData(body.getInteger("type"));
            if (applyType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的申请类型");
            }

            orderAfterSalesApplyService.createApply(applyType,
                    body.getString("childOrderNo"),
                    body.getInteger("productCount"),
                    body.getString("photo"),
                    body.getString("remarks")
            );
            return ResponseMsgUtil.success("提交成功");

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

    @RequestMapping(value="/audit",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "申请审核")
    public ResponseData audit(@RequestBody JSONObject body) {
        try {
            SecUserSessionObject secUserSessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (secUserSessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            if (body == null
                    || StringUtils.isBlank(body.getString("applyNo"))
                    || body.getBoolean("auditStatus") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            orderAfterSalesApplyService.audit(
                    body.getString("applyNo"),
                    body.getBoolean("auditStatus"),
                    body.getString("remarks"),
                    secUserSessionObject.getAccount().getId());
            return ResponseMsgUtil.success("提交成功");

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

    @RequestMapping(value="/sendExpress",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "邮寄")
    public ResponseData sendExpress(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("applyNo"))
                    || StringUtils.isBlank(body.getString("sendExpressNo"))
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            orderAfterSalesApplyService.sendExpress(body.getString("applyNo"),body.getString("sendExpressNo"));
            return ResponseMsgUtil.success("提交成功");

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

    @RequestMapping(value="/finish",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "完成")
    public ResponseData finish(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("applyNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            SecUserSessionObject secUserSessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (secUserSessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }

            orderAfterSalesApplyService.finish(body.getString("applyNo"), secUserSessionObject.getAccount().getId());
            return ResponseMsgUtil.success("提交成功");

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

    @RequestMapping(value="/queryApply",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询申请")
    public ResponseData queryApply(@RequestParam(value = "applyNo" , required = true) String applyNo) {
        try {
            // 查询申请
            BsOrderAfterSalesApply apply = orderAfterSalesApplyService.getDetailByApplyNo(applyNo);
            if (apply == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的申请");
            }
            Map<String,Object> map = new HashMap<>();
            map.put("applyDetail", apply);
            map.put("childOrder", orderChildService.getDetail(apply.getChildOrderNo()));
            map.put("applyOpRecord", orderAfterSalesOpRecordService.getRecordList(applyNo));
            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value="/queryApplyList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询申请列表")
    public ResponseData queryApplyList(@RequestParam(value = "merId" , required = false) Long merId,
                                       @RequestParam(value = "type" , required = false) Integer type,
                                       @RequestParam(value = "userPhone" , required = false) String userPhone,
                                       @RequestParam(value = "childOrderNo" , required = false) String childOrderNo,
                                       @RequestParam(value = "applyNo" , required = false) String applyNo,
                                       @RequestParam(value = "status" , required = false) Integer status,
                                       @RequestParam(value = "productType" , required = false) String productType,
                                       @RequestParam(value = "productName" , required = false) String productName,
                                       @RequestParam(value = "orderNo" , required = false) String orderNo,
                                       @RequestParam(value = "createTimeS" , required = false) Long createTimeS,
                                       @RequestParam(value = "createTimeE" , required = false) Long createTimeE,
                                       @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                       @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {

            SecUserSessionObject secUserSessionObject = userCenter.getSessionModel(SecUserSessionObject.class);
            if (secUserSessionObject == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
            }
            Map<String,Object> param = new HashMap<>();
            if (secUserSessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type1.getCode())) {
                param.put("merId", merId);
            } else if (secUserSessionObject.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())) {
                param.put("merId", secUserSessionObject.getAccount().getObjectId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知权限");
            }
            param.put("type", type);
            param.put("userPhone", userPhone);
            param.put("childOrderNo", childOrderNo);
            param.put("applyNo", applyNo);
            param.put("status", status);
            param.put("productType", productType);
            param.put("productName", productName);
            param.put("orderNo", orderNo);
            param.put("createTimeS", createTimeS);
            param.put("createTimeE", createTimeE);

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

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

    @RequestMapping(value="/queryUserApplyList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询用户申请列表")
    public ResponseData queryUserApplyList(@RequestParam(value = "childOrderNo" , required = false) String childOrderNo,
                                           @RequestParam(value = "applyNo" , required = false) String applyNo,
                                           @RequestParam(value = "status" , required = false) Integer status,
                                           @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                           @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
            try {

                UserSessionObject userSessionObject = userCenter.getSessionModel(UserSessionObject.class);
                if (userSessionObject == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.ACCOUNT_LOGIN_NOT, "");
                }
                Map<String,Object> param = new HashMap<>();
                param.put("userId", userSessionObject.getUser().getId());
                param.put("childOrderNo", childOrderNo);
                param.put("applyNo", applyNo);
                param.put("status", status);

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

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

}
