package com.gree.mall.manager.logic.activity;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.activity.PromotionQuestionnaireAddBean;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.GoodsMaterialVO;
import com.gree.mall.manager.bean.listvo.PromotionQuestionnairVO;
import com.gree.mall.manager.bean.listvo.param.PromotionZfireParamBean;
import com.gree.mall.manager.commonmapper.CommonMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.PromotionQuestionnaire;
import com.gree.mall.manager.plus.entity.PromotionQuestionnaireItem;
import com.gree.mall.manager.plus.entity.PromotionQuestionnaireQrcode;
import com.gree.mall.manager.plus.entity.PromotionQuestionnaireUser;
import com.gree.mall.manager.plus.service.PromotionQuestionnaireItemService;
import com.gree.mall.manager.plus.service.PromotionQuestionnaireQrcodeService;
import com.gree.mall.manager.plus.service.PromotionQuestionnaireService;
import com.gree.mall.manager.plus.service.PromotionQuestionnaireUserService;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.oss.OSSUtil;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 问卷活动业务
 * @author ：lijh
 * @description：TODO
 * @date ：2024/5/7 10:31
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PromotionQuestionnaireLogic {

    @Value("${wechat.mp.url}")
    private String mpUrl;

    private final CommonLogic commonLogic;
    private final OSSUtil ossUtil;

    private final CommonMapper commonMapper;
    private final PromotionQuestionnaireService promotionQuestionnaireService;
    private final PromotionQuestionnaireItemService promotionQuestionnaireItemService;
    private final PromotionQuestionnaireUserService promotionQuestionnaireUserService;
    private final PromotionQuestionnaireQrcodeService promotionQuestionnaireQrcodeService;

    /**
     * 问卷活动列表
     * @param zfireParamBean
     * @return
     */
    public IPage<PromotionQuestionnairVO> list(PromotionZfireParamBean zfireParamBean){
        FieldUtils.supplyParam(zfireParamBean, PromotionQuestionnairVO.class, commonLogic.getAdminUser());
        IPage<PromotionQuestionnairVO> page = commonMapper.promotionQuestionnairList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean,zfireParamBean.getStatus());
        return page;
    }


    /**
     * 新增问卷活动
     * @param promotionQuestionnaireAddBean
     */
    @Transactional
    public void add(PromotionQuestionnaireAddBean promotionQuestionnaireAddBean) throws IOException {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        //检查活动名称不能重复
        Integer count = promotionQuestionnaireService.lambdaQuery()
                .ne(StringUtils.isNotBlank(promotionQuestionnaireAddBean.getId()),PromotionQuestionnaire::getId,promotionQuestionnaireAddBean.getId())
                .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()),PromotionQuestionnaire::getCompanyWechatId,adminUser.getCompanyWechatId())
                .eq(PromotionQuestionnaire::getName, promotionQuestionnaireAddBean.getName())
                .count();
        if(count > 0){
            throw new RemoteServiceException("活动名称已存在");
        }
        if(promotionQuestionnaireAddBean.getTitle().length() > 8){
            throw new RemoteServiceException("活动主题最多支持8个字符");
        }
        Boolean addFlag = StringUtils.isBlank(promotionQuestionnaireAddBean.getId());
        if(addFlag){
            promotionQuestionnaireAddBean.setId(IdWorker.getIdStr());
        }
        if(adminUser.getAdminCompanyWechat() == null){
            throw new RemoteServiceException("请使用租户账号操作");
        }
        //新增才生成二维码
        if(addFlag) {
            String qrcodeFilePath = genQrcode(promotionQuestionnaireAddBean.getId(),adminUser.getAdminCompanyWechat().getSubAppId(),promotionQuestionnaireAddBean.getTitle(),"");
            promotionQuestionnaireAddBean.setQrcode(qrcodeFilePath);
        }
        promotionQuestionnaireAddBean.setCreateMobile(adminUser.getLinkPhone());
        promotionQuestionnaireAddBean.setCompanyWechatId(adminUser.getCompanyWechatId());
        promotionQuestionnaireAddBean.setCompanyWechatName(adminUser.getCompanyName());
        promotionQuestionnaireAddBean.insertOrUpdate();
        //提交记录
        promotionQuestionnaireUserService.lambdaUpdate().eq(PromotionQuestionnaireUser::getPromotionQuestionnaireId,promotionQuestionnaireAddBean.getId()).remove();
        if(CollectionUtils.isNotEmpty(promotionQuestionnaireAddBean.getPromotionQuestionnaireUsers())) {
            promotionQuestionnaireAddBean.getPromotionQuestionnaireUsers().forEach(v -> v.setPromotionQuestionnaireId(promotionQuestionnaireAddBean.getId()));
            promotionQuestionnaireUserService.saveOrUpdateBatch(promotionQuestionnaireAddBean.getPromotionQuestionnaireUsers());
        }
        //题目
        promotionQuestionnaireItemService.lambdaUpdate().eq(PromotionQuestionnaireItem::getPromotionQuestionnaireId,promotionQuestionnaireAddBean.getId()).remove();
        if(CollectionUtils.isNotEmpty(promotionQuestionnaireAddBean.getPromotionQuestionnaireItems())) {
            promotionQuestionnaireAddBean.getPromotionQuestionnaireItems().forEach(v -> v.setPromotionQuestionnaireId(promotionQuestionnaireAddBean.getId()));
            promotionQuestionnaireItemService.saveOrUpdateBatch(promotionQuestionnaireAddBean.getPromotionQuestionnaireItems());
        }
        //后生成二维码
        if(CollectionUtils.isNotEmpty(promotionQuestionnaireAddBean.getPromotionQuestionnaireQrcodes())){
            //检查是否有重复的网点名称
            long count2 = promotionQuestionnaireAddBean.getPromotionQuestionnaireQrcodes().stream().map(PromotionQuestionnaireQrcode::getWebsitName).distinct().count();
            if(promotionQuestionnaireAddBean.getPromotionQuestionnaireQrcodes().size() != count2){
                throw new RemoteServiceException("网点名称不能重复");
            }

            for(PromotionQuestionnaireQrcode promotionQuestionnaireQrcode : promotionQuestionnaireAddBean.getPromotionQuestionnaireQrcodes()){
                if(StringUtils.isBlank(promotionQuestionnaireQrcode.getWebsitName())){
                    throw new RemoteServiceException("网点名称不能为空");
                }
                promotionQuestionnaireQrcode.setPromotionQuestionnaireId(promotionQuestionnaireAddBean.getId());
                String qrcodeFilePath = genQrcode(promotionQuestionnaireAddBean.getId(),adminUser.getAdminCompanyWechat().getSubAppId(),
                        promotionQuestionnaireAddBean.getTitle(),promotionQuestionnaireQrcode.getWebsitName());
                promotionQuestionnaireQrcode.setQrcode(qrcodeFilePath);
            }
            //删除本次未提交的数据
            List<String> ids = promotionQuestionnaireAddBean.getPromotionQuestionnaireQrcodes().stream()
                    .filter(item -> !StringUtil.isEmpty(item.getId())).map(PromotionQuestionnaireQrcode::getId).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(ids)) {
                promotionQuestionnaireQrcodeService.lambdaUpdate().notIn(PromotionQuestionnaireQrcode::getId, ids)
                        .eq(PromotionQuestionnaireQrcode::getPromotionQuestionnaireId, promotionQuestionnaireAddBean.getId())
                        .remove();
            }
            promotionQuestionnaireQrcodeService.saveOrUpdateBatch(promotionQuestionnaireAddBean.getPromotionQuestionnaireQrcodes());
        }
    }


    /**
     * 下载二维码
     * @param id 活动id
     * @param id2 活动明细二维码id
     */
    public void batchDownload(String id, String id2, HttpServletResponse response) throws IOException {
        PromotionQuestionnaire promotionQuestionnaire = promotionQuestionnaireService.getById(id);
        List<PromotionQuestionnaireQrcode> list = promotionQuestionnaireQrcodeService.lambdaQuery()
                .eq(PromotionQuestionnaireQrcode::getPromotionQuestionnaireId, id)
                .eq(StringUtils.isNotBlank(id2),PromotionQuestionnaireQrcode::getId, id2).list();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        List<Map<String,Object>> files = new ArrayList<>();
        //String fileUrl = comDetail.getFileUrl();
        for(PromotionQuestionnaireQrcode bean : list) {
            //String fileUrl = ossUtil.getUrlWw(bean.getQrcode());
            String fileUrl = bean.getQrcode();
            Map<String,Object> map = new HashMap<>();
            map.put("fileUrl",fileUrl);
            map.put("fileName",promotionQuestionnaire.getTitle()+"-("+bean.getWebsitName()+").png");
            files.add(map);
        }
        if(files.size() > 1) {
            CommonUtils.writeZip(response,promotionQuestionnaire.getTitle(), files);
        }else{
            CommonUtils.downloadFile(files.get(0).get("fileUrl").toString(),files.get(0).get("fileName").toString(),response);
        }
    }



    /**
     * 生成二维码
     * @param id 活动id
     * @param subAppId 公众号id
     * @param title 二维码中间的活动主题
     * @param websitName 网点名称
     * @return
     */
    private String genQrcode(String id,String subAppId,String title,String websitName){
        // 生成二维码
        String content = mpUrl + "packageHome/pages/codeActivity/activityForm?id=" + id + "&appid=" + subAppId+"&websitName="+websitName;
        BufferedImage qrImage = QrCodeUtil.generate(content, 300, 300);

        // 中间文字配置
        Font font = new Font("微软雅黑", Font.BOLD, 20);
        // 将文字写在二维码中央
        //插入的图片
        BufferedImage image = ImgUtil.createImage(title, font, Color.WHITE, Color.RED, ColorSpace.TYPE_3CLR);

        //insertTextToQrCode(qrImage, title, font, Color.red, (qrImage.getWidth() - 30 * title.length()) / 2, qrImage.getHeight() / 2);
        ImgUtil.pressImage(qrImage, image, 0, 0, 1);

        byte[] bytes = ImgUtil.toBytes(qrImage, "png");
        String qrcodeFilePath = ossUtil.uploadFile(bytes, "png");
        return qrcodeFilePath;
    }


    /**
     * 是否显示隐藏
     * @param id
     * @param isShow
     */
    public void updateIsShow(String id,Boolean isShow){
        promotionQuestionnaireService.lambdaUpdate()
                .set(PromotionQuestionnaire::getIsShow,isShow)
                .eq(PromotionQuestionnaire::getId,id).update();
    }

    /**
     * 问卷活动详情
     * @param id
     * @return
     */
    public PromotionQuestionnaireAddBean detail(String id){
        PromotionQuestionnaire promotionQuestionnaire = promotionQuestionnaireService.getById(id);
        PromotionQuestionnaireAddBean bean = BeanUtil.copyProperties(promotionQuestionnaire, PromotionQuestionnaireAddBean.class);
        //提交记录
        List<PromotionQuestionnaireUser> promotionQuestionnaireUsers = promotionQuestionnaireUserService.lambdaQuery().eq(PromotionQuestionnaireUser::getPromotionQuestionnaireId, id).list();
        bean.setPromotionQuestionnaireUsers(promotionQuestionnaireUsers);
        //题目
        List<PromotionQuestionnaireItem> promotionQuestionnaireItems = promotionQuestionnaireItemService.lambdaQuery().eq(PromotionQuestionnaireItem::getPromotionQuestionnaireId, id).list();
        bean.setPromotionQuestionnaireItems(promotionQuestionnaireItems);
        //状态
        if(bean.getIsStop()){
            bean.setStatus(3);
        }else {
            if (bean.getStartTime().getTime() > new Date().getTime()) {
                bean.setStatus(0);
            } else if (bean.getEndTime().getTime() < new Date().getTime()) {
                bean.setStatus(2);
            } else {
                bean.setStatus(1);
            }
        }
        //网点的二维码
        List<PromotionQuestionnaireQrcode> qrcodes = promotionQuestionnaireQrcodeService.lambdaQuery().eq(PromotionQuestionnaireQrcode::getPromotionQuestionnaireId, id).list();
        bean.setPromotionQuestionnaireQrcodes(qrcodes);
        return bean;
    }


    /**
     * 终止
     * @param id
     */
    public void stop(String id){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        PromotionQuestionnaire promotionQuestionnaire = promotionQuestionnaireService.getById(id);
        promotionQuestionnaire.setIsStop(true);
        promotionQuestionnaire.setStopBy(adminUser.getNickName());
        promotionQuestionnaire.setStopTime(new Date());
        promotionQuestionnaire.updateById();
    }


//    public static void main(String[] args){
//        String title = "江西问卷活动";
//
//        BufferedImage qrImage = QrCodeUtil.generate("123", 300, 300);
//        BufferedImage image = ImgUtil.createImage(title, new Font("", Font.BOLD, 30), Color.WHITE, Color.RED, ColorSpace.TYPE_3CLR);
//        ImgUtil.pressImage(qrImage,image,0, 0,1);
//
//        ImgUtil.write(qrImage, FileUtil.file("D:\\1.png"));
//    }


//    private static void insertTextToQrCode(BufferedImage qrImage, String text, Font font, Color color, int x, int y) {
//        Graphics2D codeGraphics = (Graphics2D) qrImage.getGraphics();
//        codeGraphics.setFont(font);
//        codeGraphics.setColor(color);
//        codeGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//        codeGraphics.drawString(text, x, y);
//        codeGraphics.dispose();
//    }

}
