package com.iformall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.common.ResultData;
import com.iformall.domain.po.WxActivity;
import com.iformall.domain.po.WxActivityJoin;
import com.iformall.domain.po.WxCUser;
import com.iformall.domain.po.WxCreditHistory;
import com.iformall.domain.po.msg.WxMsgRecord;
import com.iformall.domain.vo.WxActivityJoinQuestionAnswer;
import com.iformall.enums.*;
import com.iformall.mapper.*;
import com.iformall.mq.MqBaseProducer;
import com.iformall.service.ExcelService;
import com.iformall.service.WxActivityJoinService;
import com.iformall.service.WxCreditHistoryService;
import com.iformall.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gongbiao
 */
@Service
public class WxActivityJoinServiceImpl implements WxActivityJoinService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxActivityJoinMapper wxActivityJoinMapper;

    @Autowired
    WxActivityMapper wxActivityMapper;

    @Autowired
    ExcelService excelService;

    @Autowired
    private MqBaseProducer mqBaseProducer;

    @Autowired
    WxCUserMapper wxCUserMapper;

    @Autowired
    WxCUserBasicInfoMapper wxCUserBasicInfoMapper;

    @Autowired
    WxCreditHistoryMapper wxCreditHistoryMapper;

    @Autowired
    WxCreditHistoryService wxCreditHistoryService;


    @Override
    public PageInfo<WxActivityJoin> listAsPage(WxActivityJoin record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxActivityJoinMapper.findList(record));
    }

    @Override
    public ResultData modifyStatus(WxActivityJoin wxActivityJoin) {
        if (wxActivityJoin.getStatus().equals(EnumActivityJoinStatus.CONFIRMED.getCode())) {
            WxActivity wxActivity = wxActivityMapper.selectById(wxActivityJoin.getActivityId());
            Integer personLimit = wxActivity.getPersonLimit();
            WxActivityJoin params = new WxActivityJoin();
            params.setTenantId(wxActivity.getTenantId());
            params.setActivityId(wxActivity.getId());
            params.setStatus(EnumActivityJoinStatus.CONFIRMED.getCode());
            int count = wxActivityJoinMapper.selectCount(new QueryWrapper(params));
            if (personLimit.equals(count)) {
                return new ResultData(ErrorCode.ACTIVITY_PERSON_LIMITED, count);
            }
        }
        wxActivityJoinMapper.updateById(wxActivityJoin);
        return new ResultData(Result.SUCCESS, "操作成功");
    }

    @Override
    public void exportData(HttpServletRequest request, HttpServletResponse response, WxActivityJoin wxActivityJoin) {
        WxActivity wxActivity = wxActivityMapper.selectById(wxActivityJoin.getActivityId());
        String title = wxActivity.getTitle();
        List<WxActivityJoin> list = wxActivityJoinMapper.findList(wxActivityJoin);
        for (WxActivityJoin activityJoin : list) {
            String answer = activityJoin.getAnswer();
            if (StringUtils.isNotEmpty(answer)) {
                StringBuffer quesAnswer = new StringBuffer();
                List<WxActivityJoinQuestionAnswer> wxActivityJoinQuestionAnswers = JSONArray.parseArray(answer, WxActivityJoinQuestionAnswer.class);
                for (int i = 0; i < wxActivityJoinQuestionAnswers.size(); i++) {
                    WxActivityJoinQuestionAnswer wxActivityJoinQuestionAnswer = wxActivityJoinQuestionAnswers.get(i);
                    if (wxActivityJoinQuestionAnswer == null) {
                        continue;
                    }
                    quesAnswer.append("[").append("问题").append(i + 1).append(":").append(wxActivityJoinQuestionAnswer.getQues())
                            .append(" ").append("答案").append(":").append(wxActivityJoinQuestionAnswer.getAnswer())
                            .append("]");
                    activityJoin.setAnswer(quesAnswer.toString());
                }
            }
        }
        excelService.exportExcel(list, title, title, WxActivityJoin.class, "报名表.xlsx", response, false);
    }

    @Override
    public ResultData queryJoinInfo(WxActivityJoin wxActivityJoin) {
        WxActivity wxActivity = wxActivityMapper.selectById(wxActivityJoin.getActivityId());
        //活动人数
        Integer personLimit = wxActivity.getPersonLimit();
        //总人数
        int total = wxActivityJoinMapper.selectCount(new QueryWrapper(wxActivityJoin));
        wxActivityJoin.setStatus(EnumActivityJoinStatus.CONFIRMED.getCode());
        //确认数
        int confirm = wxActivityJoinMapper.selectCount(new QueryWrapper(wxActivityJoin));
        Map<String, Object> data = new HashMap<>();
        data.put("personLimit", personLimit);
        data.put("confirm", confirm);
        data.put("total", total);
        return new ResultData(data);
    }

    @Override
    public ResultData sendMsg(WxActivityJoin wxActivityJoin) {
        wxActivityJoin.setSendMsg(EnumSendMsg.NO.getCode());
        wxActivityJoin.setStatus(EnumActivityJoinStatus.CONFIRMED.getCode());
        List<WxActivityJoin> joinList = wxActivityJoinMapper.selectList(new QueryWrapper(wxActivityJoin));
        if (joinList.size() == 0) {
            return new ResultData();
        }
        //更改状态
        WxActivity activity = wxActivityMapper.selectById(wxActivityJoin.getActivityId());
        activity.setSendMsg(EnumSendMsg.YES.getCode());
        activity.setUpdateTime(new Date());
        wxActivityMapper.updateById(activity);
        //发短信
        for (WxActivityJoin join : joinList) {
            if (StringUtils.isNotEmpty(join.getPhone())) {
                sendMessage(join, activity);
            }
        }
        Map<String, Object> param = new HashMap<>(2);
        param.put("sendMsg", EnumSendMsg.YES.getCode());
        param.put("joinList", joinList);
        wxActivityJoinMapper.updateSendMsg(param);
        return new ResultData();
    }

    @Override
    public PageInfo<WxActivity> clistAsPage(WxActivityJoin wxActivityJoin, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxActivityJoinMapper.cfindList(wxActivityJoin));
    }


    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public ResultData join(WxActivityJoin wxActivityJoin) {
        WxActivityJoin joinQuery = new WxActivityJoin();
        joinQuery.setUserId(wxActivityJoin.getUserId());
        joinQuery.setActivityId(wxActivityJoin.getActivityId());
        int count = wxActivityJoinMapper.selectCount(new QueryWrapper(joinQuery));
        if (count > 0) {
            return new ResultData(ErrorCode.ACTIVITY_JOINED);
        }
        WxCUser user = wxCUserMapper.selectById(wxActivityJoin.getUserId());
        //查询是否消耗积分
        WxActivity wxActivity = wxActivityMapper.selectById(wxActivityJoin.getActivityId());
        Date date = new Date();
        if (wxActivity.getUseCredit().equals(EnumActivityUseCreditStatus.YES.getCode())) {
            Integer credit = wxActivity.getCredit();
            //积分历史
            WxCreditHistory wxCreditHistory = new WxCreditHistory();
            wxCreditHistory.setTenantId(wxActivity.getTenantId());
            wxCreditHistory.setCUserId(wxActivityJoin.getUserId());
            wxCreditHistory.setCreditNum(credit);
            wxCreditHistory.setCreditType(EnumScoreType.ACTIVITY_JOIN.getCode());
            wxCreditHistory.setOperatorType(EnumUserType.CUSER.getCode());
            wxCreditHistory.setOperatorId(wxActivityJoin.getUserId());
            wxCreditHistoryService.saveOrUpdate(wxCreditHistory);
        }
        //保存到报名表中
        final IdWorker idWorker = IdWorker.get();
        wxActivityJoin.setId(idWorker.nextId());
        wxActivityJoin.setPhone(user.getPhone());
        wxActivityJoin.setCreateTime(date);
        wxActivityJoin.setUpdateTime(date);
        wxActivityJoinMapper.insert(wxActivityJoin);
        return new ResultData();
    }

    @Override
    public ResultData sign(WxActivityJoin wxActivityJoin) {
        //是否报名记录
        WxActivityJoin activityJoin = wxActivityJoinMapper.selectOne(new QueryWrapper(wxActivityJoin));
        if (activityJoin == null) {
            return new ResultData(ErrorCode.ACTIVITY_JOIN_NOT_FOUND);
        }
        if (activityJoin.getStatus().equals(EnumActivityJoinStatus.NOT_CONFIRMED.getCode())) {
            return new ResultData(ErrorCode.ACTIVITY_WAIT_CONFIRMED);
        }
        if (activityJoin.getStatus().equals(EnumActivityJoinStatus.CONFIRMED.getCode())) {
            activityJoin.setSignIn(EnumActivityJoinSignStatus.YES.getCode());
            wxActivityJoinMapper.updateById(activityJoin);
            //查询活动名称
            WxActivity activity = wxActivityMapper.selectById(wxActivityJoin.getActivityId());
            return new ResultData(Result.SUCCESS, "签到成功", activity.getTitle());
        }
        return new ResultData(ErrorCode.ACTIVITY_EXPIRED);
    }

    private void sendMessage(WxActivityJoin join, WxActivity activity) {
        logger.info("》》》》》》》》》》》");
        logger.info("活动发送短信开始");
        logger.info("》》》》》》》》》》》");
        //人名
        String person = join.getName();
        person = StringUtils.isNotEmpty(person) ? person : "";
        //找出用户手机号 联系电话为空时 使用授权手机号
        String phone = StringUtils.isNotEmpty(join.getTelphone()) ? join.getTelphone() : join.getPhone();
        //活动名
        String party = activity.getTitle();
        String time = DateUtils.date2String(activity.getActivityStartTime());
        Map<String, String> msgReplaceMap = new HashMap();
        msgReplaceMap.put("person", person);
        msgReplaceMap.put("party", party);
        msgReplaceMap.put("time", time);
        WxMsgRecord wxMsgRecord = new WxMsgRecord();
        wxMsgRecord.setMsgType(EnumMsgRecordType.SMS.getCode());
        wxMsgRecord.setModelType(EnumMsgModel.TIME_LIMIT_CAMPAIGN_JOIN_SUCCESS.getCode());
        wxMsgRecord.setReceiver(phone);
        wxMsgRecord.setTenantId(join.getTenantId());
        wxMsgRecord.setDynamicContentMap(msgReplaceMap);
        mqBaseProducer.sendMessage(wxMsgRecord, EnumMsgMqTopic.DEFAULT.getCode(), EnumMsgMqTag.DEFAULT.getCode(), EnumMsgMqKey.DEFAULT.getCode());
        logger.info("》》》》》》》》》》》");
        logger.info("活动发送短信结束");
        logger.info("》》》》》》》》》》》");
    }


}
