package com.ruoyi.system.service.form;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.system.domain.form.MdForm;
import com.ruoyi.system.domain.form.MdFormRecord;
import com.ruoyi.system.domain.form.params.FormRecordQuery;
import com.ruoyi.system.domain.md.request.NewMsgSendData;
import com.ruoyi.system.domain.md.request.NewMsgSendRequest;
import com.ruoyi.system.domain.md.request.NewMsgUser;
import com.ruoyi.system.service.md.NewMsgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Service
public class FormMsgManager {

    private static ExecutorService pool = Executors.newFixedThreadPool(10);

    @Autowired
    private FormManager formManager;

    @Autowired
    private FormRecordManager formRecordManager;

    @Autowired
    private NewMsgService newMsgService;

    /**
     * 发布
     */
    public void send4Publish(List<String> userIds, MdForm mdForm) {
        if (mdForm == null) {
            return;
        }


        NewMsgUser user = new NewMsgUser();
        user.setUserid(mdForm.getOwnUser());
        user.setDeptid(mdForm.getOwnDept());

        String formName = mdForm.getName();
        String formId = mdForm.getId();
        pool.submit(() -> {
            try {
                NewMsgSendRequest request = new NewMsgSendRequest();

                String title = "您有一份新的表单等待填报，请尽快处理！";
                String body = formName + "等待填报，点击填报。";

                request.setSendData(build(title, body, formId));
                request.setFrom(user);

                List<NewMsgUser> toUserLists = new ArrayList<>();

                for (String userId : userIds) {
                    NewMsgUser toMsgUser = new NewMsgUser();
                    toMsgUser.setUserid(userId);
                    toUserLists.add(toMsgUser);
                }
                request.setTo(toUserLists);
                newMsgService.send(request);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    /**
     * 提醒   isSend表示是否发短信 true发 false不发
     */
    public void send4Mind(String formId, Integer noRecord, Boolean isSend) {
        if (StringUtils.isEmpty(formId)) {
            return;
        }
        MdForm mdForm = formManager.detail(formId);

        if (mdForm == null) {
            return;
        }

        NewMsgUser user = new NewMsgUser();
        user.setUserid(mdForm.getOwnUser());
        user.setDeptid(mdForm.getOwnDept());

        String formName = mdForm.getName();
        String cycleNow = mdForm.getCycleNow();

        pool.submit(() -> {
            try {
                int pageNum = 1;

                while (true) {

                    FormRecordQuery recordQuery = new FormRecordQuery();
                    recordQuery.setForm_id(formId);
                    recordQuery.setCommit_status(0);
                    recordQuery.setPageNum(pageNum);
                    recordQuery.setPageSize(500);
                    recordQuery.setNoRecord(noRecord);

                    if (StringUtils.isNotBlank(cycleNow)) {
                        recordQuery.setCommit_cycle(cycleNow);
                    }

                    PageInfo<MdFormRecord> page = formRecordManager.queryByPage(recordQuery);
                    if (CollectionUtils.isEmpty(page.getList())) {
                        break;
                    }

                    List<String> userIds = page.getList().stream().map(MdFormRecord::getOwnUser).collect(Collectors.toList());

                    NewMsgSendRequest request = new NewMsgSendRequest();

                    String title = "您有一份表单尚未填报，请尽快处理！";
                    String body = formName + "尚未填报，点击填报。";

                    request.setSendData(build(title, body, formId));
                    request.setFrom(user);

                    List<NewMsgUser> toUserLists = new ArrayList<>();

                    for (String userId : userIds) {
                        NewMsgUser toMsgUser = new NewMsgUser();
                        toMsgUser.setUserid(userId);
                        toUserLists.add(toMsgUser);
                    }
                    request.setTo(toUserLists);
                    newMsgService.send(request);
                    pageNum++;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    private NewMsgSendData build(String title, String body, String formId) {

        NewMsgSendData data = new NewMsgSendData();
        data.setTitle(title);
        data.setBody(body);
        data.setMsgtype((byte) 0);
        data.setNeedpush((byte) 0);
        JSONObject map = new JSONObject();
        map.put("needreply", "0");
        map.put("hasatt", "0");
        map.put("sender", "系统消息");
        map.put("msgcategory", "系统消息");
        map.put("needsms", "0");
        data.setParams(map);
        return data;
    }
}
