package com.bweb.controller.discount;

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.SessionObject;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.OrderUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.discount.CouponDiscountPackageService;
import com.hfkj.service.discount.impl.CouponDiscountServiceImpl;
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 javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/discountPackage")
@Api(value="优惠券包")
public class DiscountPackageController {

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

    @Resource
    private CouponDiscountPackageService couponDiscountPackageService;

    @Resource
    private UserCenter userCenter;

    @Resource
    private CouponDiscountServiceImpl couponDiscountService;

    @RequestMapping(value = "/getDiscountPackageList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取优惠券包列表")
    public ResponseData getDiscountPackageList(
                                               @RequestParam(name = "title", required = false) String title,
                                               @RequestParam(name = "key", required = false) String key,
                                               @RequestParam(name = "status", required = false) Integer status,
                                               @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                               @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {

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

            map.put("title" , title);
            map.put("key" , key);
            map.put("status" , status);

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


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


    @RequestMapping(value = "/getDiscountPackageRecordList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取优惠券包记录列表")
    public ResponseData getDiscountPackageRecordList(@RequestParam(name = "discountPackageId", required = false) Long discountPackageId) {
        try {


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

            map.put("discountPackageId" , discountPackageId);

            return ResponseMsgUtil.success(couponDiscountPackageService.getListRecordByMap(map));

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

    @RequestMapping(value = "/editCouponPackageInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑优惠券包基本信息")
    public ResponseData editCouponPackageInfo(@RequestBody CouponDiscountPackage body, HttpServletRequest request) {
        try {

            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            SecUserSessionObject userModel = (SecUserSessionObject) sessionObject.getObject();

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


            CouponDiscountPackage discountPackage;

            if (body.getId() != null) {
                // 查询
                discountPackage = couponDiscountPackageService.queryDetail(body.getId());
                if (discountPackage == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.CONTENT_NOT_FOUND, "");
                }
            } else {
                discountPackage = new CouponDiscountPackage();
                discountPackage.setCreatedUserId(userModel.getAccount().getId().intValue());
                discountPackage.setKey(OrderUtil.generateOrderNo());
                discountPackage.setStatus(1);
                discountPackage.setTotalStock(0);
                discountPackage.setCreatedTime(new Date());
            }

            discountPackage.setSurplusStock(body.getSurplusStock());
            discountPackage.setTitle(body.getTitle());
            discountPackage.setEffectiveTime(body.getEffectiveTime());
            discountPackage.setUpdatedTime(new Date());
            discountPackage.setUpdatedUserId(userModel.getAccount().getId().intValue());

            if (body.getId() != null) {
                couponDiscountPackageService.update(discountPackage);
            } else {
                couponDiscountPackageService.create(discountPackage);
            }

            return ResponseMsgUtil.success("成功");

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

    @RequestMapping(value = "/insertCouponPackageDetail", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增优惠券包详情")
    public ResponseData insertCouponPackageDetail(@RequestBody CouponDiscountPackageDetails discountPackageDetails, HttpServletRequest request) {
        try {


            if ( discountPackageDetails.getDiscountPackageId() == null
                    || discountPackageDetails.getDiscountId() == null
                    || discountPackageDetails.getNum() == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }


            CouponDiscount discount = couponDiscountService.queryDetail(discountPackageDetails.getDiscountId().longValue());

            if (discount  == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "优惠券不存在!");
            }

            CouponDiscountPackageDetails details = couponDiscountPackageService.discountPackageDetail(discountPackageDetails.getDiscountPackageId() , discountPackageDetails.getDiscountId());


            if (details == null) {
                discountPackageDetails.setStatus(1);
                discountPackageDetails.setDiscountName(discount.getName());
                discountPackageDetails.setDiscountImg(discount.getImg());
                discountPackageDetails.setCreatedTime(new Date());
                discountPackageDetails.setUpdatedTime(new Date());
                couponDiscountPackageService.createDetail(discountPackageDetails);
            } else {
                details.setNum(discountPackageDetails.getNum() + details.getNum());
                details.setUpdatedTime(new Date());
                couponDiscountPackageService.updateDetail(details);
            }

            return ResponseMsgUtil.success("成功");

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

    @RequestMapping(value = "/deleteDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除券包详情")
    public ResponseData deleteDetail(@RequestParam(name = "detailId", required = false) Integer detailId) {
        try {

            couponDiscountPackageService.deleteDetail(detailId);

            return ResponseMsgUtil.success("删除成功！");

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

    @RequestMapping(value = "/getDetailList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "券包详情列表")
    public ResponseData getDetailList(@RequestParam(name = "discountPackageId", required = false) Integer discountPackageId) {
        try {

            return ResponseMsgUtil.success( couponDiscountPackageService.getDetailList(discountPackageId));

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

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除券包")
    public ResponseData delete(@RequestParam(name = "id", required = false) Long id) {
        try {

            couponDiscountPackageService.delete(id , false);

            return ResponseMsgUtil.success("删除成功！");

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

    @RequestMapping(value="/discountPackageAudit",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "券包上下架")
    public ResponseData discountPackageAudit(@RequestParam(value = "id" , required = false) Long id) {
        try {

            CouponDiscountPackage discountPackage = couponDiscountPackageService.queryDetail(id);

            if (discountPackage.getStatus() == 1) {
                discountPackage.setStatus(2);
                discountPackage.setUpdatedTime(new Date());
            } else if (discountPackage.getStatus() == 2) {
                discountPackage.setStatus(3);
                discountPackage.setUpdatedTime(new Date());
            }

            couponDiscountPackageService.update(discountPackage);

            return ResponseMsgUtil.success("成功");

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

    @RequestMapping(value = "/giveDiscountPackage", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "赠送券包")
    public ResponseData giveDiscountPackage(@RequestBody JSONObject body) {
        try {

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

            couponDiscountPackageService.giveDiscountPackage(body.getInteger("discountPackageId") , body.getString("phone"));

            return ResponseMsgUtil.success("成功！");

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