package com.cweb.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.utils.DateUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsMer;
import com.hfkj.entity.BsRebateActivity;
import com.hfkj.model.ResponseData;
import com.hfkj.service.BsMerService;
import com.hfkj.service.rebate.BsRebateActivityAccountService;
import com.hfkj.service.rebate.BsRebateActivityService;
import com.hfkj.sysenum.*;
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.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: BsRebateActivityController
 * @author: HuRui
 * @date: 2023/10/18
 **/
@Controller
@Api(value = "活动金 - 活动配置")
@RequestMapping(value = "/rebateActivity")
public class BsRebateActivityController {

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

    @Resource
    private BsRebateActivityService rebateActivityService;
    @Resource
    private BsRebateActivityAccountService rebateActivityAccountService;
    @Resource
    private BsMerService merService;

    @RequestMapping(value="/addActivity",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "增加活动")
    public ResponseData addActivity(@RequestBody JSONObject body) {
        try {

            if (body == null
                    || StringUtils.isBlank(body.getString("merNo"))
                    || body.getInteger("activityType") == null
                    || body.getInteger("preferentialType") == null
                    || body.getBigDecimal("price") == null
                    || body.getLong("endTime") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 活动类型
            RebateActivityTypeEnum activityType = RebateActivityTypeEnum.getDataByNumber(body.getInteger("activityType"));
            if (activityType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的活动类型");
            }
            // 优惠类型
            RebateActivityPreferentialTypeEnum preferentialType = RebateActivityPreferentialTypeEnum.getDataByNumber(body.getInteger("preferentialType"));
            if (preferentialType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠类型");
            }
            // 满减条件
            if (preferentialType.getNumber().equals(RebateActivityPreferentialTypeEnum.type1.getNumber())
                && body.getBigDecimal("condition") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "满减类型未设置满减条件");
            }
            // 限制类型
            if (body.getInteger("partakeType") != null) {
                Integer partakeType = body.getInteger("partakeType");

                if (RebateActivityPartakeTypeEnum.type1.getNumber().equals(partakeType)
                        && body.getInteger("partakeNum") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "需要上传限制使用次数");
                }
            }

            // 查询商户
            BsMer mer = merService.getMer(body.getString("merNo"));
            if (mer == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
            }
            BsRebateActivity activity = new BsRebateActivity();
            activity.setMerId(mer.getId());
            activity.setMerNo(mer.getMerNo());
            activity.setMerName(mer.getMerName());
            activity.setMerAbbreviate(mer.getMerAbbreviate());
            activity.setActivityNo(System.currentTimeMillis()+"");
            activity.setActivityType(activityType.getNumber());
            activity.setPreferentialType(preferentialType.getNumber());
            activity.setPrice(body.getBigDecimal("price"));
            activity.setCondition(body.getBigDecimal("condition"));
            activity.setEndTime(new Date(body.getLong("endTime")));
            activity.setRestrictPartakeType(body.getInteger("partakeType"));
            activity.setRestrictPartakeNum(body.getInteger("partakeNum"));
            activity.setStatus(RebateActivityStatusEnum.status1.getNumber());
            rebateActivityService.editData(activity);

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

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

    @RequestMapping(value="/updateActivity",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改活动")
    public ResponseData updateActivity(@RequestBody JSONObject body) {
        try {

            if (body == null
                    || StringUtils.isBlank(body.getString("activityNo"))
                    || body.getInteger("activityType") == null
                    || body.getInteger("preferentialType") == null
                    || body.getBigDecimal("price") == null
                    || body.getLong("endTime") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 活动类型
            RebateActivityTypeEnum activityType = RebateActivityTypeEnum.getDataByNumber(body.getInteger("activityType"));
            if (activityType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的活动类型");
            }
            // 优惠类型
            RebateActivityPreferentialTypeEnum preferentialType = RebateActivityPreferentialTypeEnum.getDataByNumber(body.getInteger("preferentialType"));
            if (preferentialType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠类型");
            }
            // 满减条件
            if (preferentialType.getNumber().equals(RebateActivityPreferentialTypeEnum.type1.getNumber())
                    && body.getBigDecimal("condition") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "满减类型未设置满减条件");
            }
            // 限制类型
            if (body.getInteger("partakeType") != null) {
                Integer partakeType = body.getInteger("partakeType");

                if (RebateActivityPartakeTypeEnum.type1.getNumber().equals(partakeType)
                        && body.getInteger("partakeNum") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "需要上传限制使用次数");
                }
            }
            // 查询活动
            BsRebateActivity activity = rebateActivityService.getActivityByNo(body.getString("activityNo"));
            if (activity == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户");
            }
            if (!activity.getStatus().equals(RebateActivityStatusEnum.status1.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "当前活动状态无法修改");
            }
            activity.setActivityType(activityType.getNumber());
            activity.setPreferentialType(preferentialType.getNumber());
            activity.setPrice(body.getBigDecimal("price"));
            activity.setCondition(body.getBigDecimal("condition"));
            activity.setEndTime(new Date(body.getLong("endTime")));
            activity.setRestrictPartakeType(body.getInteger("partakeType"));
            activity.setRestrictPartakeNum(body.getInteger("partakeNum"));
            rebateActivityService.editData(activity);

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

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

    @RequestMapping(value="/openActivity",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "开启活动")
    public ResponseData openActivity(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("activityNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            rebateActivityService.openActivity(body.getString("activityNo"));

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

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

    @RequestMapping(value="/closeActivity",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "关闭活动")
    public ResponseData closeActivity(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("activityNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            rebateActivityService.closeActivity(body.getString("activityNo"), RebateActivityEndTypeEnum.type2);

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

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

    @RequestMapping(value="/updateActivityEndTime",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改活动结束时间")
    public ResponseData updateActivityEndTime(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("activityNo")) ||  body.getLong("endTime") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            rebateActivityService.updateActivityEndTime(body.getString("activityNo"), new Date(body.getLong("endTime")));

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

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

    @RequestMapping(value="/getActivityDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询活动详情")
    public ResponseData getActivityDetail(@RequestParam(value = "activityNo" , required = true) String activityNo) {
        try {
            // 查询活动
            BsRebateActivity activity = rebateActivityService.getActivityByNo(activityNo);
            if (activity == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到活动");
            }
            activity.setEndTimeStr(DateUtil.date2String(activity.getEndTime(), "yyyy-MM-dd"));
            activity.setActivityAccount(rebateActivityAccountService.getAccountByActivityNo(activityNo));
            return ResponseMsgUtil.success(activity);

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

    @RequestMapping(value="/getActivityList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询活动列表")
    public ResponseData getActivityList(@RequestParam(value = "activityNo" , required = false) String activityNo,
                                        @RequestParam(value = "merNo" , required = false) String merNo,
                                        @RequestParam(value = "merName" , required = false) String merName,
                                        @RequestParam(value = "merAbbreviate" , required = false) String merAbbreviate,
                                        @RequestParam(value = "status" , required = false) Integer status,
                                        @RequestParam(value = "pageNum" , required = true) Integer pageNum,
                                        @RequestParam(value = "pageSize" , required = true) Integer pageSize) {
        try {

            Map<String,Object> param = new HashMap<>();
            param.put("activityNo", activityNo);
            param.put("merNo", merNo);
            param.put("merName", merName);
            param.put("merAbbreviate", merAbbreviate);
            param.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<BsRebateActivity> pageInfo = new PageInfo<>(rebateActivityService.getActivityList(param));
            for (BsRebateActivity activity : pageInfo.getList()) {
                activity.setActivityAccount(rebateActivityAccountService.getAccountByActivityNo(activity.getActivityNo()));
            }
            return ResponseMsgUtil.success(pageInfo);

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

}
