package com.ruoyi.system.service.impl;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendBatchSmsResponse;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SendSmsUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.InvestigateDispositionTable;
import com.ruoyi.system.domain.InvestigateUser;
import com.ruoyi.system.mapper.InvestigateDispositionMapper;
import com.ruoyi.system.mapper.InvestigateDispositionTableMapper;
import com.ruoyi.system.mapper.InvestigateUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.InvestigateTableMapper;
import com.ruoyi.system.domain.InvestigateTable;
import com.ruoyi.system.service.IInvestigateTableService;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.common.config.RuoYiConfig.getProfile;

/**
 * 考察主Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-10
 */
@Service
public class InvestigateTableServiceImpl implements IInvestigateTableService {
    @Autowired
    private InvestigateTableMapper investigateTableMapper;
    @Autowired
    private InvestigateDispositionTableMapper investigateDispositionTableMapper;
    @Autowired
    private InvestigateUserMapper investigateUserMapper;

    /**
     * 查询考察主
     *
     * @param id 考察主主键
     * @return 考察主
     */
    @Override
    public InvestigateTable selectInvestigateTableById(Long id) {
        return investigateTableMapper.selectInvestigateTableById(id);
    }

    /**
     * 查询考察主列表
     *
     * @param investigateTable 考察主
     * @return 考察主
     */
    @Override
    public List<InvestigateTable> selectInvestigateTableList(InvestigateTable investigateTable) {
        return investigateTableMapper.selectInvestigateTableList(investigateTable);
    }

    /**
     * 查询考察主列表
     *
     * @param investigateTable 考察主
     * @return 考察主
     */
    @Override
    public TableDataInfo selectInvestigateTableListData(InvestigateTable investigateTable) {
        //先去查询分页的考察团id;
        List<InvestigateTable> investigateTables = investigateTableMapper.selectInvestigateTableList(investigateTable);
        List<InvestigateTable> investigateTablesAll = new ArrayList<>();
        if (investigateTables != null && investigateTables.size() > 0) {
            StringBuilder sb = new StringBuilder("");
            //获取考察团的id
            for (InvestigateTable table : investigateTables) {
                Long investigateTableId = table.getInvestigateTableId();
                sb.append(investigateTableId).append(",");
            }
            String substring = sb.substring(0, sb.length() - 1);
            //查询考察团全部信息
            investigateTable.setInvestigateTableIds(substring);
            investigateTablesAll = investigateTableMapper.selectInvestigateTableListALL(investigateTable);
        }
        if (investigateTablesAll != null && investigateTablesAll.size() > 0) {
            for (InvestigateTable table : investigateTablesAll) {
                table.setType("进行中");
                //根据开始时间结束时间计算状态
                Date beginTime = table.getBeginTime();
                Date endTime = table.getEndTime();
                Date nowDate = DateUtils.getNowDate();
                //默认进行中
                if (nowDate.before(beginTime)) {
                    //未开始
                    table.setType("未开始");

                } else if (nowDate.after(endTime)) {
                    //已结束
                    table.setType("已结束");
                }
            }
            investigateTablesAll = investigateTablesAll.stream().sorted(Comparator.comparing(InvestigateTable::getCreateTime).reversed()).collect(Collectors.toList());
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(investigateTablesAll);
        rspData.setTotal(new PageInfo(investigateTableMapper.selectInvestigateTableList(investigateTable)).getSize());
        return rspData;
    }

    /**
     * 新增考察主
     *
     * @param investigateTable 考察主
     * @return 结果
     */
    @Override
    public int insertInvestigateTable(InvestigateTable investigateTable) {
        investigateTable.setCreateTime(DateUtils.getNowDate());
        //新增考察配置与考察主表关联
        //insertInvestigateDispositionTable(investigateTable);
        List<InvestigateUser> investigateUserList = investigateTable.getInvestigateUserList();
        investigateTable.setCipher(getCode(4));
        int i = investigateTableMapper.insertInvestigateTable(investigateTable);
        Long investigateTableId = investigateTable.getInvestigateTableId();
        if (investigateUserList != null && investigateUserList.size() > 0) {
            for (InvestigateUser investigateUser : investigateUserList) {
                investigateUser.setInvestigateId(investigateTable.getInvestigateTableId());
            }
            investigateUserMapper.batchDispositionUser(investigateUserList);
            //发送短信 新增不能立刻发送短信
            sendBatchSmsTable(investigateTableId, investigateUserList);
        }

        //新增察配置与考察主表关联表的内容
        List<InvestigateDispositionTable> investigateDispositionTableList = investigateTable.getInvestigateDispositionTableList();

        if (investigateDispositionTableList != null && investigateDispositionTableList.size() > 0) {

            insertInvestigateDispositionTable(investigateTableId, investigateDispositionTableList);
        }
/*        //单独查询考察点信息,新增到关联表
        String investigateDispositionIds = investigateTable.getInvestigateDispositionIds();
        List<InvestigateDispositionTable> investigateDispositionTableListKaoCha = new ArrayList<>();
        if (StringUtils.isNotEmpty(investigateDispositionIds)) {
            for (String investigateDispositionId : investigateDispositionIds.split(",")) {
                InvestigateDispositionTable investigateDispositionTable = new InvestigateDispositionTable();
                investigateDispositionTable.setInvestigateTableId(investigateTableId);
                InvestigateDisposition investigateDisposition = investigateDispositionMapper.selectInvestigateDispositionByInvestigateDispositionId(Long.parseLong(investigateDispositionId));
                investigateDispositionTable.setInvestigateDispositionId(investigateDisposition.getInvestigateDispositionId());
                investigateDispositionTable.setUrl(investigateDisposition.getUrl());
                investigateDispositionTable.setTitle(investigateDisposition.getTitle());
                investigateDispositionTable.setContent(investigateDisposition.getContent());
                investigateDispositionTableListKaoCha.add(investigateDispositionTable);
            }
            investigateDispositionTableMapper.batchDispositionTable(investigateDispositionTableListKaoCha);
        }*/
        return i;
    }


    /**
     * 新增考察配置与考察主关联
     *
     * @param investigateDispositionTableList 考察配置与考察主关联
     * @return 结果
     */

    private void insertInvestigateDispositionTable(Long investigateTableId, List<InvestigateDispositionTable> investigateDispositionTableList) {

        for (int i = 0; i < investigateDispositionTableList.size(); i++) {
            Date nowDate = new Date();
            nowDate.setTime(nowDate.getTime() + (i * 1000L));
            InvestigateDispositionTable investigateDispositionTable = investigateDispositionTableList.get(i);
            investigateDispositionTable.setInvestigateTableId(investigateTableId);
            investigateDispositionTable.setCreateTime(nowDate);
            //获取HTML文件
            String content = investigateDispositionTable.getContent();
            content = " <meta charset=\"utf-8\">\n" +
                    "<style>\n" +
                    " body{margin: 0 !important;}\n" +
                    " img{max-width: 100% !important;height: auto !important;}\n" +
                    "</style>" + content;
            try {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                String fileNameHtml = UUID.randomUUID().toString();
                File html = File.createTempFile(fileNameHtml, ".html", new File(filePath));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(html, true), StandardCharsets.UTF_8));
                writer.write(content);
                writer.close();
                InputStream inputStream = new FileInputStream(html);
                MultipartFile file = new org.springframework.mock.web.MockMultipartFile(html.getName(), html.getName(), "text/html", inputStream);
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                investigateDispositionTable.setUrl(fileName);
                html.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("文件生成成功！");
        }
        investigateDispositionTableMapper.batchDispositionTable(investigateDispositionTableList);
    }

