package com.testor.module.safeCheck.task;

import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.messageNotice.model.domain.TMsgNotice;
import com.testor.module.messageNotice.model.vo.MsgTemplateVO;
import com.testor.module.messageNotice.service.TMsgNoticeService;
import com.testor.module.safeCheck.model.domain.TSafeCheckPersonArrange;
import com.testor.module.safeCheck.model.domain.TSafeCheckPlan;
import com.testor.module.safeCheck.model.domain.TSafeCheckTask;
import com.testor.module.safeCheck.service.TSafeCheckPersonArrangeService;
import com.testor.module.safeCheck.service.TSafeCheckPlanService;
import com.testor.module.safeCheck.service.TSafeCheckTaskService;
import com.testor.module.safeCheck.service.impl.TSafeCheckTaskServiceImpl;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class HandleTasks implements TaskListener {

    @Autowired
    private TMsgNoticeService tMsgNoticeService;

    @Autowired
    private TSafeCheckPersonArrangeService tSafeCheckPersonArrangeService;

    @Autowired
    private TSafeCheckPlanService tSafeCheckPlanService;


    @Override
    public void notify(DelegateTask delegateTask) {
        Map<String, Object> variablesLocal = delegateTask.getVariablesLocal();
        // 对应业务值
        String bizKeyId = String.valueOf(variablesLocal.get("bizKeyId"));
        String checkUser = String.valueOf(variablesLocal.get("checkUser"));
        TSafeCheckPersonArrange byId = tSafeCheckPersonArrangeService.getById(bizKeyId);
        if (byId != null){
            String planId = byId.getPlanId();
            TSafeCheckPlan tSafeCheckPlan = tSafeCheckPlanService.getById(planId);
            if (tSafeCheckPlan != null){
                String time = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date());
                String msg = "安全检查任务[" + tSafeCheckPlan.getName() + "]于" + time + "开始,请您及时处理";
                // 发送消息
                MsgTemplateVO msgTemplateVO = new MsgTemplateVO();
                msgTemplateVO.setTemplateContent(msg);
                msgTemplateVO.setTemplateType("notice");
                msgTemplateVO.setTemplateTypeName("通知");
                String bizKey = "safetyCheck";
                List<String> userIdList = new ArrayList<String>();
                userIdList.add(checkUser);
                List<TMsgNotice> tMsgNotices = tMsgNoticeService.generateMsgNotice(bizKey, bizKeyId, userIdList, msgTemplateVO);
                tMsgNoticeService.saveBatch(tMsgNotices);
            }
        }


    }
}
