package com.iformall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxActivity;
import com.iformall.domain.po.WxActivityJoin;
import com.iformall.domain.po.WxCampaign;
import com.iformall.enums.*;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxActivityJoinMapper;
import com.iformall.mapper.WxActivityMapper;
import com.iformall.mapper.WxCampaignMapper;
import com.iformall.service.WxActivityService;
import com.iformall.service.WxCampaignService;
import org.apache.commons.lang3.StringUtils;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;

/**
 * @author gongbiao
 */
@Service
public class WxActivityServiceImpl implements WxActivityService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxActivityMapper wxActivityMapper;
    @Autowired
    WxCampaignService wxCampaignService;
    @Autowired
    WxCampaignMapper wxCampaignMapper;
    @Autowired
    WxActivityJoinMapper wxActivityJoinMapper;
    @Override
    public PageInfo<WxActivity> listAsPage(WxActivity record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxActivityMapper.findList(record));
    }

    @Override
    public WxActivity getById(Long id) {
        WxActivity wxActivity = wxActivityMapper.selectById(id);
        if (wxActivity == null) {
            return null;
        }
        String html = wxActivity.getHtml();
        if (!StringUtils.isEmpty(html)) {
            try {
                html = URLDecoder.decode(html, "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.info("图文内容解码失败");
            }
            wxActivity.setHtml(html);
        }
        return wxActivity;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public ResultData saveOrUpdate(WxActivity wxActivity) {
        if (wxActivity.getType().equals(EnumActivityType.STABLE.getCode())) {
            if (StringUtils.isEmpty(wxActivity.getCoverImg())) {
                return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "封面图不能为空");
            }
            if (StringUtils.isEmpty(wxActivity.getTitle())) {
                return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "标题不能为空");
            }
            if (StringUtils.isEmpty(wxActivity.getDetail())) {
                return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "活动说明不能为空");
            }
        } else if (wxActivity.getType().equals(EnumActivityType.FREE.getCode())) {
            if (StringUtils.isEmpty(wxActivity.getHtml())) {
                return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "图文不能为空");
            }
            int length = wxActivity.getHtml().getBytes().length;
            if (length >= 0xFFFFFF) { //Mysql MiddleText length limited
                return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "图文内容过大无法保存");
            }
        } else {
            return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);
        }
        wxActivity.setStatus(EnumActivityStatus.STATUS_THROW_IN.getCode());
        if (wxActivity.getEndTime().before(new Date())) {
            throw new MallinkException(ErrorCode.ACTIVITY_JOIN_TIME_END);
        }
        if (wxActivity.getEndTime().after(wxActivity.getActivityEndTime())) {
            throw new MallinkException(ErrorCode.ACTIVITY_TIME_ERROR);
        }
        Date date = new Date();
        wxActivity.setCreateTime(date);
        wxActivity.setUpdateTime(date);
        if (wxActivity.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            wxActivity.setId(idWorker.nextId());
            wxActivityMapper.insert(wxActivity);
        } else {
            wxActivityMapper.updateById(wxActivity);
        }
        return new ResultData(Result.SUCCESS, "操作成功");
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public ResultData updateStatus(WxActivity wxActivity) {
        WxActivity activity = wxActivityMapper.selectById(wxActivity.getId());
        if (activity == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_ERROR);
        }
        wxActivity.setUpdateTime(new Date());
        wxActivityMapper.updateById(wxActivity);
        if (wxActivity.getStatus().equals(EnumActivityStatus.STATUS_TAKE_OFFF.getCode())) {
            WxCampaign campaign = new WxCampaign();
            campaign.setProduceId(wxActivity.getId());
            WxCampaign wxCampaign = wxCampaignMapper.selectOne(new QueryWrapper(campaign));
            wxCampaign.setStatus(EnumCampaignStatus.STATUS_TAKE_OFFF.getCode());
            wxCampaignMapper.updateById(wxCampaign);
        }
        return new ResultData(Result.SUCCESS, "操作成功");
    }

    @Override
    public void printHtmlById(Long id, HttpServletResponse response) {
        try {
            response.setHeader("Content-type", "text/html;charset=utf-8");
            WxActivity wxActivity = wxActivityMapper.selectById(id);
            String html = StringUtils.isEmpty(wxActivity.getHtml()) ? "" : wxActivity.getHtml();
            try {
                html = URLDecoder.decode(html, "utf-8");
            } catch (UnsupportedEncodingException e) {
                logger.info("图文内容解码失败");
            }
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            InputStream inStream = new ByteArrayInputStream(html.getBytes());
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (Exception e) {
            logger.info("输出富文本内容" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public ResultData sendToCampaign(Long id) {
        WxCampaign campaignQuery = new WxCampaign();
        campaignQuery.setStatus(EnumCampaignStatus.STATUS_THROW_IN.getCode());
        int count = wxCampaignMapper.selectCount(new QueryWrapper(campaignQuery));
        int campaignTotal = 7;
        if (count == campaignTotal) {
            return new ResultData(ErrorCode.ACTIVITY_SEND_ERROR);
        }
        //修改投放状态
        WxActivity wxActivity = wxActivityMapper.selectById(id);
        if (wxActivity.getEndTime().before(new Date())) {
            return new ResultData(ErrorCode.ACTIVITY_JOIN_TIME_END);
        }
        wxActivity.setStatus(EnumActivityStatus.INJECT_CAMPAIGN.getCode());
        wxActivity.setUpdateTime(new Date());
        wxActivityMapper.updateById(wxActivity);
        //添加到宣传页
        campaignQuery = new WxCampaign();
        campaignQuery.setProduceId(id);
        WxCampaign campaign = wxCampaignMapper.selectOne(new QueryWrapper(campaignQuery));
        if (campaign == null) {
            campaign = new WxCampaign();
        }
        campaign.setCoverImg(wxActivity.getCoverImg());
        campaign.setTenantId(wxActivity.getTenantId());
        campaign.setTitle(wxActivity.getTitle());
        campaign.setSubTitle(wxActivity.getSubTitle());
        campaign.setDetail(wxActivity.getDetail());
        campaign.setValidStartDate(wxActivity.getStartTime());
        campaign.setValidEndDate(wxActivity.getEndTime());
        campaign.setType(EnumCampaignType.PAGEPATH.getCode());
        campaign.setHtml(wxActivity.getHtml());
        campaign.setProduceType(EnumCampaignProductType.ACTIVITY_JOIN.getCode());
        campaign.setProduceId(wxActivity.getId());
        campaign.setPagePath(wxActivity.getWeappPath());
        campaign.setPageScene(wxActivity.getWeappSceneForJoin());
        return wxCampaignService.addForPath(campaign);

    }

    @Override
    public Integer queryStatus(Long id, Long userId) {
        WxActivity wxActivity = wxActivityMapper.selectById(id);
        WxActivityJoin activityJoin = new WxActivityJoin();
        activityJoin.setUserId(userId);
        activityJoin.setActivityId(id);
        activityJoin.setTenantId(wxActivity.getTenantId());
        //查询是否已参加报名
        //下线 就是 结束
        if (wxActivity.getStatus().equals(EnumActivityStatus.STATUS_TAKE_OFFF.getCode())) {
            return EnumActivityEnrollStatus.END.getCode();
        }
        //未投放 就是 未开始
        if (wxActivity.getStatus().equals(EnumActivityStatus.STATUS_THROW_IN.getCode())) {
            return EnumActivityEnrollStatus.NOT_START.getCode();
        }
        Date date = new Date();
        if (wxActivity.getStatus().equals(EnumActivityStatus.INJECT_CAMPAIGN.getCode())) {
            //报名未开始
            if (wxActivity.getStartTime().after(date)) {
                return EnumActivityEnrollStatus.NOT_START.getCode();
            }
            if (wxActivity.getEndTime().before(date)) {
                //报名结束
                return EnumActivityEnrollStatus.END.getCode();
            }
        }
        int count = wxActivityJoinMapper.selectCount(new QueryWrapper(activityJoin));
        if (count > 0) {
            return EnumActivityEnrollStatus.JOINED.getCode();
        }
        return EnumActivityEnrollStatus.NORMAL.getCode();
    }


}
