package com.ruoyi.system.service.impl;


import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsResponse;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.ZxFj;
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 org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.ZxConferenceMapper;
import com.ruoyi.system.service.IZxConferenceService;

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

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

/**
 * 政协会议活动Service业务层处理
 *
 * @author boman
 * @date 2024-03-06
 */
@Service
public class ZxConferenceServiceImpl implements IZxConferenceService {
    @Autowired
    private ZxConferenceMapper zxConferenceMapper;
    @Autowired
    private ZxFjMapper zxFjMapper;

    /**
     * 获取政协会议活动详细信息
     */
    @Override
    public ZxConference selectZxConferenceInfo(ZxConference zxConference) {
        return zxConferenceMapper.selectZxConferenceInfo(zxConference);
    }

    /**
     * 查询政协会议活动人员详情
     *
     * @param conferenceId 政协会议活动主键
     * @return
     */
    @Override
    public List<ZxConferenceUser> selectZxConferenceUserByConferenceId(Long conferenceId) {
        return zxConferenceMapper.selectZxConferenceUserByConferenceId(conferenceId);
    }

    /**
     *查询政协会议活动人员详情
     * @return
     */
    @Override
    public List<ZxConferenceUser> selectZxConferenceUser(ZxConferenceUser zxConferenceUser) {
        return zxConferenceMapper.selectZxConferenceUser(zxConferenceUser);
    }

    /**
     * 查询政协会议活动列表
     *
     * @param zxConference 政协会议活动
     * @return 政协会议活动
     */
    @Override
    public List<ZxConference> selectZxConferenceList(ZxConference zxConference) {
        //查询是否答复，不答复算未读
        List<ZxConference> zxConferences = zxConferenceMapper.selectZxConferenceList(zxConference);
        if (zxConferences != null && zxConferences.size() > 0) {
            long count;
            for (ZxConference conference : zxConferences) {
                List<ZxConferenceUser> zxConferenceUserList = conference.getZxConferenceUserList();
                conference.setRead("0");
                conference.setNoRead("0");
                if (zxConferenceUserList != null && zxConferenceUserList.size() > 0) {
                    //找出答复字段不是null的
                    count = zxConferenceUserList.stream().filter(e -> e.getIsJoin() != null).count();
                    conference.setRead(count + "");
                    conference.setNoRead(String.valueOf(zxConferenceUserList.size() - count));
                    String isJoin = zxConferenceUserList.get(0).getIsJoin();
                    if (StringUtils.isNotEmpty(isJoin)){
                        conference.setIsJoin(isJoin);
                    }
                }
            }
        }
        return zxConferences;
    }

    /**
     * 新增政协会议活动
     *
     * @param zxConference 政协会议活动
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertZxConference(ZxConference zxConference) {
        zxConference.setCreateTime(DateUtils.getNowDate());
        zxConference.setPublishTime(DateUtils.getNowDate());
        int rows = zxConferenceMapper.insertZxConference(zxConference);
        insertZxConferenceUser(zxConference);
        insertZxFj(zxConference);
        try {
            String imagePath= QRCodeUtils.encode(zxConference.getConferenceId().toString(), null, RuoYiConfig.getUploadQrPath(), true);
            zxConference.setConferenceQr(imagePath);
            zxConferenceMapper.updateZxConference(zxConference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rows;
    }

    /**
     * 修改政协会议活动
     *
     * @param zxConference 政协会议活动
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateZxConference(ZxConference zxConference) {
        zxConference.setUpdateTime(DateUtils.getNowDate());
        zxConferenceMapper.deleteZxConferenceUserByConferenceId(zxConference.getConferenceId());
        zxFjMapper.deleteZxFjBySourceId(zxConference.getConferenceId());
        insertZxConferenceUser(zxConference);
        insertZxFj(zxConference);
        return zxConferenceMapper.updateZxConference(zxConference);
    }

    /**
     * 修改会议答复信息
     */
    @Override
    public int updateReply(ZxConferenceUser zxConferenceUser) {
        zxConferenceUser.setUserId(SecurityUtils.getUserId());
        zxConferenceUser.setReplyTime(DateUtils.getNowDate());
        return zxConferenceMapper.updateReply(zxConferenceUser);
    }

