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.common.StringUtils;
import com.huiju.estateagents.entity.*;
import com.huiju.estateagents.event.EventBus;
import com.huiju.estateagents.excel.HelpInitiateRecordSucceed;
import com.huiju.estateagents.excel.HelpProceedAndFinish;
import com.huiju.estateagents.excel.HelpRecordExport;
import com.huiju.estateagents.mapper.*;
import com.huiju.estateagents.service.IHelpActivityService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 助力活动  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-10-17
 */
@Service
public class HelpActivityServiceImpl extends ServiceImpl<HelpActivityMapper, HelpActivity> implements IHelpActivityService {

    @Autowired
    HelpActivityMapper taHelpActivityMapper;

    @Autowired
    HelpInitiateRecordMapper helpInitiateRecordMapper;

    @Autowired
    private TaActivityDynamicEnlistMapper taActivityDynamicEnlistMapper;

    @Autowired
    private TaShareRecordMapper taShareRecordMapper;

    @Autowired
    HelpRecordMapper helpRecordMapper;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    TaShareActivityMapper taShareActivityMapper;

    @Override
    public ResponseBean helpActivityList(Integer pageNum, Integer pageSize, Integer cityId, String buildingId, String title, String startDate, String endDate, Integer activityStatus, Integer orgId, List<TaPersonBuilding> personBuildingList) {
        ResponseBean responseBean = new ResponseBean<>();
        IPage<HelpActivity> pg = new Page<>(pageNum, pageSize);
        IPage<HelpActivity> result = taHelpActivityMapper.helpActivityListPage(pg, cityId, buildingId, title, startDate, endDate, activityStatus, orgId, personBuildingList);
        responseBean.addSuccess(result);
        return responseBean;
    }

    @Override
    public int helpActivityAdd(HelpActivity helpActivity, Integer orgId) {
        helpActivity.setOrgId(orgId)
                .setCreateDate(LocalDateTime.now());
        taHelpActivityMapper.insert(helpActivity);
        return helpActivity.getHelpActivityId();
    }

    @Override
    public void helpActivityUpdate(HelpActivity helpActivity) {
        taHelpActivityMapper.updateById(helpActivity);
    }

