package com.yunzhi.marketing.redpack.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.drainage.entity.TaDrainage;
import com.yunzhi.marketing.drainage.mapper.TaDrainageMapper;
import com.yunzhi.marketing.entity.TaCustomerFrom;
import com.yunzhi.marketing.entity.TaMiniapp;
import com.yunzhi.marketing.excel.redPacket.RedPacketVisitRecordtExport;
import com.yunzhi.marketing.mapper.TaMiniappMapper;
import com.yunzhi.marketing.redpack.entity.TaH5Images;
import com.yunzhi.marketing.redpack.entity.TaRedPacket;
import com.yunzhi.marketing.redpack.mapper.TaH5ImagesMapper;
import com.yunzhi.marketing.redpack.mapper.TaRedPacketMapper;
import com.yunzhi.marketing.redpack.service.ITaRedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 红包助力活动  服务实现类
 * </p>
 *
 * @author fxf
 * @since 2020-06-03
 */
@Service
public class TaRedPacketServiceImpl extends ServiceImpl<TaRedPacketMapper, TaRedPacket> implements ITaRedPacketService {

    private Logger logger = LoggerFactory.getLogger(TaRedPacketServiceImpl.class);

    @Autowired
    private TaRedPacketMapper taRedPacketMapper;

    @Autowired
    private TaH5ImagesMapper taH5ImagesMapper;

    @Autowired
    private TaMiniappMapper taMiniappMapper;

    @Autowired
    private TaDrainageMapper taDrainageMapper;

    @Override
    @Transactional
    public ResponseBean initializeRedPacket(TaRedPacket record, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();

        // 获取小程序信息
        QueryWrapper<TaMiniapp> miniappQueryWrapper = new QueryWrapper<>();
        miniappQueryWrapper.eq("org_id", orgId);
        TaMiniapp taMiniapp = taMiniappMapper.selectOne(miniappQueryWrapper);

        // 初始化数据
        taRedPacketMapper.initRedPacket(record.getActivityId(), record.getName(), record.getQrcode(), record.getStartDate(), record.getEndDate(), record.getTempleActivityId(), record.getBuildingId(), record.getOrgId());
        taRedPacketMapper.initRedPacketHelp(record.getActivityId(), record.getTempleActivityId());
        taRedPacketMapper.initRedPacketClient(record.getActivityId(), record.getName(), taMiniapp.getName(), record.getTempleActivityId());
        taRedPacketMapper.initRedPacketMoney(record.getActivityId(), record.getTempleActivityId());
        taRedPacketMapper.initRedPacketImages(record.getActivityId(), record.getTempleActivityId());
        responseBean.addSuccess("success");
        return responseBean;
    }

    @Override
    public ResponseBean updateRedPacket(TaRedPacket taRedPacket,Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        Boolean updateResult = updateById(taRedPacket);
        if (!updateResult) {
            responseBean.addError("fail");
            return responseBean;
        }
        saveRedPacketImages(taRedPacket, 2);

        // 更新H5活动数据
        UpdateWrapper<TaDrainage> taDrainageUpdateWrapper = new UpdateWrapper<>();
        taDrainageUpdateWrapper.eq("activity_id", taRedPacket.getActivityId());
        taDrainageUpdateWrapper.eq("status", CommConstant.STATUS_NORMAL);
        taDrainageUpdateWrapper.eq("org_id", orgId);

        TaDrainage taDrainage = new TaDrainage();
        taDrainage.setBuildingId(taRedPacket.getBuildingId());

        taDrainageMapper.update(taDrainage, taDrainageUpdateWrapper);
        responseBean.addSuccess("success");
        return responseBean;
    }

    @Override
    public TaRedPacket getRedPacketImages(TaRedPacket record) {

        // 查询红包配置图片信息
        QueryWrapper<TaH5Images> h5ImagesQueryWrapper = new QueryWrapper<>();
        h5ImagesQueryWrapper.eq("activity_id", record.getActivityId());
        List<TaH5Images> h5ImagesList = taH5ImagesMapper.selectList(h5ImagesQueryWrapper);
        h5ImagesList.stream().forEach(r -> {
            String img = r.getImageUrl();

            switch (r.getImageType()) {
                case "RedPacket.rp_share_post_img":
                    record.setSharePosterImg(img);
                    break;
                case "RedPacket.rp_activity_rules_img":
                    record.setActivityRulesImg(img);
                    break;
                case "RedPacket.rp_help_background_img":
                    record.setHelpBackgroundImg(img);
                    break;
                case "RedPacket.rp_index_background_img":
                    record.setIndexBackgroundImg(img);
                    break;
                case "RedPacket.rp_ranking_background_img":
                    record.setRankingBackgroundImg(img);
                    break;

                case "RedPacket.rp_invite_btn_img":
                    record.setInviteBtnImg(img);
                    break;

                case "RedPacket.rp_rule_btn_img":
                    record.setRuleBtnImg(img);
                    break;

                case "RedPacket.rp_join_btn_img":
                    record.setJoinBtnImg(img);
                    break;

                case "RedPacket.rp_top_btn_img":
                    record.setTopBtnImg(img);
                    break;

                case "RedPacket.rp_home_btn_img":
                    record.setHomeBtnImg(img);
                    break;

                case "RedPacket.rp_help_btn_img":
                    record.setHelpBtnImg(img);
                    break;

                case "RedPacket.rp_back_btn_img":
                    record.setBackBtnImg(img);
                    break;

                case "RedPacket.rp_poster_btn_img":
                    record.setPosterBtnImg(img);
                    break;

                case "RedPacket.rp_building_btn_img":
                    record.setBuildingBtnImg(img);
                    break;
                default:
                    break;
            }
        });
        return record;
    }

