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.ResponseMsgUtil;
import com.hfkj.entity.CouponDiscount;
import com.hfkj.entity.CouponDiscountGoodsRel;
import com.hfkj.entity.GoodsMsg;
import com.hfkj.entity.GoodsSpecs;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.model.discount.DiscountGoodsModel;
import com.hfkj.service.discount.CouponDiscountService;
import com.hfkj.service.goods.impl.GoodsMsgServiceImpl;
import com.hfkj.service.goods.impl.GoodsSpecsServiceImpl;
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.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.util.*;

@Controller
@RequestMapping(value="/discount")
@Api(value="优惠券")
public class DiscountController {

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

    @Resource
    private CouponDiscountService couponDiscountService;

    @Resource
    private UserCenter userCenter;
    @Autowired
    private GoodsMsgServiceImpl goodsMsgService;
    @Autowired
    private GoodsSpecsServiceImpl goodsSpecsService;

    @RequestMapping(value="/editDiscount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑优惠券")
    public ResponseData editDiscount(@RequestBody CouponDiscount body, HttpServletRequest request) {

        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            SecUserSessionObject userModel = (SecUserSessionObject) sessionObject.getObject();

            if (body == null
                    || body.getImg() == null
                    || body.getType() == null
                    || body.getEffectiveNum() == null
                    || body.getEffectiveDay() == null
                    || body.getPlatformCode() == null
                    || body.getSalesEndTime() == null
                    || StringUtils.isBlank(body.getName())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            if (body.getType() == 1 ){
                if ( body.getCondition() == null || body.getPrice() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            }
            if (body.getType() == 2 ){
                if (body.getPrice() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            }
            if (body.getType() == 3){
                if ( body.getPercentage() == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            }

            CouponDiscount couponDiscount;

            if (body.getId() != null) {
                // 查询品牌
                couponDiscount = couponDiscountService.queryDetail(body.getId());
                if (couponDiscount == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.CONTENT_NOT_FOUND, "");
                }
            } else {
                couponDiscount = new CouponDiscount();
                couponDiscount.setCreateTime(new Date());
                couponDiscount.setLimitNum(0);
            }

            couponDiscount.setUpdateTime(new Date());
            couponDiscount.setStatus(1);
            couponDiscount.setType(body.getType());
            couponDiscount.setEffectiveNum(body.getEffectiveNum());
            couponDiscount.setName(body.getName());
            couponDiscount.setPlatformCode(body.getPlatformCode());
            couponDiscount.setPercentage(body.getPercentage());
            couponDiscount.setPrice(body.getPrice());
            couponDiscount.setCondition(body.getCondition());
            couponDiscount.setSalesEndTime(body.getSalesEndTime());
            couponDiscount.setEffectiveDay(body.getEffectiveDay());
            couponDiscount.setImg(body.getImg());
            couponDiscount.setOpId(userModel.getAccount().getId());
            couponDiscount.setOpName(userModel.getAccount().getUserName());

            if (body.getId() != null) {
                couponDiscountService.update(couponDiscount);
            } else {
                couponDiscountService.create(couponDiscount);
            }

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/getListDiscount",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询列表")
    public ResponseData getListDiscount(@RequestParam(value = "name" , required = false) String name,
                                      @RequestParam(value = "type" , required = false) Integer type,
                                      @RequestParam(value = "status" , required = false) Integer status,
                                      @RequestParam(value = "platformCode" , required = false) String platformCode,
                                     @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                     @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {

            Map<String , Object> map = new HashMap<>();
            map.put("name", name);
            map.put("type", type);
            map.put("status", status);
            map.put("platformCode", platformCode);

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

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

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

            couponDiscountService.delete(id , false);

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

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

    @RequestMapping(value="/getListDiscountGoodsRel",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询列表")
    public ResponseData getListDiscountGoodsRel(@RequestParam(value = "discountId" , required = false) Long discountId) {
        try {

            Map<String , Object> map = new HashMap<>();
            map.put("discountId", discountId);

            List<CouponDiscountGoodsRel> list = couponDiscountService.getListGoodsRel(map);

            List<DiscountGoodsModel> discountGoodsModelList = new ArrayList<>();


            for (CouponDiscountGoodsRel goodsRel : list) {
                DiscountGoodsModel discountGoodsModel = new DiscountGoodsModel();
                GoodsSpecs goodsSpecs = goodsSpecsService.queryDetail(goodsRel.getSpecsId());
                GoodsMsg goodsMsg = goodsMsgService.queryDetail(goodsSpecs.getGoodsId());

                BeanUtils.copyProperties(goodsRel, discountGoodsModel);
                discountGoodsModel.setSalePrice(goodsSpecs.getSalePrice());
                discountGoodsModel.setGoodsName(goodsMsg.getTitle());
                discountGoodsModel.setSpecsName(goodsSpecs.getName());
                discountGoodsModelList.add(discountGoodsModel);
            }

            return ResponseMsgUtil.success(discountGoodsModelList);

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

    @RequestMapping(value="/bindDiscountSpecs",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "绑定优惠券规格")
    public ResponseData bindDiscountSpecs(@RequestBody JSONObject body) {

        try {

            if (body == null
                    || body.getLong("discountId") == null
                    || StringUtils.isBlank(body.getString("specsIds"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            couponDiscountService.deleteDiscountGoodsRelDiscountId(body.getLong("discountId"));

            String[] specsIds = body.getString("specsIds").split(",");

            for (String specsId : specsIds) {
                CouponDiscountGoodsRel goodsRel = new CouponDiscountGoodsRel();
                goodsRel.setDiscountId(body.getLong("discountId"));
                goodsRel.setSpecsId(Long.valueOf(specsId));
                goodsRel.setCreateTime(new Date());
                goodsRel.setStatus(1);

                couponDiscountService.createGoodsRel(goodsRel);
            }

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }

    }


}