    @Override
    public void sendBatchSmsTable(Long investigateTableId, List<InvestigateUser> investigateUserList) {
        if (investigateUserList != null && investigateUserList.size() > 0) {
            for (InvestigateUser investigateUser : investigateUserList) {
                StringBuffer phoneNumberJson = new StringBuffer();
                StringBuffer templateParamJson = new StringBuffer();
                StringBuffer signNameJson = new StringBuffer();
                phoneNumberJson.append("[");
                templateParamJson.append("[");
                signNameJson.append("[");

                // 防止有空行，手机号是必须要有的
                String phone = investigateUser.getPhonenumber();
                if (StringUtils.isEmpty(phone)) {
                    continue;
                }
                phoneNumberJson.append("\"" + phone + "\",");
                signNameJson.append("\"中新云\",");
                //发送短信
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("number", investigateTableId);
                templateParamJson.append(jsonObject).append(",");


                phoneNumberJson.deleteCharAt(phoneNumberJson.length() - 1);//移除最后一个逗号字符，
                templateParamJson.deleteCharAt(templateParamJson.length() - 1);//移除最后一个逗号字符
                signNameJson.deleteCharAt(signNameJson.length() - 1);
                phoneNumberJson.append("]");
                templateParamJson.append("]");
                signNameJson.append("]");

                SendBatchSmsRequest sendBatchSmsRequest = new SendBatchSmsRequest();
                //组装电话号码
                sendBatchSmsRequest.setPhoneNumberJson(phoneNumberJson.toString());
                //签名名称
                sendBatchSmsRequest.setSignNameJson(signNameJson.toString());
                //替换参数
                sendBatchSmsRequest.setTemplateParamJson(templateParamJson.toString());
                //固定的模板名称
                sendBatchSmsRequest.setTemplateCode("SMS_463622836");
                long startTimeSend = System.currentTimeMillis();
                SendBatchSmsResponse sendBatchSmsResponse = SendSmsUtils.sendBatchSms(sendBatchSmsRequest);
                long endTimeSend = System.currentTimeMillis() - startTimeSend;
                System.out.println("执行批量下发短信接口请求:" + endTimeSend + "ms");
                String code = sendBatchSmsResponse.getBody().getCode();
                if (sendBatchSmsResponse.getBody().getCode() != null && "OK".equals(code)) {
                    System.out.println("批量短信发送成功");
                } else {
                    System.out.println("批量短信发送失败");
                }
            }
        }
    }

