package com.huiju.estateagents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.entity.*;
import com.huiju.estateagents.excel.ShareChildRecordExport;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.entity.TaPerson;
import com.huiju.estateagents.entity.TaShareActivity;
import com.huiju.estateagents.entity.TaShareChildRecord;
import com.huiju.estateagents.entity.TaShareRecord;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.mapper.TaPointsRecordsMapper;
import com.huiju.estateagents.mapper.TaShareActivityMapper;
import com.huiju.estateagents.mapper.TaShareChildRecordMapper;
import com.huiju.estateagents.mapper.TaShareRecordMapper;
import com.huiju.estateagents.service.IMiniAppService;
import com.huiju.estateagents.service.ITaPointsRecordsService;
import com.huiju.estateagents.service.ITaShareChildRecordService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *   服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-10-18
 */
@Service
public class TaShareChildRecordServiceImpl extends ServiceImpl<TaShareChildRecordMapper, TaShareChildRecord> implements ITaShareChildRecordService {

    @Autowired
    private TaShareChildRecordMapper taShareChildRecordMapper;
    @Autowired
    private TaPersonMapper taPersonMapper;
    @Autowired
    private TaShareActivityMapper activityMapper;
    @Autowired
    private TaShareRecordMapper tashareRecordmapper;
    @Autowired
    private IMiniAppService miniAppService;
    
    @Autowired
    public ITaPointsRecordsService taPointsRecordsService;
    
    @Override
    public IPage<TaShareChildRecord> getList(Integer pageNum, Integer pageSize, Integer groupActivityId, Integer status, Integer recordId, Integer orgId) {
        IPage<TaShareChildRecord> page = new Page<>(pageNum,pageSize);
        return taShareChildRecordMapper.getList(page, groupActivityId, status, recordId, orgId);
    }

    @Override
    public ResponseBean validateRule(TaShareChildRecord taShareChildRecord) {
        ResponseBean responseBean = new ResponseBean();
        try{
            TaPerson taPerson = taPersonMapper.getById(taShareChildRecord.getPersonId());
            TaShareActivity taShareActivity = activityMapper.selectTaShareActivityById(taShareChildRecord.getGroupActivityId());

            TaShareRecord record = tashareRecordmapper.selectById(taShareChildRecord.getRecordId());

            if (taPerson.getPoints() == null || taPerson.getPoints() < taShareActivity.getIntegral()){
                responseBean.addError("积分不足");
                return responseBean;
            }
            //判断参团人数是否已满
            if (taShareActivity.getGroupBuyPeople().equals(record.getJoinPeople())){
                TaShareRecord taShareRecord = new TaShareRecord();
                taShareRecord.setStatus(0);
                taShareRecord.setRecordId(taShareChildRecord.getRecordId());
                tashareRecordmapper.updateById(taShareRecord);
                responseBean.addError("拼团已结束");
                return responseBean;
            }
            //扣取积分,更新参团人数
            taPerson.setPoints(taPerson.getPoints() - taShareActivity.getIntegral());
            taPersonMapper.updateById(taPerson);
            responseBean.addSuccess("您已成功参团");

        }catch (Exception e){
            e.printStackTrace();
            responseBean.addError("参团失败");
        }

        return responseBean;
    }

    @Override
    public Integer getShareRecord(Integer recordId, Integer status) {
        QueryWrapper<TaShareChildRecord> taShareChildRecordQueryWrapper= new QueryWrapper<>();
        taShareChildRecordQueryWrapper.eq("record_id",recordId);
        taShareChildRecordQueryWrapper.eq("status",status);
        return taShareChildRecordMapper.selectCount(taShareChildRecordQueryWrapper);
    }

    @Override
    public List<ShareChildRecordExport> getShareRecordExportList(Integer pageCode, Integer pageSize, Integer recordId, Integer status, Integer groupActivityId) {
        List<ShareChildRecordExport> list = taShareChildRecordMapper.getShareRecordExportList(pageCode, pageSize, recordId, status, groupActivityId);
        return list;
    }

