package com.rongwei.sfcommon.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwe.scentity.domian.*;
import com.rongwe.scentity.vo.ThemeCheckItemVo;
import com.rongwei.commonservice.serial.service.SysSerialNumberService;
import com.rongwei.commonservice.service.SysConfigService;
import com.rongwei.rwadmincommon.system.domain.SysUserDo;
import com.rongwei.rwadmincommon.system.service.SysConfigFeignService;
import com.rongwei.rwadmincommon.system.service.SysDictService;
import com.rongwei.rwadmincommon.system.service.SysUserService;
import com.rongwei.rwcommon.base.QueryPar;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.rwcommon.vo.MailDo;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
import com.rongwei.sfcommon.sys.dao.ThemeCheckItemDao;
import com.rongwei.sfcommon.sys.service.HiddenDangerTrackService;
import com.rongwei.sfcommon.sys.service.ThemeCheckContentService;
import com.rongwei.sfcommon.sys.service.ThemeCheckItemService;
import com.rongwei.sfcommon.sys.service.ThemeCheckService;
import com.rongwei.sfcommon.utils.MlConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("themeCheckItemService")
@Slf4j
public class ThemeCheckItemServiceImpl extends ServiceImpl<ThemeCheckItemDao, ThemeCheckItemDo> implements ThemeCheckItemService {

    @Autowired
    private ThemeCheckContentService themeCheckContentService;
    @Autowired
    private ThemeCheckItemDao themeCheckItemDao;
    @Autowired
    private HiddenDangerTrackService hiddenDangerTrackService;
    @Autowired
    private SysSerialNumberService sysSerialNumberService;
    @Autowired
    private ThemeCheckService themeCheckService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysConfigFeignService sysConfigFeignService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysConfigService sysConfigService;


    /**
     * 待检查、已检查日常检查列表
     * @param themeCheckItemVo
     * @return
     */
    @Override
    public IPage<ThemeCheckItemVo> themeCheckList(QueryPar<ThemeCheckItemVo> themeCheckItemVo){
        IPage<ThemeCheckItemVo> retList = null;
        if(MlConstants.THEME_CHECK_STATUS_WAIT.equals(themeCheckItemVo.getParameter().getCheckstatus())){
            retList = themeCheckItemDao.themeChecktodoList(themeCheckItemVo.getPage(),themeCheckItemVo.getParameter().getUserid());
        }else if(MlConstants.THEME_CHECK_STATUS_HAS.equals(themeCheckItemVo.getParameter().getCheckstatus())){
            retList = themeCheckItemDao.themeCheckdoneList(themeCheckItemVo.getPage(),themeCheckItemVo.getParameter().getUserid());
        }
        // 日期格式化
        retList.getRecords().forEach(v->{
            v.setPlanstarttimestr(DateUtil.format(v.getPlanstarttime(),"yyyy-MM-dd HH:mm:ss"));
            v.setPlanendtimestr(DateUtil.format(v.getPlanendtime(),"yyyy-MM-dd HH:mm:ss"));
            v.setActualchecktimestr(DateUtil.format(v.getActualchecktime(),"yyyy-MM-dd HH:mm:ss"));
        });
        return retList;
    }

