package com.bweb.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.BsDiscount;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.discount.BsDiscountService;
import com.hfkj.service.discount.BsDiscountUserService;
import com.hfkj.sysenum.*;
import com.hfkj.sysenum.discount.DiscountStatusEnum;
import com.hfkj.sysenum.discount.DiscountStockCodeObtainTypeEnum;
import com.hfkj.sysenum.discount.DiscountTypeEnum;
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.util.*;

@Controller
@RequestMapping(value = "/discount")
@Api(value = "优惠券管理")
public class BsDiscountController {
    private static Logger log = LoggerFactory.getLogger(BsDiscountController.class);
    @Resource
    private BsDiscountService discountService;
    @Resource
    private UserCenter userCenter;
    @Resource
    private BsDiscountUserService discountUserService;

    @RequestMapping(value="/editDiscount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑优惠券")
    public ResponseData editDiscount(@RequestBody JSONObject body)  {
        try {
            if (StringUtils.isBlank(body.getString("discountName"))
                    || body.getInteger("discountType") == null
                    || body.getBigDecimal("discountPrice") == null
                    || body.getBoolean("overlayDiscount") == null
                    || StringUtils.isBlank(body.getString("useScope"))
                    || body.getInteger("receiveExpirationDate") == null
                    || body.getLong("endTime") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 优惠券类型
            if (DiscountTypeEnum.getNameByType(body.getInteger("discountType")) == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知优惠券类型");
            }
            // 满减条件
            if (DiscountTypeEnum.type1.getCode().equals(body.getInteger("discountType"))
               && body.getBigDecimal("discountCondition") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未设置满减条件");
            }
            BsDiscount discount;
            if (StringUtils.isNotBlank(body.getString("discountNo"))) {
                // 查询优惠券
                discount = discountService.getDetail(body.getString("discountNo"));
                if (discount == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            } else {
                discount = new BsDiscount();
            }
            discount.setDiscountType(body.getInteger("discountType"));
            discount.setDiscountName(body.getString("discountName"));
            discount.setDiscountPrice(body.getBigDecimal("discountPrice"));
            discount.setOverlayDiscount(body.getBoolean("overlayDiscount"));
            discount.setDiscountCondition(body.getBigDecimal("discountCondition"));
            discount.setUseScope(body.getString("useScope"));
            discount.setReceiveExpirationDate(body.getInteger("receiveExpirationDate"));
            discount.setEndTime(new Date(body.getLong("endTime")));
            discount.setStatus(DiscountStatusEnum.status1.getCode());

            // 用户信息
            SecUserSessionObject userInfoModel = userCenter.getSessionModel(SecUserSessionObject.class);
            if (SecUserObjectTypeEnum.type1.getCode() == userInfoModel.getAccount().getObjectType()) {
                discount.setCreateUserType(1);
                discount.setCreateUserId(userInfoModel.getAccount().getId());
                discount.setCreateUserName(userInfoModel.getAccount().getUserName());
            } else if (SecUserObjectTypeEnum.type2.getCode() == userInfoModel.getAccount().getObjectType()) {
                discount.setCreateUserType(2);
                discount.setCreateUserId(userInfoModel.getAccount().getId());
                discount.setCreateUserName(userInfoModel.getAccount().getUserName());
                discount.setCreateUserMerNo(userInfoModel.getMerchant().getMerNo());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            discountService.editDiscount(discount);

            return ResponseMsgUtil.success(discount);

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

    @RequestMapping(value="/updateEndTime",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改结束时间")
    public ResponseData updateEndTime(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("discountNo"))
                    || body.getLong("endTime") == null) {
                log.error("BsDiscountController -> updateEndTime() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询详情
            BsDiscount discount = discountService.getDetail(body.getString("discountNo"));
            if (discount == null) {
                log.error("BsDiscountController -> updateEndTime() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠券");
            }
            if (!discount.getStatus().equals(DiscountStatusEnum.status2.getCode())) {
                log.error("BsDiscountController -> updateEndTime() error!","无法修改，优惠不处于上线状态");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法修改，优惠不处于上线状态");
            }
            discount.setEndTime(new Date(body.getLong("endTime")));
            discountService.editDiscount(discount);

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

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

    @RequestMapping(value="/giveUser",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "赠送用户")
    public ResponseData giveUser(@RequestBody JSONObject body) {
        try {
            if (body == null
                    || StringUtils.isBlank(body.getString("discountNo"))
                    || StringUtils.isBlank(body.getString("userPhone"))
                    || body.getInteger("number") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            discountUserService.receive(
                    body.getString("discountNo"),
                    body.getInteger("number"),
                    DiscountStockCodeObtainTypeEnum.type3,
                    body.getString("userPhone"),
                    null);

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

        } catch (Exception e) {
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/online",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "上线优惠券")
    public ResponseData online(@RequestBody JSONObject body) {
        try {

            if (body == null || StringUtils.isBlank(body.getString("discountNo"))) {
                log.error("BsDiscountController -> online() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            discountService.online(body.getString("discountNo"));

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

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

    @RequestMapping(value="/done",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "结束优惠券")
    public ResponseData done(@RequestBody JSONObject body) {
        try {

            if (body == null || StringUtils.isBlank(body.getString("discountNo"))) {
                log.error("BsDiscountController -> done() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            discountService.done(body.getString("discountNo"));

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

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

    @RequestMapping(value="/delete",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除优惠券")
    public ResponseData delete(@RequestBody JSONObject body) {
        try {

            if (body == null || StringUtils.isBlank(body.getString("discountNo"))) {
                log.error("BsDiscountController -> delDiscount() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            discountService.delete(body.getString("discountNo"));

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

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

    @RequestMapping(value="/queryDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询详情")
    public ResponseData queryDetail(@RequestParam(name = "discountNo", required = true) String discountNo) {
        try {

            return ResponseMsgUtil.success(discountService.getDetail(discountNo));

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

    @RequestMapping(value="/queryList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询列表")
    public ResponseData queryList(@RequestParam(name = "merNo", required = false) String merNo,
                                  @RequestParam(name = "discountName", required = false) String discountName,
                                  @RequestParam(name = "discountType", required = false) Integer discountType,
                                  @RequestParam(name = "status", required = false) Integer status,
                                  @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                  @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            SecUserSessionObject userInfoModel = userCenter.getSessionModel(SecUserSessionObject.class);
            Map<String,Object> param = new HashMap<>();
            if (userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type1.getCode())
                || userInfoModel.getAccount().getObjectType().equals(SecUserObjectTypeEnum.type2.getCode())) {
                param.put("createUserId", userInfoModel.getAccount().getId());
            } else {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ROLE_NOT_PERMISSIONS, "");
            }
            param.put("discountName", discountName);
            param.put("discountType", discountType);
            param.put("status", status);

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

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

}
