package com.iformall.service.impl;

import com.alibaba.fastjson.JSONArray;
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.domain.po.WxCoupon;
import com.iformall.domain.po.WxCouponChannel;
import com.iformall.domain.po.WxTopic;
import com.iformall.enums.EnumCouponChannelType;
import com.iformall.enums.EnumWxTopicStatus;
import com.iformall.mapper.WxCouponChannelMapper;
import com.iformall.mapper.WxCouponMapper;
import com.iformall.mapper.WxTopicMapper;
import com.iformall.service.QrCodeService;
import com.iformall.service.WxTopicService;
import com.iformall.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.iformall.common.ResultData;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author luozukai ^_^
 * @date 2019/3/28 17:02
 */
@Service
public class WxTopicServiceImpl implements WxTopicService {
    @Autowired
    private WxTopicMapper wxTopicMapper;
    @Autowired
    private WxCouponMapper wxCouponMapper;
    @Autowired
    private WxCouponChannelMapper wxCouponChannelMapper;
    @Autowired
    private QrCodeService qrCodeService;

    @Override
    public PageInfo<WxTopic> listAsPage(WxTopic record, Integer pageIndex, Integer pageSize) {
        wxTopicMapper.updateStatus(record);
        wxTopicMapper.couponDownLine(record);
        if(StringUtils.isNotBlank(record.getStatusStr())){
            String[] array = record.getStatusStr().split(",");
            List<Integer> integerList = new ArrayList<>();
            for (String status:array) {
                integerList.add(Integer.parseInt(status));
            }
            record.setStatusList(integerList);
        }
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxTopicMapper.findList(record));
    }

    @Override
    public WxTopic show(WxTopic record) {
        WxTopic wxTopic = wxTopicMapper.show(record);
        if(wxTopic != null) {
            wxTopic.setCouponList(wxCouponMapper.findCouponByTopic(record));
        }
        return wxTopic;
    }

    @Override
    public ResultData saveOrUpdate(WxTopic record) {
        //验证是否存在已发放的专题
        if(record.getStatus().equals(EnumWxTopicStatus.VAILD.getCode())) {
            WxTopic query = new WxTopic();
            query.setTenantId(record.getTenantId());
            if(record.getId() != null && record.getBeginTime() == null){
                WxTopic wt = wxTopicMapper.selectById(record.getId());
                query.setBeginTime(wt.getBeginTime());
                query.setEndTime(wt.getEndTime());
            }else{
                query.setBeginTime(record.getBeginTime());
                query.setEndTime(record.getEndTime());
            }
            WxTopic dbquery = new WxTopic();
            dbquery.setTenantId(record.getTenantId());
            dbquery.setStatus(EnumWxTopicStatus.VAILD.getCode());
            List<WxTopic> onLineTopicList = wxTopicMapper.findList(dbquery);
            for (WxTopic topic:onLineTopicList) {
                if(DateUtils.belongCalendar(query.getBeginTime(),topic.getBeginTime(),topic.getEndTime())
                        || DateUtils.belongCalendar(query.getEndTime(),topic.getBeginTime(),topic.getEndTime())
                        || (query.getBeginTime().before(topic.getBeginTime())&&query.getEndTime().after(topic.getEndTime()))  ){
                    return new ResultData(ErrorCode.SYS_REPEAT_SUBMIT_EXCEPTION.getCode(), "[" + topic.getName() + "]正在活动中，"+DateUtils.date2String(topic.getBeginTime(), "yyyy-MM-dd")+"至" + DateUtils.date2String(topic.getEndTime(), "yyyy-MM-dd"));
                }
            }
        }

        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            wxTopicMapper.insert(record);

            if(StringUtils.isNotBlank(record.getCouponIds())) {
                addCouponTopic(record);
            }
            return new ResultData(Result.SUCCESS,"添加成功");
        } else {
            record.setUpdatetime(new Date());
            wxTopicMapper.updateById(record);
            if(StringUtils.isNotBlank(record.getCouponIds())) {
                //优化：区分添加的和删除的
                wxCouponChannelMapper.delByTopic(record);
                addCouponTopic(record);
            }
            wxTopicMapper.couponDownLine(record);
            return new ResultData(Result.SUCCESS,"更新成功");
        }
    }

    public void addCouponTopic(WxTopic record){
        for (String couponId:JSONArray.parseArray(record.getCouponIds(), String.class)) {
            final IdWorker idWorker = IdWorker.get();
            String[] couponArray = couponId.split("-");
            //保存coupon_channel
            WxCoupon wxCoupon = wxCouponMapper.selectById(Long.parseLong(couponArray[1]));
            WxCouponChannel wxCouponChannel = new WxCouponChannel();
            wxCouponChannel.setId(idWorker.nextId());
            wxCouponChannel.setBeginTime(record.getBeginTime());
            wxCouponChannel.setEndTime(record.getEndTime());
            wxCouponChannel.setCouponId(Long.parseLong(couponArray[1]));
            wxCouponChannel.setSubTargetId(record.getId());
            wxCouponChannel.setTenantId(record.getTenantId());
            wxCouponChannel.setTitle(wxCoupon.getTitle());
            wxCouponChannel.setTargetAd(EnumCouponChannelType.COUPON_CHANNEL_ID_TOPIC.getCode());
            wxCouponChannel.setType(wxCoupon.getType());
            wxCouponChannel.setBusiness(wxCoupon.getBusiness());
            wxCouponChannel.setSubBusiness(wxCoupon.getSubBusiness());
            wxCouponChannelMapper.insert(wxCouponChannel);

            String pageUrl = "pages/index/index";
            WxCouponChannel couponChannel = new WxCouponChannel();
            couponChannel.setId(wxCouponChannel.getId());
            couponChannel.setType(wxCouponChannel.getType());
            String param = couponChannel.getWeappScene();
            ResultData resultDataQ = qrCodeService.uploadQrcode(wxCoupon.getTenantId(),1,pageUrl,param,0,"","","卷");
            Map<String,String> map = (Map)resultDataQ.data;
            if(map!=null && map.get("url") !=null) {
                String url = map.get("url");
                couponChannel.setQrCode(url);
                wxCouponChannelMapper.updateById(couponChannel);
            }
        }
    }

    @Override
    public WxTopic findById(WxTopic record) {
        WxTopic wxTopic = wxTopicMapper.selectById(record.getId());
        List<WxCoupon> wxCouponList = wxCouponMapper.findCouponByTopic(record);
        wxTopic.setCouponList(wxCouponList);
        String couponIds = "";
        if(CollectionUtils.isNotEmpty(wxCouponList)) {
            for (int i = 0; i < wxCouponList.size(); i++) {
                WxCoupon wxCoupon = wxCouponList.get(i);
                if (i == wxCouponList.size() - 1) {
                    couponIds += wxCoupon.getType() +"-"+ wxCoupon.getId().toString();
                } else {
                    couponIds +=  wxCoupon.getType() +"-"+ wxCoupon.getId().toString() + ",";
                }
            }
            wxTopic.setCouponIds(couponIds);
        }
        return wxTopic;
    }
}