    /**
     * 日常检查详情信息
     * @param themeCheckItemVo
     * @return
     */
    public ThemeCheckItemVo themeCheckInfo(ThemeCheckItemVo themeCheckItemVo){
        ThemeCheckItemVo themeCheckInfo = new ThemeCheckItemVo();
        ThemeCheckItemDo themeCheckItem = this.getById(themeCheckItemVo.getId());
        BeanUtil.copyProperties(themeCheckItem,themeCheckInfo);
        // 日常检查检查内容明细
        /*Map<String,Object> itemMap = new HashMap<>();
        itemMap.put("THEMECHECKITEMID",themeCheckItemVo.getId());
        List<ThemeCheckContentDo> themeCheckContentDos = (List<ThemeCheckContentDo>)themeCheckContentService.listByMap(itemMap);*/
        ThemeCheckContentDo queryDo = new ThemeCheckContentDo();
        queryDo.setThemecheckitemid(themeCheckItemVo.getId());
        queryDo.setDeleted("0");
        Wrapper<ThemeCheckContentDo> entity = (Wrapper<ThemeCheckContentDo>)new QueryWrapper(queryDo).orderByAsc("ITEMSORT");
        List<ThemeCheckContentDo> themeCheckContentDos = themeCheckContentService.list(entity);

        themeCheckInfo.setThemeCheckContents(themeCheckContentDos);
        themeCheckInfo.setPlanstarttimestr(DateUtil.format(themeCheckInfo.getPlanstarttime(),"yyyy-MM-dd HH:mm:ss"));
        themeCheckInfo.setPlanendtimestr(DateUtil.format(themeCheckInfo.getPlanendtime(),"yyyy-MM-dd HH:mm:ss"));
        themeCheckInfo.setActualchecktimestr(DateUtil.format(themeCheckInfo.getActualchecktime(),"yyyy-MM-dd HH:mm:ss"));
        //检查类别
        ThemeCheckDo themeCheckDo = themeCheckService.getById(themeCheckItem.getThemecheckid());
        themeCheckInfo.setChecktype(themeCheckDo.getChecktype());
        return themeCheckInfo;
    }

