package com.bweb.controller;

import com.bweb.model.AddGoodsPriceModel;
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.entity.*;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighCouponService;
import com.hai.service.HighGoodsPriceReferService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.math.BigDecimal;
import java.util.*;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/21 20:11
 */
@Controller
@RequestMapping(value = "/highGoodsPriceRefer")
@Api(value = "产品价格配置接口")
public class HighGoodsPriceReferController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighGoodsPriceReferService highGoodsPriceReferService;

    @Resource
    private HighCouponService highCouponService;

    @RequestMapping(value="/insertGoodsPriceRefer",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加产品销售价格")
    public ResponseData insertGoodsPriceRefer(@RequestBody AddGoodsPriceModel addGoodsPriceModel, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (addGoodsPriceModel.getObjectType() == null
                || addGoodsPriceModel.getPriceType() == null
                || addGoodsPriceModel.getPromptlyType() == null
                || addGoodsPriceModel.getObjectIdList() == null
                || addGoodsPriceModel.getObjectIdList().size() == 0
            ) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 价格类型 1：原价  2：折扣
            // 原价需要填写新价格
            if (addGoodsPriceModel.getPriceType() == 1 && addGoodsPriceModel.getNewSalePrice() == null) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","请填写正确的新销售价格");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NEED_WRITE_NEW_SALE_PRICE, "");
            }
            // 折扣需要填写折扣数(几折)
            if (addGoodsPriceModel.getPriceType() == 2
                    && addGoodsPriceModel.getDiscountNum() == null
                    && addGoodsPriceModel.getDiscountNum().compareTo(new BigDecimal("0")) ==  - 1
                    && addGoodsPriceModel.getDiscountNum().compareTo(new BigDecimal("10")) ==  1) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","请填写正确的折扣数,折扣数范围【0】 ~ 【10】");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NEED_WRITE_DISCOUNT_PRICE, "");
            }

            // 失效时间 大于 生效时间
            if (addGoodsPriceModel.getInvalidTime() != null
                    && addGoodsPriceModel.getEffectiveTime() != null
                    && addGoodsPriceModel.getInvalidTime().after(addGoodsPriceModel.getEffectiveTime())) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","失效时间不能大于生效时间");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.INVALID_TIME_BIG_EFFECTIVE_TIME_ERROR, "");
            }


            HighGoodsPriceRefer highGoodsPriceRefer;
            List<HighGoodsPriceRefer> list = new ArrayList<>();

            for (Long objectId : addGoodsPriceModel.getObjectIdList()) {
                highGoodsPriceRefer = new HighGoodsPriceRefer();

                // 卡卷
                if (addGoodsPriceModel.getObjectType() == 1) {
                    HighCoupon coupon = highCouponService.getCouponById(objectId);
                    if (coupon == null) {
                        log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","未找到卡卷信息");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
                    }
                    // 是否满足增加条件
                    if (highGoodsPriceReferService.isAddCondition(addGoodsPriceModel.getObjectType(),coupon.getId(),addGoodsPriceModel.getPriceType()) == false) {
                        log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!", "【" + coupon.getCouponName() + "】，暂时无法增加，有处于在待编辑、待生效、审批中的价格");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.PRICE_REFER_STATUS_ERROR, "");
                    }
                    // 价格类型 1：原价  2：折扣
                    // 获取旧价格
                    if (addGoodsPriceModel.getPriceType() == 1) {
                        highGoodsPriceRefer.setOldSalePrice(coupon.getSalesPrice());
                        highGoodsPriceRefer.setNewSalePrice(addGoodsPriceModel.getNewSalePrice());
                    }
                    if (addGoodsPriceModel.getPriceType() == 2) {
                        highGoodsPriceRefer.setOldSalePrice(coupon.getDiscountPrice());
                        // 卡卷原价 * （折扣 ÷ 10）
                        BigDecimal newSalePrice = coupon.getSalesPrice().multiply(new BigDecimal(addGoodsPriceModel.getDiscountNum().toString()).divide(new BigDecimal("10")));
                        highGoodsPriceRefer.setNewSalePrice(newSalePrice);
                        highGoodsPriceRefer.setDiscountNum(addGoodsPriceModel.getDiscountNum());
                    }
                    highGoodsPriceRefer.setCreateTime(new Date());
                    highGoodsPriceRefer.setStatus(101);   // 状态: 0:删除 1:待编辑  2:待生效  3:已生效  4:已失效  101.审批中  102.审批驳回
                    highGoodsPriceRefer.setOperatorId(userInfoModel.getSecUser().getId());
                    highGoodsPriceRefer.setOperatorName(userInfoModel.getSecUser().getUserName());
                    list.add(highGoodsPriceRefer);
                }

            }
            highGoodsPriceReferService.submitApproveList(list);
            return ResponseMsgUtil.success("操作成功");

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

/*    @RequestMapping(value="/updateGoodsPriceRefer",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改产品销售价格")
    public ResponseData updateGoodsPriceRefer(@RequestBody HighGoodsPriceRefer highGoodsPriceRefer, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (highGoodsPriceRefer.getId() == null
                    || highGoodsPriceRefer.getObjectType() == null
                    || highGoodsPriceRefer.getObjectId() == null
                    || highGoodsPriceRefer.getPromptlyType() == null
                    || highGoodsPriceRefer.getNewSalePrice() == null) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 是否及时生效  否：需要填写生效时间
            if (highGoodsPriceRefer.getPromptlyType() == false && highGoodsPriceRefer.getEffectiveTime() == null) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询价格信息
            HighGoodsPriceRefer refer = highGoodsPriceReferService.getPriceReferById(highGoodsPriceRefer.getId());
            if (refer == null) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","未找到价格信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.GOODS_PRICE_REFER_ERROR, "");
            }

            // 只有审批驳回后才能修改
            if (refer.getStatus() != 102) {
                log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!","状态错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

            refer.setObjectType(highGoodsPriceRefer.getObjectType());
            refer.setObjectId(highGoodsPriceRefer.getObjectId());
            refer.setPromptlyType(highGoodsPriceRefer.getPromptlyType());
            refer.setNewSalePrice(highGoodsPriceRefer.getNewSalePrice());
            refer.setStatus(101);   // 状态: 0:删除 1:待编辑  2:待生效  3:已生效  4:已失效  101.审批中  102.审批驳回
            refer.setOperatorId(userInfoModel.getSecUser().getId());
            refer.setOperatorName(userInfoModel.getSecUser().getUserName());
            highGoodsPriceReferService.updatePriceRefer(refer);

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

        } catch (Exception e) {
            log.error("HighGoodsPriceReferController -> insertGoodsPriceRefer() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }*/

    @RequestMapping(value="/getPriceReferList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询价格列表")
    public ResponseData getPriceReferList(@RequestParam(name = "objectType", required = false) Integer objectType,
                                          @RequestParam(name = "objectId", required = false) Long objectId,
                                          @RequestParam(name = "priceType", required = false) Integer priceType,
                                          @RequestParam(name = "status", required = false) Integer status,
                                          @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                          @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("objectType", objectType);
            map.put("objectId", objectId);
            map.put("priceType", priceType);
            map.put("status", status);

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

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

}
