package com.artfess.cqxy.universal.manager.impl;
import com.artfess.application.service.TemplateService;
import com.artfess.application.service.impl.TemplateServiceImpl;
import com.artfess.base.jms.JmsActor;
import com.artfess.base.jms.Notice;
import com.artfess.base.jms.NoticeMessageType;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.DateUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.cqxy.projectManagement.manager.ProjectManagementManager;
import com.artfess.cqxy.projectManagement.model.ProjectManagement;
import com.artfess.cqxy.universal.dao.NoticeDao;
import com.artfess.cqxy.universal.manager.NoticeManager;
import com.artfess.cqxy.universal.model.NoticeDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description:
 * @Author: Rong Tao
 * @Date: 2022/7/24 20:04
 */

@Component
public class NoticeManagerImpl extends BaseManagerImpl<NoticeDao,NoticeDTO> implements NoticeManager{

    @Autowired
    private ProjectManagementManager pmm;

    @Override
    //每天上午10:15触发
    @Scheduled(cron = "0 15 10 ? * *")
    public void isSend() {
        for(ProjectManagement projectManagement : pmm.list()){
            //筛选出状态在施工之前的项目
            if(Integer.valueOf(projectManagement.getProjectStatus()) < 11){
                String projectId = projectManagement.getId();
                String projectName = projectManagement.getProjectName();
                //合同状态以外的状态都是显示的下一个状态，所以查询的是上一个状态资料的上传时间
                Integer prevStatus = Integer.valueOf(projectManagement.getProjectStatus())-1;
                String tableName = getTableNameByStatus(String.valueOf(prevStatus));
                Calendar target = Calendar.getInstance();

                //目标状态是否上传资料
                String targetStatus = projectManagement.getProjectStatus();

                //除合同状态显示的是当前状态，其他显示的是下一个状态
                //判断当前状态是否是合同
                if(projectManagement.getProjectStatus().equals("9")){
                    //根据项目当前状态设置对应表名
                    tableName = getTableNameByStatus(projectManagement.getProjectStatus());
                    //查询下一个状态
                    targetStatus = String.valueOf(Integer.valueOf(projectManagement.getProjectStatus())+ 1);
                }

                //资料最新上传时间
                String createTime = getCreateTimeById(tableName, projectId);
                Date date = DateUtils.str2Date(createTime,new SimpleDateFormat("yyyy-MM-dd"));
                target.setTime(date);
                int tYear = target.get(Calendar.YEAR);
                int tMonth = target.get(Calendar.MONTH);
                int tDay = target.get(Calendar.DATE);

                Calendar now = Calendar.getInstance();
                int nowYear = now.get(Calendar.YEAR);
                int nowMonth = now.get(Calendar.MONTH);
                int nowDay = now.get(Calendar.DATE);

                //查询目标状态是否上传资料
                Integer targetNum = getCount(getTableNameByStatus(String.valueOf(targetStatus)), projectId);

                //根据项目状态查询消息配置中上传提醒时间限制
                Integer limitTime = getLimitTimeByCode(targetStatus);

                //目录管理提醒时间：（天）timeoutPeriod
                //判断是否超过时间限制,未超过限制时间跳过本次循环
                if(nowYear==tYear && nowMonth==tMonth && nowDay-tDay<limitTime){
                    continue;
                }
                //目标状态还没有上传数据，发送消息提醒
                if(targetNum==0) {
                    System.out.println("发送消息");
                    send(projectManagement.getProjectManagerId(),projectName,getFileNameByStatus(String.valueOf(targetStatus)));
                }

            }
        }
    }

    @Override
    //每月25-31号9:30触发
    @Scheduled(cron = "0 30 9 25,26,27,28,29,30,31 * ? ")
    //工程月报发送通知
    public void isReportSend() {
        for(ProjectManagement projectManagement : pmm.list()){
            //筛选出状态在施工的项目
            if(projectManagement.getProjectStatus().equals("11")){
                String projectId = projectManagement.getId();
                String projectName = projectManagement.getProjectName();

                Integer count = getCountReport(projectId);

                Calendar now = Calendar.getInstance();
                int nowMonth = now.get(Calendar.MONTH)+1;

                //判断审批日期是否有本月的数据，如果没有就发送消息
                if(BeanUtils.isEmpty(count) || count == 0){
                    send(projectManagement.getProjectManagerId(),projectName,nowMonth+"月工程月报");
                    break;
                }
            }
        }
    }

