package com.huiju.estateagents.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.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.TaCustomerFrom;
import com.huiju.estateagents.excel.redPacket.RedPacketVisitRecordtExport;
import com.huiju.estateagents.redpack.entity.TaH5Images;
import com.huiju.estateagents.redpack.entity.TaRedPacket;
import com.huiju.estateagents.redpack.mapper.TaH5ImagesMapper;
import com.huiju.estateagents.redpack.mapper.TaRedPacketMapper;
import com.huiju.estateagents.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.LocalDate;
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;

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

        // 初始化数据
        taRedPacketMapper.initRedPacket(record.getActivityId(), record.getName(), record.getQrcode(), record.getStartDate(), record.getEndDate(),record.getTempleActivityId(), record.getOrgId());
        taRedPacketMapper.initRedPacketHelp(record.getActivityId(),record.getTempleActivityId());
        taRedPacketMapper.initRedPacketClient(record.getActivityId(),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) {
        ResponseBean responseBean = new ResponseBean();
        Boolean updateResult = updateById(taRedPacket);
        if (!updateResult) {
            responseBean.addError("fail");
            return responseBean;
        }
        saveRedPacketImages(taRedPacket, 2);
        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 -> {
            switch (r.getActivityType()) {
                case "rp_share_post_img":
                    record.setSharePosterImg(r.getImageUrl());
                    break;
                case "rp_activity_rules_img":
                    record.setActivityRulesImg(r.getImageUrl());
                    break;
                case "rp_help_background_img":
                    record.setHelpBackgroundImg(r.getImageUrl());
                    break;
                case "rp_index_background_img":
                    record.setIndexBackgroundImg(r.getImageUrl());
                    break;
                case "rp_ranking_background_img":
                    record.setRankingBackgroundImg(r.getImageUrl());
                    break;
                default:
                    break;
            }
        });
        return record;
    }

    @Override
    public ResponseBean listVisitRecordByCondition(Integer pageNum, Integer pageSize, LocalDate startTime, LocalDate 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(LocalDate startTime, LocalDate 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());

        // 新增
        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);
            });
        }
    }
}
