package com.bweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
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.ResponseMsgUtil;
import com.hai.entity.HighActivityInfo;
import com.hai.entity.HighActivityPartakeRule;
import com.hai.entity.HighCoupon;
import com.hai.enum_type.ActivityInfoStatus;
import com.hai.enum_type.ActivityProductType;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.HighActivityAwardService;
import com.hai.service.HighActivityInfoService;
import com.hai.service.HighActivityPartakeRuleService;
import com.hai.service.HighCouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
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 javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 活动业务
 * @author hurui
 */
@Controller
@RequestMapping(value = "/activity")
@Api(value = "活动业务接口")

public class HighActivityInfoController {

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

    @Resource
    private HighActivityInfoService highActivityInfoService;

    @Resource
    private HighActivityPartakeRuleService highActivityPartakeRuleService;

    @Resource
    private HighActivityAwardService highActivityAwardService;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private UserCenter userCenter;

    @RequestMapping(value = "/editActivityInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "编辑活动基本信息")
    public ResponseData editActivityInfo(@RequestBody JSONObject body, HttpServletRequest request) {
        {
            try {
                //发布人员
                SessionObject sessionObject = userCenter.getSessionObject(request);
                UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
                if (userInfoModel.getBsCompany() == null) {
                    log.error("HighActivityInfoController -> editActivityInfo() error!","该主角色没有权限");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
                }
                if (body == null
                        || body.getInteger("type") == null
                        || StringUtils.isBlank(body.getString("title"))
                        || StringUtils.isBlank(body.getString("content"))
                        || body.getLong("startTime") == null
                        || body.getLong("endTime") == null
                ) {
                    log.error("HighActivityInfoController -> editActivityInfo() error!","该主角色没有权限");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                HighActivityPartakeRule partakeRule;
                List<HighActivityPartakeRule> partakeRuleList = new ArrayList<>();

                if (body.getJSONArray("ruleArray") != null && body.getJSONArray("ruleArray").size() > 0) {
                    for (Object object : body.getJSONArray("ruleArray")) {
                        JSONObject ruleObject = (JSONObject)object;
                        Integer partakeMode = ruleObject.getInteger("partakeMode");
                        Integer productType = ruleObject.getInteger("productType");
                        JSONArray productIdArray = ruleObject.getJSONArray("productIdArray");
                        if (productIdArray == null || productIdArray.size() == 0) {
                            log.error("HighActivityInfoController -> editActivityInfo() error!","未选择产品");
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未选择产品");
                        }
                        for (Object productId : productIdArray) {
                            // 产品类型
                            if (productType.equals(ActivityProductType.type1.getNumber())) {
                                // 查询卡券信息
                                HighCoupon coupon = highCouponService.getCouponDetail(Long.parseLong(productId.toString()));
                                if (coupon == null) {
                                    log.error("HighActivityInfoController -> editActivityInfo() error!","未找到产品信息");
                                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到产品信息");
                                }
                                partakeRule = new HighActivityPartakeRule();
                                partakeRule.setPartakeMode(partakeMode);
                                partakeRule.setProductType(productType);
                                partakeRule.setProductId(coupon.getId());
                                partakeRule.setProductName(coupon.getCouponName());
                                partakeRuleList.add(partakeRule);
                            }
                        }
                    }
                }

                HighActivityInfo highActivityInfo;
                if (body.getLong("id") != null) {
                    highActivityInfo = highActivityInfoService.getDetailById(body.getLong("id"));
                    if (highActivityInfo == null) {
                        log.error("HighActivityInfoController -> editActivityInfo() error!","该主角色没有权限");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到活动信息");
                    }
                    if (highActivityInfo.getStatus().equals(ActivityInfoStatus.status3.getNumber())) {
                        log.error("HighActivityInfoController -> editActivityInfo() error!","状态错误");
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
                    }
                } else {
                    highActivityInfo = new HighActivityInfo();
                }

                highActivityInfo.setCompanyId(userInfoModel.getBsCompany().getId());
                highActivityInfo.setOpUserId(userInfoModel.getSecUser().getId());
                highActivityInfo.setOpUserName(userInfoModel.getSecUser().getUserName());
                highActivityInfo.setType(body.getInteger("type"));
                highActivityInfo.setTitle(body.getString("title"));
                highActivityInfo.setContent(body.getString("content"));
                highActivityInfo.setStartTime(new Date(body.getLong("startTime")));
                highActivityInfo.setEndTime(new Date(body.getLong("endTime")));
                highActivityInfoService.editActivityBusiness(highActivityInfo,partakeRuleList);

                return ResponseMsgUtil.success(highActivityInfo);
            } catch (Exception e) {
                log.error("HighActivityInfoController --> editActivityInfo() error!", e);
                return ResponseMsgUtil.exception(e);
            }
        }
    }

    @RequestMapping(value = "/getDetailById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询活动详情")
    public ResponseData getDetailById(@RequestParam(value = "activityId", required = true) Long activityId) {
        {
            try {
                // 查询活动信息
                HighActivityInfo detail = highActivityInfoService.getDetailById(activityId);
                if (detail == null) {
                    log.error("HighActivityInfoController -> getDetailById() error!","未找到数据");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到数据");
                }

                JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(detail));
                // 查询活动的 参与规则 和 商品类型
                List<Map<String, Object>> maps = highActivityPartakeRuleService.countRule(detail.getId());
                JSONArray ruleArray = new JSONArray();
                for (Map<String, Object> map : maps) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("partakeMode", map.get("partakeMode"));
                    jsonObject.put("productType", map.get("productType"));

                    JSONArray productIdArray = new JSONArray();
                    JSONArray productObjectArray = new JSONArray();
                    List<HighActivityPartakeRule> ruleList = highActivityPartakeRuleService.getProductList(detail.getId(), MapUtils.getInteger(map, "partakeMode"), MapUtils.getInteger(map, "productType"));
                    for (HighActivityPartakeRule rule : ruleList) {
                        productIdArray.add(rule.getProductId());

                        JSONObject productObject = new JSONObject();
                        productObject.put("productId", rule.getProductId());
                        productObject.put("productName", rule.getProductName());
                        productObjectArray.add(productObject);
                    }
                    jsonObject.put("productIdArray", productIdArray);
                    jsonObject.put("productObjectArray", productObjectArray);
                    ruleArray.add(jsonObject);
                }
                object.put("ruleArray", ruleArray);

                return ResponseMsgUtil.success(object);
            } catch (Exception e) {
                log.error("HighActivityInfoController --> getDetailById() error!", e);
                return ResponseMsgUtil.exception(e);
            }
        }
    }