    /**
     * 日常检查保存
     * @param themeCheckItemVo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void themeCheckSave(ThemeCheckItemVo themeCheckItemVo){
        this.updateById(themeCheckItemVo);
        themeCheckContentService.updateBatchById(themeCheckItemVo.getThemeCheckContents());
    }

    /**
     * 日常检查保存后生成跟踪任务
     * @param map
     */
    public void createHiddenDangerTask(Map<String,Object> map){
        //根据ID
        String themeCheckItemId = map.get("ID").toString();
        if(StringUtils.isNotEmpty(themeCheckItemId)){
            ThemeCheckItemDo themeCheckItemDo = this.getById(themeCheckItemId);
            ThemeCheckDo themeCheck = themeCheckService.getById(themeCheckItemDo.getThemecheckid());
//            Map<String,Object> itemMap = new HashMap<>();
//            itemMap.put("THEMECHECKITEMID",themeCheckItemId);
//            itemMap.put("DELETED","0");
//            List<ThemeCheckContentDo> themeCheckContents = (List<ThemeCheckContentDo>)themeCheckContentService.listByMap(itemMap);
            ThemeCheckContentDo queryItemDo = new ThemeCheckContentDo();
            queryItemDo.setThemecheckitemid(themeCheckItemId);
            queryItemDo.setDeleted("0");
            Wrapper<ThemeCheckContentDo> Tcentity = (Wrapper<ThemeCheckContentDo>)new QueryWrapper(queryItemDo).orderByAsc("ITEMSORT");
            List<ThemeCheckContentDo> themeCheckContents = themeCheckContentService.list(Tcentity);

            // 生成隐患跟踪任务
            if(themeCheckItemDo != null && MlConstants.CHECK_RESULT_TRACK.equals(themeCheckItemDo.getCheckresult())){
                QueryWrapper<HiddenDangerTrackDo> entity = new QueryWrapper<HiddenDangerTrackDo>()
                        .eq("RELATIONID",themeCheckItemDo.getId())
                        .eq("DANGERSOURCE", MlConstants.DANGER_SOURCE_THEMECHECK)
                        .ne("STATUS",MlConstants.HIDDEN_DANGER_STATUS_HASCLOSE);
                List<HiddenDangerTrackDo> hiddenDangerTracks = hiddenDangerTrackService.list(entity);
                // 不存在当前日常检查生成的状态为未关闭和已延期的任务时，生成一条对应的任务
                if(hiddenDangerTracks == null || hiddenDangerTracks.size() == 0){
                    HiddenDangerTrackDo hiddenDangerTrack = new HiddenDangerTrackDo();
                    hiddenDangerTrack.setId(SecurityUtil.getUUID());
                    //隐患来源 检查录入
                    hiddenDangerTrack.setDangersource(MlConstants.DANGER_SOURCE_THEMECHECK);
                    hiddenDangerTrack.setRelationid(themeCheckItemDo.getId());
                    hiddenDangerTrack.setFinduser(themeCheckItemDo.getGroupleader());
                    hiddenDangerTrack.setFindusername(themeCheckItemDo.getGroupleadername());
                    hiddenDangerTrack.setFindtime(themeCheckItemDo.getActualchecktime());
                    hiddenDangerTrack.setStatus(MlConstants.HIDDEN_DANGER_STATUS_NOTCLOSE);
                    // 总编号生成
                    SysSerialVo sysSerialVo = new SysSerialVo();
                    sysSerialVo.setRuleTemplateStr("@{date:yyyyMMdd}@{serialNumber:#000000}");
                    sysSerialVo.setModulecode("asp_hidden_danger_track_CODE");
                    hiddenDangerTrack.setCode(sysSerialNumberService.getCodeByTemplate(sysSerialVo));
                    // 指派跟踪人取点检人的所属工段的工段主管
                    if(StringUtils.isNotEmpty(themeCheckItemDo.getChargeorgid())){
                        String[] orgs = themeCheckItemDo.getChargeorgid().split("/");
                        List<Map<String,Object>> users = null;
                        // 全厂检查 跟踪人为安全工程师
                        if(MlConstants.THEMECHECK_TYPE_DAYCHECK.equals(themeCheck.getChecktype())){
                            // 安全工程师
                            users = themeCheckItemDao.getGdzgByUserId(null,"safety-engineer");
                        }else if(MlConstants.THEMECHECK_TYPE_SPECIALCHECK.equals(themeCheck.getChecktype())){
                            // 周五专项检查 跟踪人为工段主管
                            users = themeCheckItemDao.getGdzgByUserId(orgs[orgs.length-1],"gdzg");
                        }
                        if(users != null && users.size()>0){
                            String userids = "";
                            String usernames = "";
                            for(Map<String,Object> user:users){
                                if("".equals(userids)){
                                    userids = user.get("USERID").toString();
                                }else{
                                    userids = userids+","+user.get("USERID").toString();
                                }
                                if("".equals(usernames)){
                                    usernames = user.get("USERNAME").toString();
                                }else{
                                    usernames = usernames+","+user.get("USERNAME").toString();
                                }
                            }
                            hiddenDangerTrack.setTrackuserid(userids);
                            hiddenDangerTrack.setTrackusername(usernames);
                            // 设置最初指派跟踪人
                            hiddenDangerTrack.setFirsttrackuserid(userids);
                            hiddenDangerTrack.setFirsttrackusername(usernames);
                        }
                    }
                    // 隐患内容  发现项+检查内容+备注
                    StringBuilder sb = new StringBuilder();
                    sb.append("发现项：");
                    if(StringUtils.isNotEmpty(themeCheckItemDo.getDiscoveryitems())){
                        sb.append(themeCheckItemDo.getDiscoveryitems());
                    }
                    sb.append("\n");
                    // if(themeCheckContents != null && themeCheckContents.size()>0){
                    //     for(ThemeCheckContentDo themeCheckContent:themeCheckContents){
                    //         sb.append("检查内容：").append(themeCheckContent.getCheckcontent()).append("；");
                    //         if(themeCheckContent.getRemark() != null){
                    //             sb.append("备注：").append(themeCheckContent.getRemark());
                    //             sb.append("；").append("\n");
                    //         }
                    //     }
                    // }
                    hiddenDangerTrack.setHiddendangercontent(sb.toString());
                    // 隐患工段
                    hiddenDangerTrack.setDangerworkpark(themeCheckItemDo.getChargeorgid());
                    hiddenDangerTrack.setDangerworkparkname(themeCheckItemDo.getChargeorgname());
                    // 限整改日期
                    if(themeCheckItemDo.getActualchecktime() != null){
                        hiddenDangerTrack.setRectificationdate(DateUtil.offsetDay(themeCheckItemDo.getActualchecktime(),7));
                    }
                    // 隐患类型默认为一般
                    hiddenDangerTrack.setHiddendangertype(MlConstants.HIDDEN_DANGER_TYPE_NORMAL);
                    hiddenDangerTrack.setCheckphoto(themeCheckItemDo.getCheckphoto());
                    // 隐患跟踪任务保存
                    hiddenDangerTrackService.save(hiddenDangerTrack);
                }
            }

            // 邮件发送
            MailDo mail = new MailDo();
            if(MlConstants.THEMECHECK_TYPE_SPECIALCHECK.equals(themeCheck.getChecktype())){
                mail.setSubject("周五专项检查结果");
            }else if(MlConstants.THEMECHECK_TYPE_DAYCHECK.equals(themeCheck.getChecktype())){
                mail.setSubject("主管经理检查结果");
            }

            StringBuilder mailContent = new StringBuilder();
            mailContent.append("检查主题：");
            if(StringUtils.isNotEmpty(themeCheckItemDo.getThemecheckname())){
                mailContent.append(themeCheckItemDo.getThemecheckname());
            }
            mailContent.append("\n");
            mailContent.append("组长：");
            if(StringUtils.isNotEmpty(themeCheckItemDo.getGroupleadername())){
                mailContent.append(themeCheckItemDo.getGroupleadername());
            }
            mailContent.append("\n");
            mailContent.append("组员：");
            if(StringUtils.isNotEmpty(themeCheckItemDo.getGroupusernames())){
                mailContent.append(themeCheckItemDo.getGroupusernames());
            }
            mailContent.append("\n");
            mailContent.append("检查时间：");
            if(themeCheckItemDo.getPlanstarttime() != null){
                mailContent.append(DateUtil.format(themeCheckItemDo.getPlanstarttime(),"yyyy-MM-dd HH:mm:ss"));
            }
            mailContent.append(" 至 ");
            if(themeCheckItemDo.getPlanendtime() != null){
                mailContent.append(DateUtil.format(themeCheckItemDo.getPlanendtime(),"yyyy-MM-dd HH:mm:ss"));
            }
            mailContent.append("\n");
            /*mailContent.append("检查项：\n");
            if(themeCheckContents != null && themeCheckContents.size()>0){
                for(ThemeCheckContentDo checkContent:themeCheckContents){
                    if(StringUtils.isNotEmpty(checkContent.getCheckposition())){
                        mailContent.append("检查部位：").append(checkContent.getCheckposition()).append("；");
                    }listByfoldIdAndRelationId
                    if(StringUtils.isNotEmpty(checkContent.getCheckcontent())){
                        mailContent.append("检查内容：").append(checkContent.getCheckcontent()).append("；");
                    }
                    if(checkContent.getQualifiednum() != null){
                        mailContent.append("合格数：").append(checkContent.getQualifiednum()).append("；");
                    }
                    if(checkContent.getViolationsnum() != null){
                        mailContent.append("违规数：").append(checkContent.getViolationsnum()).append("；");
                    }
                    if(StringUtils.isNotEmpty(checkContent.getRemark())){
                        mailContent.append("备注：").append(checkContent.getRemark()).append("；");
                    }
                    mailContent.append("\n");
                }
            }*/
            mailContent.append("发现项：\n");
            if(StringUtils.isNotEmpty(themeCheckItemDo.getDiscoveryitems())){
                mailContent.append(themeCheckItemDo.getDiscoveryitems());
            }
            mailContent.append("\n\n");
            mailContent.append("检查结果：");
            if(StringUtils.isNotEmpty(themeCheckItemDo.getCheckresult())){
                String resultname = sysDictService.getDictNameByValue("asp_check_result",themeCheckItemDo.getCheckresult());
                if(resultname != null){
                    mailContent.append(resultname);
                }
            }
            mailContent.append("\n\n");
            mailContent.append("详见智能安全监控平台：http://192.168.0.205:8000");
            // 邮件接收人，组员和组长
            String leaders = themeCheckItemDo.getGroupleader();
            String groups = themeCheckItemDo.getGroupusers();
            leaders = leaders == null ? "" : leaders;
            groups = groups == null ? "" : groups;
            String ids = leaders;
            if("".equals(ids)){
                ids = groups;
            }else{
                ids = ids + "," + groups;
            }
            // 经理值班检查还需要发送到领导角色
            if(MlConstants.THEMECHECK_TYPE_DAYCHECK.equals(themeCheck.getChecktype())){
                List<Map<String,Object>> uleaders = themeCheckItemDao.getGdzgByUserId(null,"code-leader");
                if(uleaders != null && uleaders.size()>0){
                    List<String> leaderIds = new ArrayList<>();
                    uleaders.forEach(v->{
                        leaderIds.add(v.get("USERID").toString());
                    });

                    if(StringUtils.isNotEmpty(ids)){
                        ids = ids + "," + String.join(",",leaderIds);
                    }else{
                        ids = String.join(",",leaderIds);
                    }
                }
            }else if(MlConstants.THEMECHECK_TYPE_SPECIALCHECK.equals(themeCheck.getChecktype())){
                // 周五专项检查邮件发送指定人
                if(StringUtils.isNotEmpty(themeCheckItemDo.getMailsenduserids())){
                    if(StringUtils.isNotEmpty(ids)){
                        ids = ids + "," + themeCheckItemDo.getMailsenduserids();
                    }else{
                        ids = themeCheckItemDo.getMailsenduserids();
                    }
                }
            }
            /*if(MlConstants.THEMECHECK_TYPE_DAYCHECK.equals(themeCheck.getChecktype())){
                // 主管经理检查结果固定人员
                String zgjljcjgMails = sysConfigService.getContentByConfigCode("zgjljcjgMails");
                log.info("主管经理检查结果所有收件人:",zgjljcjgMails);
                if(StringUtils.isNotEmpty(zgjljcjgMails)){
                    JSONArray mailArray = JSONUtil.parseArray(zgjljcjgMails);
                    for(int i=0;i<mailArray.size();i++){
                        JSONObject jsonObject = mailArray.getJSONObject(i);
                        JSONArray receiveEmail = jsonObject.getJSONArray("receiveEmail");
                        String[] strings = new String[receiveEmail.size()];
                        String[] str = receiveEmail.toArray(strings);
                        log.info("主管经理检查结果单组收件人:",JSONUtil.toJsonStr(str));
                        if(str != null && str.length>0){
                            mail.setReceiveEmail(str);
                            mail.setContent(mailContent.toString());
                            // 邮件发送服务调用
                            sysConfigFeignService.sendTextMail(mail);
                            try {
                                Thread.sleep(5000L);
                            } catch (InterruptedException e) {
                                log.error(e.getMessage());
                            }
                        }
                    }
                }
            }else{*/
                if(StringUtils.isNotEmpty(ids)){
                    String[] idArray = ids.split(",");
                    List<SysUserDo> users = (List<SysUserDo>)sysUserService.listByIds(Arrays.asList(idArray));
                    if(users != null && users.size()>0){
                        List<String> reMails = new ArrayList<>();
                        for(SysUserDo user:users){
                            if(StringUtils.isNotEmpty(user.getEmail()) && !reMails.contains(user.getEmail())){
                                reMails.add(user.getEmail());
                            }
                        }
                        String[] userArray = new String[reMails.size()];
                        mail.setReceiveEmail(reMails.toArray(userArray));
                        mail.setContent(mailContent.toString());
                        // 邮件发送服务调用
                        sysConfigFeignService.sendTextMail(mail);
                    }
                }
//            }
        }
    }

}
