package com.ruoyi.system.service.impl;


import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsResponse;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SendSmsUtils;
import com.ruoyi.system.domain.ZxFj;
import com.ruoyi.system.domain.activity.ZxActivity;
import com.ruoyi.system.domain.activity.ZxActivityUser;
import com.ruoyi.system.domain.conference.ZxConference;
import com.ruoyi.system.domain.conference.ZxConferenceUser;
import com.ruoyi.system.domain.notice.ZxNotice;
import com.ruoyi.system.mapper.ZxFjMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.ZxActivityMapper;
import com.ruoyi.system.service.IZxActivityService;

import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.ruoyi.common.constant.CommonConstants.FIV;
import static com.ruoyi.common.constant.CommonConstants.THR;

/**
 * 政协活动Service业务层处理
 *
 * @author boman
 * @date 2024-03-14
 */
@Service
public class ZxActivityServiceImpl implements IZxActivityService {
    @Autowired
    private ZxActivityMapper zxActivityMapper;

    @Autowired
    private ZxFjMapper zxFjMapper;

    /**
     * 查询政协活动
     *
     * @param activityId 政协活动主键
     * @return 政协活动
     */
    @Override
    public ZxActivity selectZxActivityByActivityId(Long activityId) {
        return zxActivityMapper.selectZxActivityByActivityId(activityId);
    }

    /**
     * 查询政协活动人员详情
     *
     * @param activityId 政协活动主键
     * @return 政协活动
     */
    @Override
    public List<ZxActivityUser> selectZxActivityUserByActivityId(Long activityId) {
        return zxActivityMapper.selectZxActivityUserByActivityId(activityId);
    }

    /**
     * 获取政协活动详细信息
     */
    @Override
    public ZxActivity selectZxActivityInfo(ZxActivity zxActivity) {
        return zxActivityMapper.selectZxActivityInfo(zxActivity);
    }

    /**
     * 获取政协活动人员详细信息
     */
    @Override
    public List<ZxActivityUser> selectZxActivityUser(ZxActivityUser zxActivityUser) {
        return zxActivityMapper.selectZxActivityUser(zxActivityUser);
    }

    /**
     * 查询政协活动列表
     *
     * @param zxActivity 政协活动
     * @return 政协活动
     */
    @Override
    public List<ZxActivity> selectZxActivityList(ZxActivity zxActivity) {
        List<ZxActivity> zxActivities = zxActivityMapper.selectZxActivityList(zxActivity);
        if (zxActivities != null && zxActivities.size() > 0) {
            long count;
            for (ZxActivity activity : zxActivities) {
                List<ZxActivityUser> zxActivityUserList = activity.getZxActivityUserList();
                activity.setRead("0");
                activity.setNoRead("0");
                if (zxActivityUserList != null && zxActivityUserList.size() > 0) {
                    //找出答复字段不是null的
                    count = zxActivityUserList.stream().filter(e -> e.getIsJoin() != null).count();
                    activity.setRead(count + "");
                    activity.setNoRead(String.valueOf(zxActivityUserList.size() - count));
                    String isJoin = zxActivityUserList.get(0).getIsJoin();
                    if (StringUtils.isNotEmpty(isJoin)){
                        activity.setIsJoin(isJoin);
                    }
                }
            }
        }
        return zxActivities;
    }

    /**
     * 新增政协活动
     *
     * @param zxActivity 政协活动
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertZxActivity(ZxActivity zxActivity) {
        zxActivity.setPublishTime(DateUtils.getNowDate());
        zxActivity.setPublishDeptId(SecurityUtils.getDeptId());
        zxActivity.setPublishDept(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        zxActivity.setCreateTime(DateUtils.getNowDate());
        int rows = zxActivityMapper.insertZxActivity(zxActivity);
        insertZxActivityUser(zxActivity);
        insertZxFj(zxActivity);
        return rows;
    }

    /**
     * 修改活动答复信息
     */
    @Override
    public int updateReply(ZxActivityUser zxActivityUser) {
        zxActivityUser.setUserId(SecurityUtils.getUserId());
        zxActivityUser.setReplyTime(DateUtils.getNowDate());
        return zxActivityMapper.updateReply(zxActivityUser);
    }