    /**
     * 会议签到
     * @param zxConferenceUser
     * @return
     */
    @Override
    public int signIn(ZxConferenceUser zxConferenceUser) {
        zxConferenceUser.setSignIn(DateUtils.getNowDate());
        return zxConferenceMapper.signIn(zxConferenceUser);
    }

    /**
     * 批量删除政协会议活动
     *
     * @param conferenceIds 需要删除的政协会议活动主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteZxConferenceByConferenceIds(Long[] conferenceIds) {
        zxConferenceMapper.deleteZxConferenceUserByConferenceIds(conferenceIds);
        return zxConferenceMapper.deleteZxConferenceByConferenceIds(conferenceIds);
    }

    /**
     * 删除政协会议活动信息
     *
     * @param conferenceId 政协会议活动主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteZxConferenceByConferenceId(Long conferenceId) {
        zxConferenceMapper.deleteZxConferenceUserByConferenceId(conferenceId);
        return zxConferenceMapper.deleteZxConferenceByConferenceId(conferenceId);
    }

    /**
     * 新增政协会议活动-用户关联信息
     *
     * @param zxConference 政协会议活动对象
     */
    public void insertZxConferenceUser(ZxConference zxConference) {
        List<ZxConferenceUser> zxConferenceUserList = zxConference.getZxConferenceUserList();
        Long conferenceId = zxConference.getConferenceId();
        if (StringUtils.isNotNull(zxConferenceUserList)) {
            LocalDate localDate = DateUtils.toLocalDate(zxConference.getConferenceDate());
            String conferenceTime = zxConference.getConferenceTime();
            String conferenceAddress = zxConference.getConferenceAddress();
            String conferenceTitle = zxConference.getConferenceTitle();
            List<ZxConferenceUser> list = new ArrayList<ZxConferenceUser>();
            List<String> phoneList = new ArrayList<>();
            List<String> userNameList = new ArrayList<>();
            for (ZxConferenceUser zxConferenceUser : zxConferenceUserList) {
                String userName = zxConferenceUser.getUserName();
                zxConferenceUser.setConferenceId(conferenceId);
                list.add(zxConferenceUser);
                //获取手机号
                String phonenumber = zxConferenceUser.getPhonenumber().trim();
                if (StringUtils.isNotEmpty(phonenumber)){
                    phoneList.add(phonenumber);
                    userNameList.add(userName);
                }
            }
            if (list.size() > 0) {
                zxConferenceMapper.batchZxConferenceUser(list);
            }
            if (phoneList.size() > 0) {
                int maxNums = 100; //每次最多发送100条，我们一次批量发100条
                int times = 0;// 循环几个100  用List的长度 除 100
                int size = phoneList.size(); // 数据数量
                //会议通知模板id
                String templateCode = "SMS_465422107";
                //签名
                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\":\"" + conferenceTime +  "\",\"place\":\"" + conferenceAddress + "\",\"content\":\"" + conferenceTitle + "\",\"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(ZxConference zxConference)
    {
        List<ZxFj> zxFjListFj = zxConference.getZxFjList();
        Long conferenceId = zxConference.getConferenceId();
        if (StringUtils.isNotNull(zxFjListFj))
        {
            List<ZxFj> list = new ArrayList<ZxFj>();
            for (ZxFj zxFj : zxFjListFj)
            {
                zxFj.setType(FOR);
                zxFj.setMainId(conferenceId);
                zxFj.setSourceId(conferenceId);
                list.add(zxFj);
            }
            if (list.size() > 0)
            {
                zxFjMapper.batchZxFj(list);
            }
        }
    }
}