    @Override
    public void send(String id,String projectName,String content){
        //判断项目所属人员id是否有多个
        ArrayList<JmsActor> actors = new ArrayList<>();
        String[] ids = id.split(",");
        if(ids.length>=1){
            TemplateService templateService = new TemplateServiceImpl();

            Notice notice = new Notice();
            notice.setMessageTypes(new NoticeMessageType[]{NoticeMessageType.INNER});
            notice.setSubject("上传资料通知");
            notice.setContent("您管理的【"+projectName+"】项目"+content+"资料还未进行填报，请及时进行填报。");
            notice.setReceivers(getAccountById(id).split(","));

            for(String pId : ids){
                JmsActor jmsActor = new JmsActor();
                jmsActor.setAccount(getAccountById(pId));
                //"1509749870024593408"
                jmsActor.setId(pId);
//                jmsActor.setName("刘勤");
                actors.add(jmsActor);
            }
            notice.setReceiver(actors);
            templateService.sendNotice(notice);
        }
    }

    public String getTableNameByStatus(String status){
        // 1：决策，2：立项：3：可研批复，4：规划，5：初步设计，6：概算，7：施工图，8：招投标，9：合同，10：施工许可
        String tableName = "";
        switch(status){
            case "1":
                tableName = "BIZ_DECISION_BASIS";
                break;
            case "2":
                tableName = "BIZ_PROJECT_ESTABLISHMENT";
                break;
            case "3":
                tableName = "biz_feasibility_study_reply";
                break;
            case "4":
                tableName = "BIZ_PLANNING_ENGINEERING";
                break;
            case "5":
                tableName = "BIZ_PRELIMINARY_DESIGN";
                break;
            case "6":
                tableName = "BIZ_ESTIMATE";
                break;
            case "7":
                tableName = "BIZ_CONSTRUCTION_DRAWING";
                break;
            case "8":
                tableName = "BIZ_BIDDING_MANAGEMENT";
                break;
            case "9":
                tableName = "BIZ_CONTRACT";
                break;
            default:
                tableName = "BIZ_CONSTRUCTION_PERMIT";
                break;
        }
        return tableName;
    }

    @Override
    public Integer getLimitTimeByCode(String id){
        Integer intId = Integer.valueOf(id);
        if(intId>7){
            intId+=2;
            id=String.valueOf(intId);
        }
        return baseMapper.getLimitTimeByCode(id);
    }

    public String getFileNameByStatus(String status){
        // 1：决策，2：立项：3：可研批复，4：规划，5：初步设计，6：概算，7：施工图，8：招投标，9：合同，10：施工许可
        String fileName = "";
        switch(status){
            case "1":
                fileName = "决策";
                break;
            case "2":
                fileName = "立项";
                break;
            case "3":
                fileName = "可研";
                break;
            case "4":
                fileName = "规划";
                break;
            case "5":
                fileName = "初步设计";
                break;
            case "6":
                fileName = "概算";
                break;
            case "7":
                fileName = "施工图";
                break;
            case "8":
                fileName = "招投标";
                break;
            case "9":
                fileName = "合同";
                break;
            default:
                fileName = "施工许可";
                break;
        }
        return fileName;
    }

    @Override
    public String getAccountById(String id){
        return baseMapper.getAccountById(id);
    }

    @Override
    public String getCreateTimeById(String tableName,String projectId) {
         return baseMapper.getCreateTimeById(tableName,projectId);
    }

    @Override
    public Integer getCount(String tableName,String projectId) {
        return baseMapper.getCount(tableName,projectId);
    }

    @Override
    public Integer getCountReport(String projectId) {
        return baseMapper.getCountReport(projectId);
    }
}