    @Override
    public ResponseBean helpRecord(Integer helpActivityId, String status, Integer pageNum, Integer pageSize, String tel) {
        ResponseBean responseBean = new ResponseBean<>();
        //  status: helpSucceed助力成功，helpUnderway进行中，helpUnfinished助力失败

        //查询当前助力成功所需的人数限制（persion_num）
        HelpActivity helpActivity = taHelpActivityMapper.selectById(helpActivityId);
        // 得到活动限制助力的总数
        int persionNumCount = helpActivity.getPersonNum();
        IPage<HelpInitiateRecord> pg = new Page<>(pageNum, pageSize);
        IPage<HelpInitiateRecord> list = helpInitiateRecordMapper.selectPageList(pg, helpActivityId, status, tel);

        List<HelpInitiateRecord> helpInitiateRecordList = list.getRecords();
        for (HelpInitiateRecord helpInitiateRecord : helpInitiateRecordList) {
            helpInitiateRecord.setPersionNumCount(persionNumCount);
            // 统计助力成功的总数(发起人得到助力数满了即可)
            QueryWrapper<HelpRecord> helpRecorddQueryWrapper = new QueryWrapper<>();
            helpRecorddQueryWrapper.eq("help_record_initiate_id", helpInitiateRecord.getHelpRecordInitiateId());
            // 拿到每个发起人，得到助力的总数
            int helpRecordCount = helpRecordMapper.selectCount(helpRecorddQueryWrapper);
            // 助力成功
            if ("helpSucceed".equals(status)) {
                if (persionNumCount == helpRecordCount) {
                    helpInitiateRecord.setHelpCount(helpRecordCount);
                }
            }
            // 助力进行中（活动进行中，未结束）
            if ("helpUnderway".equals(status) && helpInitiateRecord.getStatus().equals(1)) {
                if (persionNumCount > helpRecordCount) {
                    helpInitiateRecord.setHelpCount(helpRecordCount);
                }
            }
            // 活动助力失败
            // 活动进行中（活动已结束）
            if ("helpUnfinished".equals(status) && helpInitiateRecord.getStatus().equals(2)) {
                if (persionNumCount > helpRecordCount) {
                    helpInitiateRecord.setHelpCount(helpRecordCount);
                }

            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", helpInitiateRecordList);
        map.put("total", list.getTotal());
        map.put("pageNum", list.getCurrent());
        map.put("pageSize", list.getSize());
        return ResponseBean.success(map);
    }

    @Override
    public ResponseBean taHelpRecordDetails(Integer helpRecordInitiateId, Integer pageNum, Integer pageSize) {
        ResponseBean responseBean = new ResponseBean<>();
        IPage<HelpInitiateRecord> pg = new Page<>(pageNum, pageSize);
        IPage<HelpRecord> helpRecordList = helpRecordMapper.taHelpRecordDetails(pg, helpRecordInitiateId);
        responseBean.addSuccess(helpRecordList);
        return responseBean;
    }

    @Override
    public ResponseBean helpInitiateRecordVerify(Integer helpRecordInitiateId, String verifyCode) {
        ResponseBean responseBean = new ResponseBean<>();
        HelpInitiateRecord helpInitiateRecord = helpInitiateRecordMapper.selectById(helpRecordInitiateId);
        if (null == verifyCode || "".equals(verifyCode)) {
            responseBean.addError("请输入核销码");
            return responseBean;
        }

        // 判断是否已核销
        if ("1".equals(helpInitiateRecord.getVerificationStatus())) {
            responseBean.addSuccess("已核销");
            return responseBean;
        }

        if (verifyCode.equals(String.valueOf(helpInitiateRecord.getVerification()))) {
            helpInitiateRecord.setVerificationStatus(1);
            helpInitiateRecordMapper.updateById(helpInitiateRecord);

            // 活动核销加积分
            applicationContext.publishEvent(new EventBus(helpInitiateRecord, EventBus.EventType.ActivityVerificationSign, helpInitiateRecord.getOrgId()));

            responseBean.addSuccess("成功");
        } else {
            responseBean.addError("核销码错误,请重新输入");
        }
        return responseBean;
    }

    @Override
    public Integer getHelpInitiateRecordSucceed(String tel, Integer helpActivityId) {
        QueryWrapper<HelpInitiateRecord> helpInitiateRecordQuery = new QueryWrapper<>();
        helpInitiateRecordQuery.eq("help_activity_id", helpActivityId);
        helpInitiateRecordQuery.eq(!StringUtils.isEmpty(tel), "phone", tel);
        return helpInitiateRecordMapper.selectCount(helpInitiateRecordQuery);
    }

    @Override
    public List<HelpInitiateRecordSucceed> getHelpInitiateRecordSucceedExportList(int i, Integer pageSize, String tel, Integer helpActivityId) {
        List<HelpInitiateRecordSucceed> lsit = helpInitiateRecordMapper.getHelpInitiateRecordSucceedExportList(i, pageSize, tel, helpActivityId);
        return lsit;
    }

    @Override
    public List<HelpProceedAndFinish> getHelpProceedAndFinishExportList(int i, Integer pageSize, String tel, Integer helpActivityId, String condition) {
        List<HelpProceedAndFinish> lsit = helpInitiateRecordMapper.getHelpProceedAndFinishExportList(i, pageSize, tel, helpActivityId, condition);
        return lsit;
    }

    @Override
    public Integer getHelpRecord(Integer helpRecordInitiateId) {
        QueryWrapper<HelpRecord> helpInitiateRecordQuery = new QueryWrapper<>();
        helpInitiateRecordQuery.eq("help_record_initiate_id", helpRecordInitiateId);
        return helpRecordMapper.selectCount(helpInitiateRecordQuery);
    }

    @Override
    public List<HelpRecordExport> getHelpRecordExportList(int i, Integer pageSize, Integer helpRecordInitiateId) {
        List<HelpRecordExport> lsit = helpRecordMapper.getHelpRecordExportList(i, pageSize, helpRecordInitiateId);
        return lsit;
    }

    @Override
    public void updateActivityToUnStart() {
        taHelpActivityMapper.updateActivityToUnStart();
    }

    @Override
    public void updateUnStartHelpActivity() {
        taHelpActivityMapper.updateUnStartHelpActivity();
    }

    @Override
    public void updateProcessingHelpActivity() {
        taHelpActivityMapper.updateProcessingHelpActivity();
    }

    @Override
    public ResponseBean wxhelpActivityAndGroup(Integer orgId, String buildingId, String cityID, TaPerson person) {
        ResponseBean responseBean = new ResponseBean<>();
        //查询是否报名了普通活动
        QueryWrapper<TaActivityDynamicEnlist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("person_id", person.getPersonId());
        List<TaActivityDynamicEnlist> taActivityDynamicEnlists = taActivityDynamicEnlistMapper.selectList(queryWrapper);
        //查询是否报名了拼团活动
        QueryWrapper<TaShareRecord> taShareRecordQueryWrapper = new QueryWrapper<>();
        taShareRecordQueryWrapper.eq("org_id", orgId);
        taShareRecordQueryWrapper.eq("person_id", person.getPersonId());
        List<TaShareRecord> taShareRecords = taShareRecordMapper.selectList(taShareRecordQueryWrapper);
        //判断是否发起了助力活动
        QueryWrapper<HelpInitiateRecord> helpInitiateRecordListQueryWrapper = new QueryWrapper<>();
        helpInitiateRecordListQueryWrapper.eq("org_id", orgId);
        helpInitiateRecordListQueryWrapper.eq("person_id", person.getPersonId());
        List<HelpInitiateRecord> helpInitiateRecords = helpInitiateRecordMapper.selectList(helpInitiateRecordListQueryWrapper);

        // buildingId 楼盘ID为空时首页只查置顶的活动，楼盘ID不为空查所有拼团和助力
        List<HelpActivity> helpActivities = taHelpActivityMapper.selectWxhelpActivityAndGroup(orgId, buildingId, cityID);
        for (HelpActivity helpActivity : helpActivities) {
            if ("activity".equals(helpActivity.getType())) {
                taActivityDynamicEnlists.forEach(dynamic -> {
                    if (helpActivity.getActivityId().equals(dynamic.getDynamicId())) {
                        helpActivity.setActivityStatus(CommConstant.ACTIVITY_STATUS_PARTNER);
                    }
                });
            } else if ("group".equals(helpActivity.getType())) {
                taShareRecords.forEach(share -> {
                    if (helpActivity.getActivityId().equals(share.getGroupActivityId().toString())) {
                        helpActivity.setActivityStatus(CommConstant.ACTIVITY_STATUS_PARTNER);
                    }
                });
            } else if ("help".equals(helpActivity.getType())) {
                helpInitiateRecords.forEach(help -> {
                    if (helpActivity.getActivityId().equals(help.getHelpActivityId().toString())) {
                        helpActivity.setActivityStatus(CommConstant.ACTIVITY_STATUS_PARTNER);
                    }
                });
            }
        }
        responseBean.addSuccess(helpActivities);
        return responseBean;
    }

    @Override
    public ResponseBean helpActivityEffectiveList(Integer pageNum, Integer pageSize, Integer cityId, Integer orgId, String buildingId, Integer status, String name, List<TaPersonBuilding> personBuildingList) {
        ResponseBean responseBean = new ResponseBean<>();
        IPage<HelpActivity> pg = new Page<>(pageNum, pageSize);
        IPage<HelpActivity> result = taHelpActivityMapper.helpActivityListEffectivePage(pg, cityId, orgId, buildingId, status, name, personBuildingList);
        responseBean.addSuccess(result);
        return responseBean;
    }
}