package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.cweb.config.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.QRCodeGenerator;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.config.WeChatQrcodeUtils;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.service.*;
import com.hfkj.sysenum.StoreDiscountActivityStatusEnum;
import com.hfkj.sysenum.WeChatQrCodeActionNameEnum;
import com.hfkj.sysenum.WeChatQrCodeTypeEnum;
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 javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;
import java.util.List;

/**
 * @className: BsStoreDiscountActivityPartakeUserController
 * @author: HuRui
 * @date: 2023/3/14
 **/
@Controller
@Api(value = "优惠参与用户")
@RequestMapping(value = "/storeDiscountActivityPartakeUser")
public class BsStoreDiscountActivityPartakeUserController {
    private static Logger log = LoggerFactory.getLogger(BsStoreDiscountActivityPartakeUserController.class);
    @Resource
    private BsStoreDiscountActivityPartakeUserService storeDiscountActivityPartakeUserService;
    @Resource
    private BsStoreDiscountActivityService storeDiscountActivityService;
    @Resource
    private BsStoreService storeService;
    @Resource
    private BsPayQrCodeService payQrCodeService;
    @Resource
    private BsTradeOrderService tradeOrderService;
    @Resource
    private WeChatQrcodeUtils weChatQrcodeUtils;

    @RequestMapping(value = "/generateWeChatMpQrCode", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "生成微信公众号二维码")
    public ResponseData generateWeChatMpQrCode(@RequestParam(value = "outTradeNo" , required = false) String outTradeNo,
                                               @RequestParam(value = "qrCodeSn" , required = false) String qrCodeSn,
                                               @RequestParam(value = "type" , required = true) Integer type,
                                               @RequestParam(value = "systemType" , required = true) Integer systemType) {
        try {
            System.out.println("outTradeNo="+outTradeNo+"&qrCodeSn="+"&type="+type+"&systemType="+systemType);

            JSONObject response = HttpsUtils.doGet(CommonSysConst.getSysConfig().getHsg_domain_name() + "/v1/wxMsg/getWxToken");
            if (StringUtils.isBlank(response.getString("return_data"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "获取token失败");
            }
            BsTradeOrder tradeNo = tradeOrderService.getOrderByOutTradeNoOrPlatformTradeNo(outTradeNo);
            if (tradeNo == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单");
            }
            String param = tradeNo.getOutTradeNo();
            String fileUrl = "/share/" + System.currentTimeMillis() + ".png";

            // type 生成类型
            // 1：支付交易成功后
            // 2：分享关注公众号
            if (type == 1) {
                // systemType系统类型；1：安卓  2：IOS
                if (systemType == 1) {
                    // 生成支付二维码
                    QRCodeGenerator.generateQRCodeImage(
                            weChatQrcodeUtils.generateQrCodeImgUrl(response.getString("return_data"), WeChatQrCodeTypeEnum.PAYMENT_SUCCESS, param, WeChatQrCodeActionNameEnum.actionName1),
                            260,
                            260,
                            CommonSysConst.getSysConfig().getFilesystem() + fileUrl
                    );
                    QRCodeGenerator.overlapImage(fileUrl, "/template/qrCodeBackdrop1_1.png",740,110);
                } else if (systemType == 2) {
                    // 生成支付二维码
                    QRCodeGenerator.generateQRCodeImage(
                            weChatQrcodeUtils.generateQrCodeImgUrl(response.getString("return_data"), WeChatQrCodeTypeEnum.PAYMENT_SUCCESS, param, WeChatQrCodeActionNameEnum.actionName1),
                            260,
                            260,
                            CommonSysConst.getSysConfig().getFilesystem() + fileUrl
                    );
                    QRCodeGenerator.overlapImage(fileUrl, "/template/qrCodeBackdrop1_2.png",740,110);
                }

            } else if (type == 2) {
                // systemType系统类型；1：安卓  2：IOS
                if (systemType == 1) {
                    // 生成支付二维码
                    QRCodeGenerator.generateQRCodeImage(
                            weChatQrcodeUtils.generateQrCodeImgUrl(response.getString("return_data"), WeChatQrCodeTypeEnum.SHARE, param, WeChatQrCodeActionNameEnum.actionName1),
                            578,
                            578,
                            CommonSysConst.getSysConfig().getFilesystem() + fileUrl
                    );
                    QRCodeGenerator.overlapImage(fileUrl, "/template/qrCodeBackdrop2_1.png",250,650);

                } else if (systemType == 2) {
                    // 生成支付二维码
                    QRCodeGenerator.generateQRCodeImage(
                            weChatQrcodeUtils.generateQrCodeImgUrl(response.getString("return_data"), WeChatQrCodeTypeEnum.SHARE, param, WeChatQrCodeActionNameEnum.actionName1),
                            578,
                            578,
                            CommonSysConst.getSysConfig().getFilesystem() + fileUrl
                    );
                    QRCodeGenerator.overlapImage(fileUrl, "/template/qrCodeBackdrop2_2.png",250,650);
                }
            }
            return ResponseMsgUtil.success(CommonSysConst.getSysConfig().getDomainName() + "/filesystem" + fileUrl);

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

    @RequestMapping(value = "/getReceiveDiscountList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询领取优惠列表")
    public ResponseData getReceiveDiscountList(@RequestParam(value = "qrCodeSn" , required = true) String qrCodeSn,
                                               @RequestParam(value = "partakeWay" , required = true) Integer partakeWay) {
        try {

            BsPayQrCode qrCode = payQrCodeService.getDetailBySN(qrCodeSn);
            if (qrCode == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知二维码");
            }
            if (qrCode.getStoreId() == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未绑定门店");
            }
            // 查询门店
            BsStore store = storeService.getStoreById(qrCode.getStoreId());
            if (store == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的门店");
            }
            List<BsStoreDiscountActivity> discountActivityList = new ArrayList<>();

            // 门店活动
            Map<String, Object> param = new HashMap<>();
            param.put("storeId", store.getId());
            param.put("partakeWay", partakeWay);
            param.put("status", StoreDiscountActivityStatusEnum.status2.getNumber());
            discountActivityList.addAll(storeDiscountActivityService.getActivityList(param));

            param.clear();
            // 商户活动
            param.put("partakeWay", partakeWay);
            param.put("merId", store.getMerId());
            param.put("storeIdNull", 0);
            param.put("status", StoreDiscountActivityStatusEnum.status2.getNumber());
            discountActivityList.addAll(storeDiscountActivityService.getActivityList(param));

            return ResponseMsgUtil.success(discountActivityList);

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

    @RequestMapping(value = "/receiveDiscount", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "领取优惠")
    public ResponseData receiveDiscount(@RequestBody JSONObject body) {
        try {
            if (StringUtils.isBlank(body.getString("phone"))
                    || body.getJSONArray("activityIds") == null
                    || body.getJSONArray("activityIds").size() == 0
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            List<Long> activityIds = new ArrayList<>();
            for (Object obj : body.getJSONArray("activityIds")) {
                JSONObject activity = (JSONObject) obj;
                if (activity == null || activity.getLong("id") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
                activityIds.add(activity.getLong("id"));
            }
            storeDiscountActivityPartakeUserService.receiveDiscount(body.getString("phone"), activityIds);

            return ResponseMsgUtil.success("领取成功");

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

    @RequestMapping(value = "/getDiscountListByPhone", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据手机号获取优惠列表")
    public ResponseData getDiscountListByPhone(@RequestParam(value = "phone" , required = true) String phone,
                                               @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("userPhone", phone);
            param.put("status", status);

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

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

    @RequestMapping(value = "/getDiscountSurplusTotalNum", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据手机号获取可用优惠总次数")
    public ResponseData getDiscountSurplusTotalNum(@RequestParam(value = "phone" , required = true) String phone) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("userPhone", phone);
            param.put("status", 1);

            Integer countNum = 0;
            List<BsStoreDiscountActivityPartakeUser> list = storeDiscountActivityPartakeUserService.getList(param);
            for (BsStoreDiscountActivityPartakeUser discountActivityPartakeUser : list) {
                countNum += discountActivityPartakeUser.getPartakeSurplusNum();
            }
            return ResponseMsgUtil.success(countNum);

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

}