    @Override
    public ResponseBean listVisitRecordByCondition(Integer pageNum, Integer pageSize, LocalDateTime startTime, LocalDateTime endTime, String drainageId, String phone, String sharePersonPhone, Integer orgId) {
        ResponseBean responseBean = new ResponseBean();
        IPage<TaCustomerFrom> pg = new Page<>(pageNum, pageSize);
        responseBean.addSuccess(taRedPacketMapper.listVisitRecordByCondition(pg, startTime, endTime, drainageId, phone, sharePersonPhone, orgId));
        return responseBean;
    }

    @Override
    public void exportVisitRecordByCondition(LocalDateTime startTime, LocalDateTime endTime, String drainageId, String phone, String sharePersonPhone, Integer orgId, HttpServletResponse response) throws Exception {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        List<RedPacketVisitRecordtExport> records = taRedPacketMapper.exportVisitRecordByCondition(startTime, endTime, drainageId, phone, sharePersonPhone, orgId);
        String fileName = URLEncoder.encode("客户数据", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), RedPacketVisitRecordtExport.class).sheet("客户数据").doWrite(records);
    }

    /**
     * 保存/更新红包图片信息
     *
     * @param taRedPacket
     * @param type        1 新增,2 更新
     */
    public void saveRedPacketImages(TaRedPacket taRedPacket, Integer type) {
        // 组装红包图片数据
        Map<String, String> redPacketImsMap = new HashMap<>();
        redPacketImsMap.put("rp_share_post_img", taRedPacket.getSharePosterImg());
        redPacketImsMap.put("rp_activity_rules_img", taRedPacket.getActivityRulesImg());
        redPacketImsMap.put("rp_help_background_img", taRedPacket.getHelpBackgroundImg());
        redPacketImsMap.put("rp_index_background_img", taRedPacket.getIndexBackgroundImg());
        redPacketImsMap.put("rp_ranking_background_img", taRedPacket.getRankingBackgroundImg());

        redPacketImsMap.put("rp_invite_btn_img", taRedPacket.getInviteBtnImg());
        redPacketImsMap.put("rp_rule_btn_img", taRedPacket.getRuleBtnImg());
        redPacketImsMap.put("rp_join_btn_img", taRedPacket.getJoinBtnImg());
        redPacketImsMap.put("rp_top_btn_img", taRedPacket.getTopBtnImg());
        redPacketImsMap.put("rp_home_btn_img", taRedPacket.getHomeBtnImg());
        redPacketImsMap.put("rp_help_btn_img", taRedPacket.getHelpBtnImg());
        redPacketImsMap.put("rp_back_btn_img", taRedPacket.getBackBtnImg());
        redPacketImsMap.put("rp_poster_btn_img", taRedPacket.getPosterBtnImg());
        redPacketImsMap.put("rp_building_btn_img", taRedPacket.getBuildingBtnImg());

        // 新增
        if (1 == type) {
            redPacketImsMap.entrySet().stream().forEach(r -> {
                if (StringUtils.isEmpty(r.getValue())) {
                    return;
                }
                TaH5Images taH5Images = new TaH5Images();
                taH5Images.setActivityId(taRedPacket.getActivityId());
                taH5Images.setActivityType(CommConstant.RED_PACKET);
                taH5Images.setImageType(CommConstant.RED_PACKET + "." + r.getKey());
                taH5Images.setImageUrl(r.getValue());
                taH5Images.setCreateDate(LocalDateTime.now());
                taH5ImagesMapper.insert(taH5Images);
            });
        }

        // 更新
        if (2 == type) {
            redPacketImsMap.entrySet().stream().forEach(r -> {
                if (StringUtils.isEmpty(r.getValue())) {
                    return;
                }
                TaH5Images taH5Images = new TaH5Images();
                taH5Images.setImageUrl(r.getValue());

                UpdateWrapper<TaH5Images> h5ImagesUpdateWrapper = new UpdateWrapper<>();
                h5ImagesUpdateWrapper.eq("activity_id", taRedPacket.getActivityId());
                h5ImagesUpdateWrapper.eq("image_type", CommConstant.RED_PACKET + "." + r.getKey());
                taH5ImagesMapper.update(taH5Images, h5ImagesUpdateWrapper);
            });
        }
    }
}