    /**
     * 修改政协活动
     *
     * @param zxActivity 政协活动
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateZxActivity(ZxActivity zxActivity) {
        zxActivity.setUpdateTime(DateUtils.getNowDate());
        zxActivityMapper.deleteZxActivityUserByActivityId(zxActivity.getActivityId());
        zxFjMapper.deleteZxFjBySourceId(zxActivity.getActivityId());
        insertZxActivityUser(zxActivity);
        insertZxFj(zxActivity);
        return zxActivityMapper.updateZxActivity(zxActivity);
    }

    /**
     * 批量删除政协活动
     *
     * @param activityIds 需要删除的政协活动主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteZxActivityByActivityIds(Long[] activityIds) {
        zxActivityMapper.deleteZxActivityUserByActivityIds(activityIds);
        return zxActivityMapper.deleteZxActivityByActivityIds(activityIds);
    }

    /**
     * 删除政协活动信息
     *
     * @param activityId 政协活动主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteZxActivityByActivityId(Long activityId) {
        zxActivityMapper.deleteZxActivityUserByActivityId(activityId);
        return zxActivityMapper.deleteZxActivityByActivityId(activityId);
    }

    /**
     * 新增政协活动-用户关联信息
     *
     * @param zxActivity 政协活动对象
     */
    public void insertZxActivityUser(ZxActivity zxActivity) {
        List<ZxActivityUser> zxActivityUserList = zxActivity.getZxActivityUserList();
        Long activityId = zxActivity.getActivityId();
        if (StringUtils.isNotNull(zxActivityUserList)) {
            List<ZxActivityUser> list = new ArrayList<ZxActivityUser>();
            LocalDate localDate = DateUtils.toLocalDate(zxActivity.getActivityDate());
            String activityTime = zxActivity.getActivityTime();
            String activityAddress = zxActivity.getActivityAddress();
            String activityTitle = zxActivity.getActivityTitle();
            List<String> phoneList = new ArrayList<>();
            List<String> userNameList = new ArrayList<>();
            for (ZxActivityUser zxActivityUser : zxActivityUserList) {
                zxActivityUser.setActivityId(activityId);
                list.add(zxActivityUser);

                String userName = zxActivityUser.getUserName();
                //获取手机号
                String phonenumber = zxActivityUser.getPhonenumber().trim();
                if (StringUtils.isNotEmpty(phonenumber)){
                    phoneList.add(phonenumber);
                    userNameList.add(userName);
                }
            }
            if (list.size() > 0) {
                zxActivityMapper.batchZxActivityUser(list);
            }

            if (phoneList.size() > 0) {
                int maxNums = 100; //每次最多发送100条，我们一次批量发100条
                int times = 0;// 循环几个100  用List的长度 除 100
                int size = phoneList.size(); // 数据数量
                //会议通知模板id
                String templateCode = "SMS_465342955";
                //签名
                String signName = "潜山市政协办公室";
                List<String> signNameList = new ArrayList<>();
                List<String> templateList = new ArrayList<>();
                List<String> phoneJsonList = new ArrayList<>();
                StringBuffer signNameJson;
                StringBuffer phoneNumberJson;
                StringBuffer templateParamJson;
                //返回提示
                String backResult = "";
                if (size < maxNums) {
                    times = 1;
                } else {
                    times = (size - 1) / maxNums + 1; //为什么要-1 因为如果是200的时候，理论上次数应该是2，而不是3，如果是101，那么次数也是2，这样就保证次数准确。
                }
                for (int j = 0; j < times; j++) {
                    if (j > 0 && (j * maxNums + 1 > size)) { //边界判定，如果刚好是100条，那么times的值为2，这时候j 为1的时候 101 大于100结束循环，100条以内不生效
                        break;
                    } else {
                        phoneNumberJson = new StringBuffer();
                        signNameJson = new StringBuffer();
                        templateParamJson = new StringBuffer();
                        phoneNumberJson.append("[");
                        signNameJson.append("[");
                        templateParamJson.append("[");
                        for (int k = j * maxNums; k < size && k < (j + 1) * maxNums; k++) {
                            // 防止有空行，手机号是必须要有的
                            String phone = phoneList.get(k);
                            if (StringUtils.isEmpty(phone)) {
                                continue;
                            }
                            phoneNumberJson.append("\"" + phoneList.get(k) + "\",");
                            signNameJson.append("\"" + signName + "\",");
                            /**
                             * 定于${month}月${day}日（${week}） ${time} 在${place}地点举行${content}活动，请${name}准时参加。
                             */
                            templateParamJson.append("{\"month\":\"" + localDate.getMonthValue() + "\",\"day\":\"" + localDate.getDayOfMonth() + "\",\"week\":\"" + localDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINESE) + "\",\"time\":\"" + activityTime +  "\",\"place\":\"" + activityAddress + "\",\"content\":\"" + activityTitle + "\",\"name\":\"" + userNameList.get(k) + "\"},");
                        }
                        phoneNumberJson.deleteCharAt(phoneNumberJson.length() - 1);//移除最后一个逗号字符，
                        signNameJson.deleteCharAt(signNameJson.length() - 1);
                        templateParamJson.deleteCharAt(templateParamJson.length() - 1);//移除最后一个逗号字符
                        phoneNumberJson.append("]");
                        signNameJson.append("]");
                        templateParamJson.append("]");
                        phoneJsonList.add(phoneNumberJson.toString());
                        signNameList.add(signNameJson.toString());
                        templateList.add(templateParamJson.toString());
                    }
                    //组装请求对象
                    if (times == phoneJsonList.size()) {
                        for (int i = 0; i < times; i++) {
                            long startTimeSql = System.currentTimeMillis();
                            SendBatchSmsRequest sendBatchSmsRequest = new SendBatchSmsRequest();
                            //组装电话号码
                            sendBatchSmsRequest.setPhoneNumberJson(phoneJsonList.get(i));
                            //签名名称
                            sendBatchSmsRequest.setSignNameJson(signNameList.get(i));
                            //替换参数
                            sendBatchSmsRequest.setTemplateParamJson(templateList.get(i));
                            //固定的模板名称
                            sendBatchSmsRequest.setTemplateCode(templateCode);
                            long endTimeSql = System.currentTimeMillis() - startTimeSql;
                            System.out.println("线程" + Thread.currentThread().getId() + "执行批量下发活动短信通知计算:" + (i + 1) + "次,时间" + endTimeSql + "ms");
                            long startTimeSend = System.currentTimeMillis();
                            SendBatchSmsResponse sendBatchSmsResponse = SendSmsUtils.sendBatchSms(sendBatchSmsRequest);
                            long endTimeSend = System.currentTimeMillis() - startTimeSend;
                            System.out.println("线程" + Thread.currentThread().getId() + "执行批量下发活动短信通知接口请求:" + (i + 1) + "次,时间" + endTimeSend + "ms");
                            if (sendBatchSmsResponse != null) {
                                String code = sendBatchSmsResponse.getBody().getCode();
                                if (sendBatchSmsResponse.getBody().getCode() != null && "OK".equals(code)) {
                                    //批量请求发送短信成功
                                    System.out.println("批量活动短信发送成功：" + phoneJsonList.get(i).split(",").length + "条");
                                    backResult = backResult + "第" + i + "次批量成功  ";
                                } else {
                                    System.out.println("批量活动短信发送失败！");
                                    backResult = backResult + "第" + i + "次批量失败  ";
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 新增活动附件关联信息
     */
    public void insertZxFj(ZxActivity zxActivity)
    {
        List<ZxFj> zxFjListFj = zxActivity.getZxFjList();
        Long activityId = zxActivity.getActivityId();
        if (StringUtils.isNotNull(zxFjListFj))
        {
            List<ZxFj> list = new ArrayList<ZxFj>();
            for (ZxFj zxFj : zxFjListFj)
            {
                zxFj.setType(FIV);
                zxFj.setMainId(activityId);
                zxFj.setSourceId(activityId);
                list.add(zxFj);
            }
            if (list.size() > 0)
            {
                zxFjMapper.batchZxFj(list);
            }
        }
    }
}
