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.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.excel.ShareChildRecordExport;
import com.huiju.estateagents.excel.ShareRecordFailExport;
import com.huiju.estateagents.excel.ShareRecordSuccessExport;
import com.huiju.estateagents.mapper.TaPersonMapper;
import com.huiju.estateagents.mapper.TaShareActivityMapper;
import com.huiju.estateagents.mapper.TaShareChildRecordMapper;
import com.huiju.estateagents.mapper.TaShareRecordMapper;
import com.huiju.estateagents.po.TaShareRecordPO;
import com.huiju.estateagents.service.ITaPointsRecordsService;
import com.huiju.estateagents.service.ITaShareRecordService;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 拼团记录  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-10-18
 */
@Service
public class TaShareRecordServiceImpl extends ServiceImpl<TaShareRecordMapper, TaShareRecord> implements ITaShareRecordService {

    @Autowired
    private TaPersonMapper taPersonMapper;
    @Autowired
    private TaShareActivityMapper activityMapper;
    @Autowired
    private TaShareRecordMapper taShareRecordMapper;
    @Autowired
    private TaShareChildRecordMapper taShareChildRecordMapper;
    
    @Autowired
    public ITaPointsRecordsService taPointsRecordsService;

    @Override
    public IPage<TaShareRecord> getSuccessList(Integer pageNum, Integer pageSize, String phone, Integer status, Integer groupActivityId, Integer orgId) {
        IPage<TaShareRecord> page = new Page<>(pageNum,pageSize);
        return taShareRecordMapper.recordSuccessList(page, phone, status, groupActivityId, orgId);
    }

    @Override
    public IPage<TaShareRecordPO> getFailAndProcessingList(Integer pageNum, Integer pageSize, String phone, Integer status, Integer groupActivityId, Integer orgId) {
        IPage<TaShareRecord> page = new Page<>(pageNum,pageSize);
        return taShareRecordMapper.recordFailAndProcessingList(page, phone, status, groupActivityId, orgId);
    }

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

            QueryWrapper<TaShareRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("person_id", taShareRecord.getPersonId());
            TaShareRecord record = taShareRecordMapper.selectOne(queryWrapper);

