package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
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.*;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.math.BigDecimal;
import java.util.*;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/4/20 23:47
 */
@Controller
@RequestMapping(value = "/highCouponAgent")
@Api(value = "代理商接口")
public class HighCouponAgentController {

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

    @Resource
    private HighCouponAgentService highCouponAgentService;

    @Resource
    private HighAgentService highAgentService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighMerchantService highMerchantService;

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighCouponService highCouponService;


    @RequestMapping(value = "/getAgentCount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "代理商统计")
    public ResponseData getAgentCount(HttpServletRequest request,
                                      @RequestParam(name = "type", required = true) Integer type) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            if (userInfoModel.getHighAgent() == null) {
                log.error("HighCouponAgentController -> assignCouponAgent() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            return ResponseMsgUtil.success(highCouponAgentService.getSalesCountByAgent(userInfoModel.getHighAgent().getId(), type));

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

    @RequestMapping(value = "/getAgentSalesCodeList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询代理商已销售的卡券")
    public ResponseData getAgentSalesCodeList(HttpServletRequest request,
                                              @RequestParam(name = "consumeTimeS", required = false) Long consumeTimeS,
                                              @RequestParam(name = "consumeTimeE", required = false) Long consumeTimeE,
                                              @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                              @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            if (userInfoModel.getHighAgent() == null) {
                log.error("HighCouponAgentController -> assignCouponAgent() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            // 如果为空查当前时间
            Calendar timeS = Calendar.getInstance();
            if (consumeTimeS != null) {
                timeS.setTime(new Date(consumeTimeS));
            } else {
                timeS.setTime(new Date());
            }
            timeS.set(Calendar.HOUR_OF_DAY, 00);
            timeS.set(Calendar.MINUTE, 00);
            timeS.set(Calendar.SECOND, 00);

            Calendar timeE = Calendar.getInstance();
            if (consumeTimeE != null) {
                timeE.setTime(new Date(consumeTimeE));
            } else {
                timeE.setTime(new Date());
            }
            timeE.set(Calendar.HOUR_OF_DAY, 23);
            timeE.set(Calendar.MINUTE, 59);
            timeE.set(Calendar.SECOND, 59);

            PageHelper.startPage(pageNum, pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highCouponAgentService.getAgentSalesCodeList(userInfoModel.getHighAgent().getId(), DateUtil.date2String(timeS.getTime(), "yyyy-MM-dd HH:mm:ss"), DateUtil.date2String(timeE.getTime(), "yyyy-MM-dd HH:mm:ss"))));

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

    @RequestMapping(value = "/getAgentSalesPriceCount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询代理商销售总价格")
    public ResponseData getAgentSalesPriceCount(HttpServletRequest request,
                                              @RequestParam(name = "consumeTimeS", required = false) Long consumeTimeS,
                                              @RequestParam(name = "consumeTimeE", required = false) Long consumeTimeE) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();

            if (userInfoModel.getHighAgent() == null) {
                log.error("HighCouponAgentController -> assignCouponAgent() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            // 如果为空查当前时间
            Calendar timeS = Calendar.getInstance();
            if (consumeTimeS != null) {
                timeS.setTime(new Date(consumeTimeS));
            } else {
                timeS.setTime(new Date());
            }
            timeS.set(Calendar.HOUR_OF_DAY, 00);
            timeS.set(Calendar.MINUTE, 00);
            timeS.set(Calendar.SECOND, 00);

            Calendar timeE = Calendar.getInstance();
            if (consumeTimeE != null) {
                timeE.setTime(new Date(consumeTimeE));
            } else {
                timeE.setTime(new Date());
            }
            timeE.set(Calendar.HOUR_OF_DAY, 23);
            timeE.set(Calendar.MINUTE, 59);
            timeE.set(Calendar.SECOND, 59);

            BigDecimal totalPrice = new BigDecimal("0.00");
            List<HighCouponAgentCode> list = highCouponAgentService.getAgentSalesCodeList(userInfoModel.getHighAgent().getId(), DateUtil.date2String(timeS.getTime(), "yyyy-MM-dd HH:mm:ss"), DateUtil.date2String(timeE.getTime(), "yyyy-MM-dd HH:mm:ss"));
            for (HighCouponAgentCode code: list) {
                totalPrice = totalPrice.add(code.getHighCoupon().getSalesPrice());
            }
            return ResponseMsgUtil.success(totalPrice);

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

    @RequestMapping(value = "/assignCouponAgent", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配卡券给代理商")
    public ResponseData assignCouponAgent(@RequestBody HighCouponAgentRel highCouponAgentRel, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighCouponAgentController -> assignCouponAgent() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            if(highCouponAgentRel.getCouponId() == null
                || highCouponAgentRel.getAgentId() == null
                || highCouponAgentRel.getType() == null
                || highCouponAgentRel.getStockCount() == null) {
                log.error("HighCouponAgentController -> assignCouponAgent() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询卡券详情
            HighCoupon coupon = highCouponService.getCouponById(highCouponAgentRel.getCouponId());
            if (coupon == null) {
                log.error("HighCouponAgentController -> assignCouponAgent() error!","未找到卡券信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_COUPON, "");
            }

            // 查询代理商
            HighAgent highAgent = highAgentService.findByAgentMsgId(highCouponAgentRel.getAgentId());
            if (highAgent == null) {
                log.error("HighCouponAgentController -> assignCouponAgent() error!","未找到代理商信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_AGENT, "");
            }

            // 校验是否分配过
            HighCouponAgentRel couponAgent = highCouponAgentService.getRelByCouponAgent(highCouponAgentRel.getCouponId(), highCouponAgentRel.getAgentId(), highCouponAgentRel.getType());
            if (couponAgent != null) {
                couponAgent.setStockCount(couponAgent.getStockCount() + highCouponAgentRel.getStockCount());
                couponAgent.setOperatorId(userInfoModel.getSecUser().getId());
                couponAgent.setOperatorName(userInfoModel.getSecUser().getUserName());
                highCouponAgentService.assignCouponAgent(couponAgent,highCouponAgentRel.getStockCount());
            } else {
                highCouponAgentRel.setCouponName(coupon.getCouponName());
                highCouponAgentRel.setSalesPrice(coupon.getSalesPrice());
                highCouponAgentRel.setStatus(1); // 状态 0:删除  1:正常
                highCouponAgentRel.setSalesCount(0);
                highCouponAgentRel.setCreateTime(new Date());
                highCouponAgentRel.setOperatorId(userInfoModel.getSecUser().getId());
                highCouponAgentRel.setOperatorName(userInfoModel.getSecUser().getUserName());
                highCouponAgentService.assignCouponAgent(highCouponAgentRel,highCouponAgentRel.getStockCount());
            }

            return ResponseMsgUtil.success("分配成功");

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


    @RequestMapping(value = "/getCouponByAgent", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据代理商 查询卡券")
    public ResponseData getCouponByAgent(@RequestParam(name = "agentId", required = true) Long agentId,
                                         @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                         @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                         HttpServletRequest request) {
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("agentId", agentId);

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<HighCouponAgentRel> pageInfo = new PageInfo<>(highCouponAgentService.getCouponAgentList(map));
            for (HighCouponAgentRel rel : pageInfo.getList()) {
                rel.setHighCoupon(highCouponService.getCouponById(rel.getCouponId()));
            }
            return ResponseMsgUtil.success(pageInfo);

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


    @RequestMapping(value = "/getAgentByCoupon", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据卡券  查询代理商")
    public ResponseData getAgentByCoupon(@RequestParam(name = "couponId", required = true) Long couponId,
                                         @RequestParam(name = "status", required = false) Integer status,
                                         @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                         @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                         HttpServletRequest request) {
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("couponId", couponId);
            map.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<HighCouponAgentRel> pageInfo = new PageInfo<>(highCouponAgentService.getCouponAgentList(map));
            if (pageInfo.getList().size() > 0) {
                for (HighCouponAgentRel code : pageInfo.getList()) {
                    code.setHighAgent(highAgentService.findByAgentMsgId(code.getAgentId()));
                }
            }
            return ResponseMsgUtil.success(pageInfo);

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

    @RequestMapping(value = "/getCodeListByAgentCoupon", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据代理商和卡券 查询分配的销售码")
    public ResponseData getCodeListByAgentCoupon(@RequestParam(name = "couponId", required = true) Long couponId,
                                            @RequestParam(name = "status", required = false) String status,
                                            @RequestParam(name = "createTimeS", required = false) Long createTimeS,
                                            @RequestParam(name = "createTimeE", required = false) Long createTimeE,
                                            @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.getHighAgent() == null) {
                log.error("HighCouponAgentController -> getCouponByAgent() error!","该角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该角色没有权限");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("agentId", userInfoModel.getHighAgent().getId());
            map.put("couponId", couponId);
            map.put("status", status);
            map.put("createTimeS", createTimeS);
            map.put("createTimeE", createTimeE);

            PageHelper.startPage(pageNum,pageSize);
            PageInfo<HighCouponAgentCode> pageInfo = new PageInfo<>(highCouponAgentService.getCouponCodeList(map));
            if (pageInfo.getList().size() > 0) {
                HighMerchant merchant = new HighMerchant();
                HighCoupon highCoupon = highCouponService.getCouponById(couponId);
                if (highCoupon != null) {
                    merchant = highMerchantService.getMerchantById(highCoupon.getMerchantId());
                }
                for (HighCouponAgentCode code : pageInfo.getList()) {
                    code.setMerchantLogo(merchant.getMerchantLogo());
                    code.setMerchantName(merchant.getMerchantName());
                    code.setHighCoupon(highCoupon);
                    code.setHighCouponCode(highCouponCodeService.getCouponCodeById(code.getCouponCodeId()));
                }
            }
            return ResponseMsgUtil.success(pageInfo);

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


    @RequestMapping(value = "/generateCode", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "生成二维码")
    public ResponseData generateCode(@RequestBody String reqBody,HttpServletRequest request) {
        try {
            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getHighAgent() == null) {
                log.error("HighCouponAgentController -> generateCode() error!","该角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "该角色没有权限");
            }

            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            Long couponAgentCodeId = jsonObject.getLong("couponAgentCodeId");
            String remark = jsonObject.getString("remark");
            if (couponAgentCodeId == null) {
                log.error("HighMerchantStoreController -> useCouponCode() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            return ResponseMsgUtil.success(highCouponAgentService.generateCode(couponAgentCodeId,remark));

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

    @RequestMapping(value = "/getCodeById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据销售码查询详情")
    public ResponseData getCodeById(@RequestParam(name = "couponAgentCodeId", required = true) Long couponAgentCodeId,
                                            HttpServletRequest request) {
        try {
            // 查询卡券销售码
            HighCouponAgentCode couponAgentCode = highCouponAgentService.getCodeById(couponAgentCodeId);
            if (couponAgentCode == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到销售码");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("couponInfo", highCouponService.getCouponById(couponAgentCode.getCouponId()));
            map.put("couponCode", highCouponCodeService.getCouponCodeById(couponAgentCode.getCouponCodeId()));
            map.put("couponAgentCode", couponAgentCode);
            return ResponseMsgUtil.success(map);

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


    @RequestMapping(value = "/remark", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "填写备注")
    public ResponseData remark(@RequestBody String reqBody) {
        try {

            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            Long couponAgentCodeId = jsonObject.getLong("couponAgentCodeId");
            String remark = jsonObject.getString("remark");
            if (couponAgentCodeId == null) {
                log.error("HighMerchantStoreController -> useCouponCode() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询卡券销售码
            HighCouponAgentCode couponAgentCode = highCouponAgentService.getCodeById(couponAgentCodeId);
            if (couponAgentCode == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到销售码");
            }
            couponAgentCode.setRemark(remark);
            highCouponAgentService.updateCouponAgentCode(couponAgentCode);

            return ResponseMsgUtil.success(couponAgentCode);

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

    @RequestMapping(value = "/getRecordByCouponAgentId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据卡券与代理商关系 查询分发记录")
    public ResponseData getRecordByCouponAgentId(@RequestParam(name = "couponAgentId", required = true) Long couponAgentId,
                                                 @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                                 @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                                 HttpServletRequest request) {
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("couponAgentId", couponAgentId);
            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highCouponAgentService.getRecordList(map)));

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


    @RequestMapping(value = "/getCouponByRecord", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据分发记录 查询卡券")
    public ResponseData getCouponByRecord(@RequestParam(name = "recordId", required = true) Long recordId,
                                                 @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                                 @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("recordId", recordId);

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

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


}