    @Override
    public void sendBatchSmsTableUpdate(Long investigateTableId, List<InvestigateUser> investigateUserList) {
        if (investigateUserList != null && investigateUserList.size() > 0) {

            for (InvestigateUser investigateUser : investigateUserList) {
                StringBuffer phoneNumberJson = new StringBuffer();
                StringBuffer templateParamJson = new StringBuffer();
                StringBuffer signNameJson = new StringBuffer();
                phoneNumberJson.append("[");
                templateParamJson.append("[");
                signNameJson.append("[");

                // 防止有空行，手机号是必须要有的
                String phone = investigateUser.getPhonenumber();
                if (StringUtils.isEmpty(phone)) {
                    continue;
                }
                phoneNumberJson.append("\"" + phone + "\",");
                signNameJson.append("\"中新云\",");
                //发送短信
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("number", investigateTableId);
                templateParamJson.append(jsonObject).append(",");


                phoneNumberJson.deleteCharAt(phoneNumberJson.length() - 1);//移除最后一个逗号字符，
                templateParamJson.deleteCharAt(templateParamJson.length() - 1);//移除最后一个逗号字符
                signNameJson.deleteCharAt(signNameJson.length() - 1);
                phoneNumberJson.append("]");
                templateParamJson.append("]");
                signNameJson.append("]");

                SendBatchSmsRequest sendBatchSmsRequest = new SendBatchSmsRequest();
                //组装电话号码
                sendBatchSmsRequest.setPhoneNumberJson(phoneNumberJson.toString());
                //签名名称
                sendBatchSmsRequest.setSignNameJson(signNameJson.toString());
                //替换参数
                sendBatchSmsRequest.setTemplateParamJson(templateParamJson.toString());
                //固定的模板名称
                sendBatchSmsRequest.setTemplateCode("SMS_463673720");
                long startTimeSend = System.currentTimeMillis();
                SendBatchSmsResponse sendBatchSmsResponse = SendSmsUtils.sendBatchSms(sendBatchSmsRequest);
                long endTimeSend = System.currentTimeMillis() - startTimeSend;
                System.out.println("执行批量下发短信接口请求:" + endTimeSend + "ms");
                String code = sendBatchSmsResponse.getBody().getCode();
                if (sendBatchSmsResponse.getBody().getCode() != null && "OK".equals(code)) {
                    System.out.println("批量短信发送成功");
                } else {
                    System.out.println("批量短信发送失败");
                }
            }
        }
    }

    //生成X位验证码
    public static String getCode(Integer num) {
        String[] codes = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < num; i++) {
            int j = (int) (Math.random() * 10);
            if (j <= 0) {
                j = 1;
            }
            code.append(codes[j - 1]);

        }
        return code.toString();
    }

    /**
     * 修改考察主
     *
     * @param investigateTable 考察主
     * @return 结果
     */
    @Override
    public int updateInvestigateTable(InvestigateTable investigateTable) {
        investigateTable.setUpdateTime(DateUtils.getNowDate());
        //删除原先的考察人员数据
        Long investigateTableId = investigateTable.getInvestigateTableId();
        investigateUserMapper.deleteInvestigateUserByInvestigateId(investigateTableId);
        List<InvestigateUser> investigateUserList = investigateTable.getInvestigateUserList();
        if (investigateUserList != null) {
            for (InvestigateUser investigateUser : investigateUserList) {
                investigateUser.setInvestigateId(investigateTable.getInvestigateTableId());
            }
            investigateUserMapper.batchDispositionUser(investigateUserList);
        }


        //删除原先的考察配置与考察主表关联表信息
        investigateDispositionTableMapper.deleteInvestigateDispositionTableByInvestigateTableId(investigateTable.getInvestigateTableId());

        //新增察配置与考察主表关联表的内容
        List<InvestigateDispositionTable> investigateDispositionTableList = investigateTable.getInvestigateDispositionTableList();

        if (investigateDispositionTableList != null && investigateDispositionTableList.size() > 0) {
            for (InvestigateDispositionTable investigateDispositionTable : investigateDispositionTableList) {
                String url = investigateDispositionTable.getUrl();
                String path = url.replace("/profile", getProfile());
                //todo 删除服务器文件
                try {
                    File file = new File(path);
                    if (file.exists()) {
                        Runtime.getRuntime().exec("rm -f " + path);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            insertInvestigateDispositionTable(investigateTableId, investigateDispositionTableList);
        }

        return investigateTableMapper.updateInvestigateTable(investigateTable);

    }

    /**
     * 批量删除考察主
     *
     * @param ids 需要删除的考察主主键
     * @return 结果
     */
    @Override
    public int deleteInvestigateTableByIds(Long[] ids) {
        return investigateTableMapper.deleteInvestigateTableByIds(ids);
    }

    /**
     * 删除考察主信息
     *
     * @param id 考察主主键
     * @return 结果
     */
    @Override
    public int deleteInvestigateTableById(Long id) {
        return investigateTableMapper.deleteInvestigateTableById(id);
    }
}
