package com.bweb.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.Base64Util;
import com.hai.common.QRCodeGenerator;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.AESEncodeUtil;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.IDGenerator;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.CommonSysConst;
import com.hai.entity.*;
import com.hai.enum_type.QrCodeType;
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.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/4/4 00:19
 */
@Controller
@RequestMapping(value = "/discountAgentRel")
@Api(value = "优惠券和代理商接口")
public class HighDiscountAgentRelController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighAgentService highAgentService;

    @Resource
    private HighDiscountService highDiscountService;

    @Resource
    private HighDiscountAgentRelService highDiscountAgentRelService;

    @Resource
    private HighDiscountAgentCodeService highDiscountAgentCodeService;

    @Resource
    private HighOrderService highOrderService;

    @RequestMapping(value="/insertDiscountAgent",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "分配优惠券给代理商")
    public ResponseData insertDiscountAgent(@RequestBody HighDiscountAgentRel highDiscountAgentRel, HttpServletRequest request) {
        try {
            SessionObject sessionObject = userCenter.getSessionObject(request);
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
            if (userInfoModel.getBsCompany() == null) {
                log.error("HighDiscountAgentRelController -> insertDiscount() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }
            if (highDiscountAgentRel.getDiscountId() == null
                    || highDiscountAgentRel.getAgentId() == null
                    || highDiscountAgentRel.getStockCount() == null) {
                log.error("HighDiscountAgentRelController -> insertDiscountAgent() error!","参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 查询优惠券
            HighDiscount discount = highDiscountService.getDiscountById(highDiscountAgentRel.getDiscountId());
            if(discount == null) {
                log.error("HighDiscountAgentRelController -> insertDiscountAgent() error!","未找到优惠券信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_DISCOUNT, "");
            }

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

            HighDiscountAgentRel discountAgent = highDiscountAgentRelService.getRelByDiscountAgent(highDiscountAgentRel.getDiscountId(), highDiscountAgentRel.getAgentId());
            // 是否已分配
            if (discountAgent != null) {
                discountAgent.setStockCount(discountAgent.getStockCount() + highDiscountAgentRel.getStockCount());
                highDiscountAgentRelService.insertDiscountAgentRel(discountAgent,highDiscountAgentRel.getStockCount());
            } else {
                highDiscountAgentRel.setCreateTime(new Date());
                highDiscountAgentRel.setStatus(1);
                highDiscountAgentRelService.insertDiscountAgentRel(highDiscountAgentRel,highDiscountAgentRel.getStockCount());
            }
/*            // 生成二维码
            String qrCodeImg = DateUtil.date2String(new Date(),agent.getId() + discount.getId() + "yyyyMMddHHmmss") + IDGenerator.nextId(2) +".png";
            String qrCodeUrl = SysConst.getSysConfig().getAgentQrCode() + "/" + qrCodeImg;

            //参数
            String url = SysConst.getSysConfig().getAgentQrCodeWxUrl() + highDiscountAgentRel.getId();
            QRCodeGenerator.generateQRCodeImage(url, 350, 350, qrCodeUrl);
            highDiscountAgentRel.setQrCode(qrCodeImg);
            highDiscountAgentRelService.updateDiscountAgentRel(highDiscountAgentRel);*/

            return ResponseMsgUtil.success("操作成功");
        } catch (Exception e) {
            log.error("HighDiscountController -> insertDiscountAgent() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/getDiscountAgentById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询")
    public ResponseData getDiscountAgentById(@RequestParam(name = "id", required = true) Long id) {
        try {

            return ResponseMsgUtil.success(highDiscountAgentRelService.getRelById(id));

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

    @RequestMapping(value="/getReceiveLink",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取领取链接")
    public ResponseData getReceiveLink(@RequestParam(name = "id", required = true) Long id) {
        try {

            String param = URLEncoder.encode(AESEncodeUtil.aesEncrypt(id.toString()), "UTF-8");

            String url = CommonSysConst.getSysConfig().getHsgDomainName() + "/hsgH5?accountId=000001&key=&code=" + param;

            return ResponseMsgUtil.success(url);

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

    @RequestMapping(value="/getDiscountAgentList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询列表")
    public ResponseData getDiscountAgentList(@RequestParam(name = "discountId", required = false) Long discountId,
                                             @RequestParam(name = "agentId", required = false) Long agentId,
                                             @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                             @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("discountId", discountId);
            map.put("agentId", agentId);

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

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

    @RequestMapping(value="/getDiscountCodeList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询优惠券码 列表")
    public ResponseData getDiscountAgentList(@RequestParam(name = "discountAgentId", required = true) Long discountAgentId,
                                             @RequestParam(name = "status", required = false) Integer status,
                                             @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                             @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("discountAgentId", discountAgentId);
            map.put("status", status);

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

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

    @RequestMapping(value="/getDiscountUseConditionList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询优惠券使用情况")
    public ResponseData getDiscountUseConditionList(@RequestParam(name = "discountId", required = false) Long discountId,
                                                    @RequestParam(name = "discountName", required = false) String discountName,
                                                    @RequestParam(name = "storeName", required = false) String storeName,
                                                    @RequestParam(name = "status", required = false) Integer status,
                                                    @RequestParam(name = "receiveTimeS", required = false) Long receiveTimeS,
                                                    @RequestParam(name = "receiveTimeE", required = false) Long receiveTimeE,
                                                    @RequestParam(name = "useTimeS", required = false) Long useTimeS,
                                                    @RequestParam(name = "useTimeE", required = false) Long useTimeE,
                                                    @RequestParam(name = "idS", required = false) Long idS,
                                                    @RequestParam(name = "idE", required = false) Long idE,
                                                    @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("HighCouponController -> insertCoupon() error!","该主角色没有权限");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.MENU_TREE_HAS_NOT_ERROR, "");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("agentId", userInfoModel.getHighAgent().getId());
            map.put("discountId", discountId);
            map.put("discountName", discountName);
            map.put("storeName", storeName);
            map.put("status", status);
            map.put("receiveTimeS", receiveTimeS);
            map.put("receiveTimeE", receiveTimeE);
            map.put("useTimeS", useTimeS);
            map.put("useTimeE", useTimeE);
            map.put("idS", idS);
            map.put("idE", idE);

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

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

    @RequestMapping(value="/getDiscountCodeById",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询优惠券码 详情")
    public ResponseData getDiscountCodeById(@RequestParam(name = "couponCodeId", required = true) Long couponCodeId) {
        try {

            HighDiscountAgentCode code = highDiscountAgentCodeService.getCodeById(couponCodeId);
            if (code != null) {
                HighDiscountAgentRel rel = highDiscountAgentRelService.getRelById(code.getDiscountAgentId());
                code.setHighDiscount(highDiscountService.getDiscountById(rel.getDiscountId()));
                code.setHighAgent(highAgentService.findByAgentMsgId(rel.getAgentId()));
                code.setHighOrder(highOrderService.getConsumeOrderByDiscountCode(code.getId()));
                return ResponseMsgUtil.success(code);
            }
            return ResponseMsgUtil.success(null);

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

    @RequestMapping(value="/getDiscountStatus",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改状态")
    public ResponseData getDiscountStatus(@RequestBody JSONObject jsonObject) {
        try {

            Integer status = jsonObject.getInteger("status");
            Long minNumber = jsonObject.getLong("minNumber");
            Long maxNumber = jsonObject.getLong("maxNumber");

            for (Long i = minNumber; i <= maxNumber; i++) {
                HighDiscountAgentCode highDiscountAgentCode = highDiscountAgentCodeService.getCodeById(i);
                if (highDiscountAgentCode.getStatus() == 1 || highDiscountAgentCode.getStatus() == 4 ) {

                    highDiscountAgentCode.setStatus(status);
                    highDiscountAgentCodeService.updateCode(highDiscountAgentCode);
                }
            }

            return ResponseMsgUtil.success("成功");

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

}
