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.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;

/**
 * @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;

    @Override
    public PageInfo<WxTopic> listAsPage(WxTopic record, Integer pageIndex, Integer pageSize) {
        wxTopicMapper.updateStatus(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.selectByPrimaryKey(record.getId());
                query.setBeginTime(wt.getBeginTime());
                query.setEndTime(wt.getEndTime());
            }else{
                query.setBeginTime(record.getBeginTime());
                query.setEndTime(record.getEndTime());
            }
            List<WxTopic> topicList = wxTopicMapper.findExist(query);
            if (CollectionUtils.isNotEmpty(topicList)) {
                return new ResultData(ErrorCode.SYS_REPEAT_SUBMIT_EXCEPTION.getCode(), "["+topicList.get(0).getName()+"]正在活动中，截止至"+ DateUtils.date2String(topicList.get(0).getEndTime(),"yyyy-MM-dd"));
            }
        }
        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            wxTopicMapper.insertSelective(record);

            if(StringUtils.isNotBlank(record.getCouponIds())) {
                addCouponTopic(record);
            }
            return new ResultData(Result.SUCCESS,"添加成功");
        } else {
            record.setUpdatetime(new Date());
            wxTopicMapper.updateByPrimaryKeySelective(record);
            if(StringUtils.isNotBlank(record.getCouponIds())) {
                wxCouponChannelMapper.delByTopic(record);
                addCouponTopic(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.selectByPrimaryKey(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());
            wxCouponChannelMapper.insertSelective(wxCouponChannel);
        }
    }

    @Override
    public WxTopic findById(WxTopic record) {
        WxTopic wxTopic = wxTopicMapper.selectByPrimaryKey(record.getId());
        wxTopic.setCouponList(wxCouponMapper.findCouponByTopic(record));
        return wxTopic;
    }
}