    @Override
    public void updateActivityProcessToEnd() {
        taShareChildRecordMapper.updateEndGroupActivity();
    }

    @Override
    public void updateActivityProcessToEndByGroupActivityId(Integer groupActivityId) {
        taShareChildRecordMapper.updateActivityProcessToEndByGroupActivityId(groupActivityId);
    }

    /**
     * 微信端成为团员
     *
     * @param taShareChildRecord
     * @param orgId
     * @param person
     * @return
     */
    @Override
    public ResponseBean addChildRecord(TaShareChildRecord taShareChildRecord, Integer orgId, TaPerson person) {
        //查看是否拼团成功
        TaShareRecord taShareRecord = tashareRecordmapper.selectById(taShareChildRecord.getRecordId());
        if (taShareRecord.getStatus().equals(CommConstant.STATUS_UNACCALIMED)){
            return ResponseBean.error("拼团失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        
        //查看是否拼团成功
        TaShareActivity taShareActivity = activityMapper.selectById(taShareChildRecord.getGroupActivityId());
        if (taShareRecord.getJoinPeople() >= taShareActivity.getGroupBuyPeople()){
            return ResponseBean.error("拼团失败", ResponseBean.ERROR_UNAVAILABLE);
        }
        if (taShareActivity.getEndTime().isBefore(LocalDateTime.now())){
            return ResponseBean.error("活动已超时", ResponseBean.ERROR_UNAVAILABLE);
        }
        if(taShareActivity.getActivityStatus().equals(CommConstant.ACTIVITY_STATUS_FINISH)){
            return ResponseBean.error("活动已结束", ResponseBean.ERROR_UNAVAILABLE);
        }
        if(taShareActivity.getStatus().equals(CommConstant.STATUS_UNACCALIMED)){
            return ResponseBean.error("活动已失效", ResponseBean.ERROR_UNAVAILABLE);
        }
        
        //查看这个人是否是团员
        QueryWrapper<TaShareChildRecord> taShareChildRecordQueryWrapper = new QueryWrapper<>();
        taShareChildRecordQueryWrapper.eq("org_id",orgId);
        taShareChildRecordQueryWrapper.eq("group_activity_id",taShareChildRecord.getGroupActivityId());
        taShareChildRecordQueryWrapper.eq("person_id",person.getPersonId());
        taShareChildRecordQueryWrapper.eq("record_id",taShareChildRecord.getRecordId());
        List<TaShareChildRecord> shareChildRecordList = taShareChildRecordMapper.selectList(taShareChildRecordQueryWrapper);
        if (shareChildRecordList.size() > 0){
            return ResponseBean.error("您已经是团员,无需重复拼团", ResponseBean.ERROR_UNAVAILABLE);
        }
        
        //检查这个团员积分够不够
        if (person.getPoints() == null || person.getPoints() < taShareActivity.getIntegral()){
            return ResponseBean.error("积分不足",ResponseBean.ERROR_UNAVAILABLE);
        }
        
        //反更新人数
        taShareRecord.setJoinPeople(taShareRecord.getJoinPeople()+1);
        activityMapper.updateById(taShareActivity);
    
        //成为团员
        taShareChildRecord.setOrgId(orgId);
        taShareChildRecord.setStatus(CommConstant.STATUS_NORMAL);
        taShareChildRecord.setPersonId(person.getPersonId());
        taShareChildRecord.setCreateTime(LocalDateTime.now());
        taShareChildRecordMapper.insert(taShareChildRecord);
        if (taShareRecord.getJoinPeople().equals(taShareActivity.getGroupBuyPeople())){
            //发送微信模板消息所有人都发送
            try{
                sendWxMessage(taShareRecord,orgId,taShareActivity);
            }catch (Exception e){}
            
            //生成团员核销码和改状态拼团成功
            changeChildRecord(taShareChildRecord.getRecordId(),orgId,taShareChildRecord.getGroupActivityId());
            //生成团长核销码和拼团成功
            taShareRecord.setVerificationCode(String.valueOf(taShareRecord.getRecordId()+System.currentTimeMillis()));
            taShareRecord.setVerificationStatus(CommConstant.STATUS_UNACCALIMED);
            taShareRecord.setStatus(CommConstant.STATUS_UNACCALIMED);
            taShareRecord.setEndTime(LocalDateTime.now());
        }
        tashareRecordmapper.updateById(taShareRecord);
        //扣取积分,更新参团人数
        person.setPoints(person.getPoints() - taShareActivity.getIntegral());
        taPersonMapper.updateById(person);
        //写入积分流水表
        taPointsRecordsService.saveGroupRecord(person,taShareActivity.getIntegral(),taShareActivity.getBuildingId(),taShareActivity.getGroupActivityId());
        Map<String,Object> map = new HashMap<>();
        map.put("taShareChildRecord",taShareChildRecordMapper.selectById(taShareChildRecord.getChildRecordId()));
        map.put("taShareRecord",taShareRecord);
        return ResponseBean.success(map);
    }
    
    /**
     * 发送微信消息
     * @param taShareRecord
     * @param orgId
     * @param taShareActivity
     */
    private void sendWxMessage(TaShareRecord taShareRecord, Integer orgId, TaShareActivity taShareActivity) {
        String link = "/pages/activity/detail/assemble?id="+taShareRecord.getGroupActivityId()+"&recordId="+taShareRecord.getRecordId();
        //发送给发起者
        TaPerson taPerson = taPersonMapper.selectById(taShareRecord.getPersonId());
        if (null != taPerson){
            miniAppService.sendGroupMessage(taPerson,link,"拼团成功",taShareActivity.getActivityName(),LocalDateTime.now());
        }
        
        //批量发送给助力者
        QueryWrapper<TaShareChildRecord> taShareChildRecordQueryWrapper = new QueryWrapper<>();
        taShareChildRecordQueryWrapper.eq("org_id",orgId);
        taShareChildRecordQueryWrapper.eq("group_activity_id",taShareRecord.getGroupActivityId());
        taShareChildRecordQueryWrapper.eq("record_id",taShareRecord.getRecordId());
        List<TaShareChildRecord> shareChildRecordList = taShareChildRecordMapper.selectList(taShareChildRecordQueryWrapper);
        shareChildRecordList.forEach(e -> {
            TaPerson toTaPerson = taPersonMapper.selectById(e.getPersonId());
            if (null != toTaPerson){
                miniAppService.sendGroupMessage(toTaPerson,link,"拼团成功",taShareActivity.getActivityName(),LocalDateTime.now());
            }
        });
    }
    
    /**
     * 更改团员状态和生成核销码
     * @param recordId
     * @param orgId
     * @param groupActivityId
     */
    private void changeChildRecord(Integer recordId, Integer orgId, Integer groupActivityId) {
        LocalDateTime dateTime = LocalDateTime.now();
        QueryWrapper<TaShareChildRecord> taShareChildRecordQueryWrapper = new QueryWrapper<>();
        taShareChildRecordQueryWrapper.eq("record_id",recordId);
        taShareChildRecordQueryWrapper.eq("org_id",orgId);
        taShareChildRecordQueryWrapper.eq("group_activity_id",groupActivityId);
        List<TaShareChildRecord> shareChildRecordList = taShareChildRecordMapper.selectList(taShareChildRecordQueryWrapper);
        shareChildRecordList.forEach(e -> {
            e.setVerificationCode(String.valueOf(e.getChildRecordId()+System.currentTimeMillis()));
            e.setVerificationStatus(CommConstant.STATUS_UNACCALIMED);
            e.setStatus(CommConstant.STATUS_UNACCALIMED);
            e.setEndTime(dateTime);
        });
        this.updateBatchById(shareChildRecordList);
    }
}
