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.entity.BsDiscountPk;
import com.hfkj.entity.BsDiscountPkRel;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.service.discount.BsDiscountPkRelService;
import com.hfkj.service.discount.BsDiscountPkService;
import com.hfkj.service.discount.BsDiscountService;
import com.hfkj.service.discount.BsDiscountUserService;
import com.hfkj.sysenum.SecUserObjectTypeEnum;
import com.hfkj.sysenum.discount.DiscountStatusEnum;
import com.hfkj.sysenum.discount.DiscountStockCodeObtainTypeEnum;
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 = "/discountPk")
@Api(value = "优惠券包管理")
public class BsDiscountPkController {
    private static Logger log = LoggerFactory.getLogger(BsDiscountPkController.class);
    @Resource
    private BsDiscountPkService discountPkService;
    @Resource
    private BsDiscountPkRelService discountPkRelService;
    @Resource
    private BsDiscountUserService discountUserService;
    @Resource
    private BsDiscountService discountService;
    @Resource
    private UserCenter userCenter;

    @RequestMapping(value="/edit",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑")
    public ResponseData edit(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("discountPkName"))
                    || body.getBigDecimal("salePrice") == null
                    || body.getJSONArray("discountList") == null
                    || body.getJSONArray("discountList").isEmpty()
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            BsDiscountPk discountPk = null;
            if (StringUtils.isNotBlank(body.getString("discountPkNo"))) {
                // 查询卷包
                discountPk = discountPkService.getDetail(body.getString("discountPkNo"));
                if (discountPk == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的券包");
                }
            } else {
                discountPk = new BsDiscountPk();
            }
            discountPk.setDiscountPkName(body.getString("discountPkName"));
            discountPk.setDescribe(body.getString("describe"));
            discountPk.setListImg(body.getString("listImg"));
            discountPk.setContent(body.getString("content"));
            discountPk.setSalePrice(body.getBigDecimal("salePrice"));

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

            List<BsDiscountPkRel> pkRelList = new ArrayList<>();
            for (Object obj : body.getJSONArray("discountList")) {
                JSONObject discountObj = (JSONObject)obj;
                if (StringUtils.isBlank(discountObj.getString("discountNo"))
                        || discountObj.getInteger("number") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                // 查询优惠券
                BsDiscount discount = discountService.getDetail(discountObj.getString("discountNo"));
                if (discount == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠券"+discountObj.getString("discountNo"));
                }
                if (!discount.getStatus().equals(DiscountStatusEnum.status2.getCode())) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, discount.getDiscountName()+"优惠券未上线");
                }
                BsDiscountPkRel discountPkRel = new BsDiscountPkRel();
                discountPkRel.setNumber(discountObj.getInteger("number"));
                discountPkRel.setDiscountNo(discount.getDiscountNo());
                discountPkRel.setDiscountName(discount.getDiscountName());
                discountPkRel.setDiscountType(discount.getDiscountType());
                discountPkRel.setDiscountCondition(discount.getDiscountCondition());
                discountPkRel.setDiscountPrice(discount.getDiscountPrice());
                discountPkRel.setUseScope(discount.getUseScope());
                discountPkRel.setReceiveExpirationDate(discount.getReceiveExpirationDate());
                pkRelList.add(discountPkRel);
            }
            discountPkService.edit(discountPk, pkRelList);

            return ResponseMsgUtil.success(discountPk);

        } 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("discountPkNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询优惠券
            BsDiscountPk discountPk = discountPkService.getDetail(body.getString("discountPkNo"));
            if (discountPk == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            discountPk.setStartTime(new Date());
            discountPk.setStatus(DiscountStatusEnum.status2.getCode());
            discountPkService.editData(discountPk);

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

        } catch (Exception 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("discountPkNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询优惠券
            BsDiscountPk discountPk = discountPkService.getDetail(body.getString("discountPkNo"));
            if (discountPk == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            discountPk.setStatus(DiscountStatusEnum.status3.getCode());
            discountPk.setEndTime(new Date());
            discountPkService.editData(discountPk);

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

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

    @RequestMapping(value="/delete",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "删除")
    public ResponseData delete(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("discountPkNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询优惠券
            BsDiscountPk discountPk = discountPkService.getDetail(body.getString("discountPkNo"));
            if (discountPk == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            discountPk.setStatus(DiscountStatusEnum.status0.getCode());
            discountPkService.editData(discountPk);

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

        } catch (Exception 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("discountPkNo"))
                    || StringUtils.isBlank(body.getString("userPhone"))
                    || body.getInteger("number") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            discountUserService.receivePk(
                    body.getString("discountPkNo"),
                    body.getInteger("number"),
                    DiscountStockCodeObtainTypeEnum.type3,
                    body.getString("userPhone"),
                    null);

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

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

    @RequestMapping(value="/getDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询详情")
    public ResponseData getDetail(@RequestParam(name = "discountPkNo", required = true) String discountPkNo) {
        try {
            // 查询优惠券包
            BsDiscountPk discountPk = discountPkService.getDetail(discountPkNo);
            if (discountPk == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠券包");
            }
            Map<String,Object> param = new HashMap<>();
            param.put("discountPk", discountPk);
            param.put("discountPkRel", discountPkRelService.getList(discountPkNo));

            return ResponseMsgUtil.success(param);

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

    @RequestMapping(value="/getList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询列表")
    public ResponseData getList(@RequestParam(name = "discountPkName", required = false) String discountPkName,
                                @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("discountPkName", discountPkName);
            param.put("status", status);

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

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