package com.bweb.controller;

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.DateUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighDiscount;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighDiscountService;
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.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/4/3 22:26
 */
@Controller
@RequestMapping(value = "/discount")
@Api(value = "优惠券接口")
public class HighDiscountController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighDiscountService highDiscountService;

    @RequestMapping(value="/insertDiscount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加优惠券")
    public ResponseData insertDiscount(@RequestBody HighDiscount highDiscount, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighDiscountController -> insertDiscount() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            if (StringUtils.isBlank(highDiscount.getDiscountName())
                    || StringUtils.isBlank(highDiscount.getDiscountImg())
                    || highDiscount.getDiscountType() == null
                    || highDiscount.getDiscountPrice() == null
                    || highDiscount.getEffectiveDay() == null
                    || highDiscount.getReceiveNumber() == null
                    || highDiscount.getUseScope() == null
                    || highDiscount.getSalesEndTime() == null) {
                log.error("HighDiscountController -> insertDiscount() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 卡卷类型  1：满减  2：抵扣   3：折扣
            if(highDiscount.getDiscountType() == 1 && highDiscount.getDiscountCondition() == null) {
                log.error("HighDiscountController -> insertDiscount() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 计算销售截止时间
            Calendar salesEndTime = Calendar.getInstance();
            salesEndTime.setTime(highDiscount.getSalesEndTime());
            salesEndTime.set(Calendar.HOUR_OF_DAY, 23);
            salesEndTime.set(Calendar.MINUTE, 59);
            salesEndTime.set(Calendar.SECOND, 59);
            highDiscount.setSalesEndTime(salesEndTime.getTime());

            highDiscount.setDiscountKey(DateUtil.date2String(new Date(), "yyyyMMddHHmmss"));
            highDiscount.setCompanyId(userInfoModel.getBsCompany().getId());
            highDiscount.setOperatorId(userInfoModel.getSecUser().getId());
            highDiscount.setOperatorName(userInfoModel.getSecUser().getUserName());
            highDiscount.setCreateTime(new Date());
            highDiscount.setUpdateTime(new Date());
            highDiscount.setStatus(1);
            highDiscountService.insertDiscount(highDiscount);

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

    @RequestMapping(value="/updateDiscount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改优惠券")
    public ResponseData updateDiscount(@RequestBody HighDiscount highDiscount, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighDiscountController -> updateDiscount() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            if (highDiscount.getId() == null
                    || StringUtils.isBlank(highDiscount.getDiscountName())
                    || StringUtils.isBlank(highDiscount.getDiscountImg())
                    || highDiscount.getReceiveNumber() == null
                    || highDiscount.getEffectiveDay() == null
                    || highDiscount.getSalesEndTime() == null) {
                log.error("HighDiscountController -> updateDiscount() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询优惠券
            HighDiscount discount = highDiscountService.getDiscountById(highDiscount.getId());
            if (discount == null) {
                log.error("HighDiscountController -> updateDiscount() error!","未找到优惠券信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_DISCOUNT, "");
            }
            // 计算销售截止时间
            Calendar salesEndTime = Calendar.getInstance();
            salesEndTime.setTime(highDiscount.getSalesEndTime());
            salesEndTime.set(Calendar.HOUR_OF_DAY, 23);
            salesEndTime.set(Calendar.MINUTE, 59);
            salesEndTime.set(Calendar.SECOND, 59);

            discount.setSalesEndTime(salesEndTime.getTime());
            discount.setDiscountName(highDiscount.getDiscountName());
            discount.setDiscountImg(highDiscount.getDiscountImg());
            discount.setDiscountCarouselImg(highDiscount.getDiscountCarouselImg());
            discount.setEffectiveDay(highDiscount.getEffectiveDay());
            discount.setUpdateTime(new Date());
            highDiscountService.updateDiscount(highDiscount);

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


    @RequestMapping(value="/updateDiscountStatus",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "修改优惠券状态")
    public ResponseData updateDiscountStatus(@RequestParam(name = "discountId", required = true) Long discountId,
                                             @RequestParam(name = "status", required = true) Integer status) {
        try {
            // 查询优惠券
            HighDiscount discount = highDiscountService.getDiscountById(discountId);
            if (discount == null) {
                log.error("HighDiscountController -> updateDiscountStatus() error!","未找到优惠券信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_DISCOUNT, "");
            }
            discount.setStatus(status);
            discount.setUpdateTime(new Date());
            highDiscountService.updateDiscount(discount);

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

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

            return ResponseMsgUtil.success(highDiscountService.getDiscountById(id));

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

    @RequestMapping(value="/getDiscountList",method = RequestMethod.GET)
    @ResponseBody

    @ApiOperation(value = "查询优惠券列表")
    public ResponseData getDiscountList(@RequestParam(name = "discountKey", required = false) String discountKey,
                                        @RequestParam(name = "discountName", required = false) String discountName,
                                        @RequestParam(name = "discountType", required = false) Integer discountType,
                                        @RequestParam(name = "useScope", required = false) Integer useScope,
                                        @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();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighDiscountController -> updateDiscount() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("companyId", userInfoModel.getBsCompany().getId());
            map.put("discountKey", discountKey);
            map.put("useScope", useScope);
            map.put("discountName", discountName);
            map.put("discountType", discountType);

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

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

}