    @RequestMapping(value = "/getList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询活动列表")
    public ResponseData getList(@RequestParam(value = "title", required = false) String title,
                                @RequestParam(value = "type", required = false) Integer type,
                                @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> map = new HashMap<>();
                map.put("title", title);
                map.put("type", type);
                map.put("status", status);

                PageHelper.startPage(pageNum,pageSize);
                return ResponseMsgUtil.success(new PageInfo<>(highActivityInfoService.getList(map)));
            } catch (Exception e) {
                log.error("HighActivityInfoController --> getDetailById() error!", e);
                return ResponseMsgUtil.exception(e);
            }
        }
    }

    @RequestMapping(value="/startActivity",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "活动开始")
    public ResponseData startActivity(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("activityId") == null) {
                log.error("HighActivityInfoController -> editActivityInfo() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询活动信息
            HighActivityInfo activityInfo = highActivityInfoService.getDetailById(body.getLong("activityId"));
            if (activityInfo == null) {
                log.error("HighActivityInfoController -> editActivityInfo() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到活动信息");
            }

            if (!activityInfo.getStatus().equals(ActivityInfoStatus.status1.getNumber())) {
                log.error("HighActivityInfoController -> editActivityInfo() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

            // 查询奖励
            if (highActivityAwardService.getListByActivityId(activityInfo.getId()).size() == 0) {
                log.error("HighActivityInfoController -> editActivityInfo() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未配置奖励");
            }

            activityInfo.setStatus(ActivityInfoStatus.status2.getNumber());
            activityInfo.setUpdateTime(new Date());
            highActivityInfoService.updateActivityInfo(activityInfo);

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

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

    @RequestMapping(value="/endActivity",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "活动结束")
    public ResponseData endActivity(@RequestBody JSONObject body) {
        try {
            if (body == null || body.getLong("activityId") == null) {
                log.error("HighActivityInfoController -> editActivityInfo() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询活动信息
            HighActivityInfo activityInfo = highActivityInfoService.getDetailById(body.getLong("activityId"));
            if (activityInfo == null) {
                log.error("HighActivityInfoController -> editActivityInfo() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到活动信息");
            }

            if (!activityInfo.getStatus().equals(ActivityInfoStatus.status2.getNumber())) {
                log.error("HighActivityInfoController -> editActivityInfo() error!","");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.STATUS_ERROR, "");
            }

            activityInfo.setStatus(ActivityInfoStatus.status3.getNumber());
            activityInfo.setUpdateTime(new Date());
            highActivityInfoService.updateActivityInfo(activityInfo);

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

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


}