            if (record != null){
                responseBean.addError("您已经发起拼团，请勿再次发起，加入好友的拼团吧");
                return responseBean;
            }
            if (taPerson.getPoints() == null || taPerson.getPoints() < taShareActivity.getIntegral()){
                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 ResponseBean verifyCode(Integer activityId, String verifyCode, String recordId) {
        ResponseBean responseBean = new ResponseBean();
        QueryWrapper<TaShareRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("verification_code", verifyCode);
        queryWrapper.eq(activityId != null, "group_activity_id", activityId);
        queryWrapper.eq(recordId != null, "record_id", recordId);
        TaShareRecord taShareRecord = taShareRecordMapper.selectOne(queryWrapper);

        QueryWrapper<TaShareChildRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("verification_code", verifyCode);
        wrapper.eq(activityId!=null, "group_activity_id", activityId);
        wrapper.eq(recordId != null, "child_record_id", recordId);
        TaShareChildRecord taShareChildRecord = taShareChildRecordMapper.selectOne(wrapper);

        if (taShareRecord == null && taShareChildRecord == null){
            responseBean.addError("请输入正确的核销码");
            return responseBean;
        }

        if (taShareRecord != null){
            taShareRecord.setGroupActivityId(activityId);
            taShareRecord.setVerificationStatus(1);
            taShareRecordMapper.updateById(taShareRecord);
            responseBean.addSuccess("核销成功");
        }

        if (taShareChildRecord != null){
            taShareChildRecord.setGroupActivityId(activityId);
            taShareChildRecord.setVerificationStatus(1);
            taShareChildRecordMapper.updateById(taShareChildRecord);
            responseBean.addSuccess("核销成功");
        }


        return responseBean;
    }

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

    @Override
    public List<ShareRecordSuccessExport> getShareRecordSuccessExportList(Integer pageCode, Integer pageSize, Integer recordId, Integer status, Integer groupActivityId) {
        List<ShareRecordSuccessExport> list= taShareRecordMapper.getShareRecordSuccessExportList(pageCode ,pageSize, recordId, status, groupActivityId);
        list.forEach(e -> e.setVerificationStatus("0".equals(e.getVerificationStatus()) ? "未核销" : "已核销")
        );
        return list;
    }

    @Override
    public List<ShareRecordFailExport> getShareRecordFailExportList(Integer pageCode, Integer pageSize, Integer recordId, Integer status, Integer groupActivityId) {
        List<ShareRecordFailExport> list= taShareRecordMapper.getShareRecordFailExportList(pageCode ,pageSize, recordId, status, groupActivityId);
        return list;
    }

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

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

    /**
     * 分页获取微信端发起拼团记录
     *
     * @param pageNum
     * @param pageSize
     * @param orgId
     * @param person
     * @return
     */
    @Override
    public ResponseBean getShareRecordList(Integer pageNum, Integer pageSize, Integer orgId, TaPerson person) {
        Page<TaShareRecord> pg = new Page<>(pageNum,pageSize);
        List<TaShareRecord> list = taShareRecordMapper.getShareRecordList(pg,orgId,person.getPersonId());
        pg.setRecords(list);
        return ResponseBean.success(pg);
    }
    
    /**
     * 微信端发起我的拼团
     *
     * @param taShareRecord
     * @param orgId
     * @param person
     * @return
     */
    @Override
    public ResponseBean saveShareRecord(TaShareRecord taShareRecord, Integer orgId, TaPerson person) {
        Map<String,Object> map = new HashMap<>();
        TaShareActivity taShareActivity = activityMapper.selectById(taShareRecord.getGroupActivityId());
        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<TaShareRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id", taShareRecord.getPersonId());
        queryWrapper.eq("group_activity_id",taShareRecord.getGroupActivityId());
        TaShareRecord record = taShareRecordMapper.selectOne(queryWrapper);
    
        if (record != null){
            map.put("taShareRecord",record);
            QueryWrapper<TaShareChildRecord> taShareChildRecordQueryWrapper = new QueryWrapper<>();
            taShareChildRecordQueryWrapper.eq("group_activity_id",taShareRecord.getGroupActivityId());
            taShareChildRecordQueryWrapper.eq("org_id",orgId);
            taShareChildRecordQueryWrapper.eq("record_id",record.getRecordId());
            List<TaShareChildRecord> shareChildRecordList = taShareChildRecordMapper.selectList(taShareChildRecordQueryWrapper);
            map.put("shareChildRecordList",shareChildRecordList);
            return ResponseBean.success(map);
        }
        if (null == taShareActivity.getIntegral()){
            taShareActivity.setIntegral(0);
        }
        if (person.getPoints() == null || person.getPoints() < taShareActivity.getIntegral()){
            return ResponseBean.error("积分不足",ResponseBean.ERROR_UNAVAILABLE);
        }
        //扣取积分,更新参团人数
        person.setPoints(person.getPoints() - taShareActivity.getIntegral());
        taPersonMapper.updateById(person);
        //写入积分流水表
        taPointsRecordsService.saveGroupRecord(person,taShareActivity.getIntegral(),taShareActivity.getBuildingId(),taShareActivity.getGroupActivityId());
        
        taShareRecord.setJoinPeople(1);
        //保存拼团团长数据
        taShareRecord.setOrgId(orgId);
        taShareRecord.setPersonId(person.getPersonId());
        taShareRecord.setCreateTime(LocalDateTime.now());
        taShareRecord.setStatus(1);
        taShareRecordMapper.insert(taShareRecord);
        map.put("taShareRecord",taShareRecord);
        map.put("shareChildRecordList",new ArrayList<>());
        return ResponseBean.success(map);
    }
}
