package com.jeeplus.common.web;

import com.easemob.server.example.api.impl.EasemobChatMessage;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.iim.entity.MyCalendar;
import com.jeeplus.modules.iim.service.MyCalendarService;
import com.jeeplus.modules.oa.entity.OaAttendance;
import com.jeeplus.modules.oa.entity.OaAttendanceRule;
import com.jeeplus.modules.oa.service.OaAttendanceService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysuseroffice.entity.Useroffice;
import com.jeeplus.modules.sysuseroffice.service.UserofficeService;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workdailyroutine.entity.WorkDailyRoutine;
import com.jeeplus.modules.workdailyroutine.entity.WorkDailyRoutineDetail;
import com.jeeplus.modules.workdailyroutine.service.WorkDailyRoutineService;
import com.jeeplus.modules.workmeeting.entity.Workmeetinginfo;
import com.jeeplus.modules.workmeeting.entity.Workmeetinguser;
import com.jeeplus.modules.workmeeting.service.WorkmeetinginfoService;
import com.jeeplus.modules.workmeeting.service.WorkmeetinguserService;
import com.jeeplus.modules.workrelationship.entity.WorkRelationship;
import com.jeeplus.modules.workrelationship.service.WorkRelationshipService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Lazy(false)
public class TaskTime {

    @Autowired
    private MyCalendarService myCalendarService;
    @Autowired
    private OaAttendanceService oaAttendanceService;
    @Autowired
    private UserofficeService userofficeService;
    @Autowired
    private WorkmeetinginfoService workmeetinginfoService;
    @Autowired
    private WorkmeetinguserService workmeetinguserService;
    @Autowired
    private WorkBidProjectService workBidProjectService;
    @Autowired
    private WorkDailyRoutineService workDailyRoutineService;
    @Autowired
    private WorkRelationshipService workRelationshipService;
    @Autowired
    private WorkStaffBasicInfoService workStaffBasicInfoService;
    @Autowired
    private UserService userService;

    public static final Logger logger = LoggerFactory.getLogger(TaskTime.class);
    private EasemobChatMessage easemobChatMessage = new EasemobChatMessage();
    private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");


    //@Scheduled(cron = "*/5 * * * * ?")//每隔5秒执行一次：*/5 * * * * ?
    @Scheduled(cron = "0 0 2 * * ?")//每天凌晨两点执行
    public void task1(){
        try {
        logger.info("任务开始......");
        long begin = System.currentTimeMillis();
        OaAttendance oaAttendance = new OaAttendance();
        String date = formatter.format(new Date());
        logger.info("now="+date);

        List<WorkBidProject> list = workBidProjectService.findListByGiveDate(new WorkBidProject());
        if(list != null && list.size() > 0){
            for (WorkBidProject w:
                 list) {
                WorkDailyRoutine workDailyRoutine = new WorkDailyRoutine();
                workDailyRoutine.setName(w.getProjectName());
                workDailyRoutine.setSource("投标保证金交付发送");
                workDailyRoutine.setStatus("未完成");
                workDailyRoutine.setCreateBy(w.getCreateBy());
                workDailyRoutine.setOffice(new Office(w.getOfficeId()));
                workDailyRoutine.setCompany(new Office(w.getCompanyId()));
                workDailyRoutine.setCreateDate(new Date());
                workDailyRoutine.setRemarks(w.getProjectName()+"的投标保证金该交付了！");
                List<WorkDailyRoutineDetail> detailList = new ArrayList<>();
                WorkDailyRoutineDetail routineDetail = new WorkDailyRoutineDetail();
                routineDetail.setOperator(w.getCreateBy());
                detailList.add(routineDetail);
                workDailyRoutine.setDetailList(detailList);
                workDailyRoutine.setSourceId(w.getId());
                workDailyRoutineService.save(workDailyRoutine);
                //添加提醒标记
                workBidProjectService.updateGiveDateSign(w);
            }
        }
        long end = System.currentTimeMillis();
        logger.info("任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
        } catch (Exception e) {
            logger.error("-------------投标交付时间提前三天提醒发生异常-------------");
        }
    }
    //@Scheduled(cron = "*/5 * * * * ?")
    @Scheduled(cron = "0 0 2 * * ?")//每天凌晨两点执行
    public void task2(){
        try {
            logger.info("任务开始......");
            long begin = System.currentTimeMillis();
            OaAttendance oaAttendance = new OaAttendance();
            String date = formatter.format(new Date());
            logger.info("now="+date);

            List<WorkBidProject> list = workBidProjectService.findListByBidDate(new WorkBidProject());
            if(list != null && list.size() > 0){
                for (WorkBidProject w:
                        list) {
                    WorkDailyRoutine workDailyRoutine = new WorkDailyRoutine();
                    workDailyRoutine.setName(w.getProjectName());
                    workDailyRoutine.setSource("投标保证金确认发送");
                    workDailyRoutine.setStatus("未完成");
                    workDailyRoutine.setCreateBy(w.getCreateBy());
                    workDailyRoutine.setOffice(new Office(w.getOfficeId()));
                    workDailyRoutine.setCompany(new Office(w.getCompanyId()));
                    workDailyRoutine.setCreateDate(new Date());
                    workDailyRoutine.setRemarks(w.getProjectName()+"的投标保证金需要到财务部确认一下！");
                    List<WorkDailyRoutineDetail> detailList = new ArrayList<>();
                    WorkDailyRoutineDetail routineDetail = new WorkDailyRoutineDetail();
                    routineDetail.setOperator(w.getCreateBy());
                    detailList.add(routineDetail);
                    workDailyRoutine.setDetailList(detailList);
                    workDailyRoutine.setSourceId(w.getId());
                    workDailyRoutineService.save(workDailyRoutine);
                    //添加提醒标记id
                    workBidProjectService.updateBidDateSign(w);
                }
            }
            long end = System.currentTimeMillis();
            logger.info("任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
        } catch (Exception e) {
            logger.error("-------------投标日期三十天保证金确认提醒发生异常-------------");
        }
    }


    //自动续签
    //@Scheduled(cron = "*/5 * * * * ?")
    @Scheduled(cron = "0 0 2 * * ?")//每天凌晨两点执行
    public void task3(){
        try {
            logger.info("任务开始......");
            long begin = System.currentTimeMillis();
            OaAttendance oaAttendance = new OaAttendance();
            String date = formatter.format(new Date());
            logger.info("now="+date);
            int day=0;
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            List<WorkRelationship> list = workRelationshipService.findLists(new WorkRelationship());
            Map<String, Object> variables = Maps.newHashMap();
            String processInstanceId ="";
            if(list != null && list.size() > 0){
                for (WorkRelationship w:
                        list) {
                    WorkStaffBasicInfo staffBasicInfo = w.getWorkStaffBasicInfo();
                    if(staffBasicInfo!=null && StringUtils.isNotBlank(staffBasicInfo.getId())){
                        staffBasicInfo = workStaffBasicInfoService.getAchives(staffBasicInfo.getId());
                        if(staffBasicInfo!=null && StringUtils.isNotBlank(staffBasicInfo.getUserId())){
                            User u = userService.get(staffBasicInfo.getUserId());
                            if(u!=null){
                                //是否自动续签
                                String isRelation = UserUtils.getSysParam("is_relation",u);
                                if("是".equals(isRelation)){
                                    //提前提醒天数
                                    String _relationDay = UserUtils.getSysParam("relation_day",u);
                                    if(StringUtils.isNotBlank(_relationDay)){
                                        long relationDay = Long.parseLong(_relationDay);
                                        if(w.getContractEndTime()!=null){
                                            day = daysBetween(format.format(w.getContractEndTime()));
                                            if(day <= relationDay){
                                                //符合条件的数据发起续签
                                                WorkRelationship workRelationship = new WorkRelationship();
                                                workRelationship.setWorkStaffBasicInfo(staffBasicInfo);
                                                workRelationship.setOfficeId(u.getOffice().getId());
                                                workRelationship.setCompanyId(u.getCompany().getId());
                                                workRelationship.setStatus("2");
                                                workRelationship.setCreateDate(new Date());
                                                workRelationship.setUpdateBy(u);
                                                workRelationship.setCreateBy(u);
                                                workRelationship.setCurrentUser(u);
                                                workRelationship.setDelFlag("0");
                                                workRelationshipService.saveRelation(workRelationship, variables,processInstanceId);
                                                //添加提醒标记id
                                                workRelationshipService.updateSign(w);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            long end = System.currentTimeMillis();
            logger.info("任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
        } catch (Exception e) {
            logger.error("-------------自动续签发生异常-------------");
        }
    }
    public int daysBetween(String dateStr) throws ParseException {
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date compareDate = sdf.parse(dateStr);

        Calendar cal = Calendar.getInstance();
        cal.setTime(compareDate);
        long time1 = cal.getTimeInMillis();

        cal.setTime(today);
        long time2 = cal.getTimeInMillis();
        long between_days = (time1 - time2) / (1000 * 3600 * 24) + 1 ;

        return Integer.parseInt(String.valueOf(between_days));
    }
    @Scheduled(cron = "0 0 2 * * ?")//每天凌晨两点执行
    public void taskOaAttendance(){
        try {
            logger.error("考勤打卡任务开始......");
            long begin = System.currentTimeMillis();
            OaAttendance oaAttendance = new OaAttendance();
            String date = formatter.format(new Date());
            logger.error("now="+date);

            List<String> companyList = oaAttendanceService.getCompanyList();
            if(companyList != null && companyList.size()>0){
                for(String companyId : companyList){
                    if(StringUtils.isNotBlank(companyId)){
                        List<OaAttendance> oaAttendanceList = oaAttendanceService.getOaAttendanceList(companyId,oaAttendanceService.parseDate());
                        if(oaAttendanceList != null && oaAttendanceList.size()>0){
                           Useroffice useroffice = new Useroffice();
                           useroffice.setCompanyId(companyId);
                           useroffice.setStatus("3");
                            List<Useroffice> userofficeList = userofficeService.findList(useroffice);
                            if(userofficeList != null && userofficeList.size()>0){
                                for(Useroffice uo : userofficeList){
                                    OaAttendance oa = oaAttendanceService.getOaAttendanceByCompanyIdAndUserIdAndSignDate(companyId,uo.getUserId());
                                    if(oa == null){
                                        Office company = new Office();
                                        company.setId(companyId);
                                        oaAttendance.setId("");
                                        oaAttendance.setCompany(company);
                                        oaAttendance.setUser(new User(uo.getUserId()));
                                        oaAttendance.setRule(new OaAttendanceRule(oaAttendanceList.get(0).getRule().getId()));
                                        oaAttendance.setSignDate(oaAttendanceService.parseDate());
                                        oaAttendance.setRemarks("未打卡--"+formatter.format(oaAttendanceService.parseDate()));
                                        oaAttendance.setCreateBy(new User("1"));
                                        oaAttendance.setUpdateBy(new User("1"));
                                        oaAttendance.setOfficeId(uo.getOfficeId());
                                        oaAttendance.setOffice(new Office(uo.getOfficeId()));
                                        oaAttendanceService.save(oaAttendance);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            long end = System.currentTimeMillis();
            logger.error("当日考勤打卡任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
        } catch (Exception e) {
            logger.error("-------------考勤打卡---解析信息发生异常-------------");
        }
    }

    @Scheduled(cron = "0 0 8 * * ?")
    public void taskGetCalendarByDate() {
        try {
            logger.info("当日定时任务开始......");
            long begin = System.currentTimeMillis();
            MyCalendar myCalendar = new MyCalendar();
            String date = formatter.format(new Date());
            logger.info("now="+date);
            myCalendar.setStart(date);
            List<MyCalendar> mapList = myCalendarService.getByUserIdCount(myCalendar);
            if (mapList!=null && mapList.size()!=0){
                for (MyCalendar m :mapList){
                    if (m.getUser()!=null && m.getUser().getId()!=null && !m.getUser().getId().equals("")){
                        logger.info("m.getUser().getId()="+m.getUser().getId());
                        Map extras = new HashMap();
                        String title="今日日程";
                        String content="今天有("+m.getCount()+")个要处理的日程";
                        extras.put("type", "5001");
                        extras.put("id", "");
                        String aliase = m.getUser().getId();
                        JPushClientUtil.sendNotificationToAlias(title, content, extras, aliase);
                    }
                }
            }

            long end = System.currentTimeMillis();
            logger.info("当日定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
        } catch (Exception e) {
            logger.error("-------------解析信息发生异常--------------");
        }
    }

    /*@Scheduled(cron = "30 40 * * * ?")//每小时执行
    public void taskGroupIdMessageByDate() {
        try {
            logger.info("当日定时任务开始......读取环信数据");
            long begin = System.currentTimeMillis();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
            Date date = new Date();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(Calendar.HOUR,-12);//把日期往前减少一天，若想把日期向后推一天则将负数改为正数
            date=calendar.getTime();
            String time = sdf.format(date);
            logger.info("time="+time);
            Object result = easemobChatMessage.exportChatMessage(time);
            String jsonStr = "";
            logger.info(result+"");

            if (result!=null){
                JSONObject json = JSONObject.fromObject(result);
                if(json!=null && StringUtils.isNotBlank(json.get("data").toString())){
                    List<Map> data = (List<Map>) json.get("data");
                    String url = data.get(0).get("url").toString();
                    //url中不可以出现空格，空格全部用%20替换
                    try {
                        URL urls = new URL(url);
                        java.net.HttpURLConnection conn = (java.net.HttpURLConnection)urls.openConnection();
                        //因为服务器的安全设置不接受Java程序作为客户端访问，解决方案是设置客户端的User Agent
                        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                        conn.setDoOutput(true);
                        conn.setDoInput(true);
                        //只可以设置为GET方式，不可以使用POST方式
                        //conn.setRequestMethod("POST");
                        conn.setRequestMethod("GET");
                        //设置编码格式为UTF-8
                        conn.setRequestProperty("contentType", "UTF-8");

                        //得到输入流
                        InputStream inputStream = conn.getInputStream();
                        //从输入流中获取数据（一定要设置编码格式，不然在服务器端接收到的数据可能乱码）
                        BufferedReader bf=new BufferedReader(new InputStreamReader(new GZIPInputStream(inputStream),"UTF-8"));
                        String line=null;
                        while((line=bf.readLine())!=null){//一行一行的读
                            jsonStr = jsonStr + line;
                        }
                        if(inputStream!=null){
                            inputStream.close();
                        }
                        String[] strs = jsonStr.split("\\\\");
                        String str = "";
                        StringBuffer jsons = new StringBuffer("");
                        for (int i = 0; i < strs.length; i++) {
                            str = strs[i];
                            jsons = jsons.append(str);
                        }
                        String[] arr = jsons.toString().split("}\\{");
                        for (int i = 0;i<arr.length;i++){
                            String string = "";
                            if (i==0){
                                string = arr[i]+"}";
                            }else if(i==arr.length-1){
                                string = "{"+arr[i];
                            }else {
                                string = "{"+arr[i]+"}";
                            }
                            logger.info(string);
                            JSONObject jsonObject = JSONObject.fromObject(string);
                            if (jsonObject!=null && jsonObject.get("to")!=null && jsonObject.get("from")!=null){
                                String to = jsonObject.get("to").toString();
                                String from = jsonObject.get("from").toString();
                                String chat_type = jsonObject.get("chat_type").toString();
                                EasemobMenage easemobMenage = new EasemobMenage();
                                easemobMenage.setUserId(from);
                                easemobMenage.setChatType(chat_type);
                                if (chat_type.equals("chat")){
                                    easemobMenage.setContactsId(to);
                                }else {
                                    easemobMenage.setGroupId(to);
                                }
                                if (jsonObject.get("payload")!=null){
                                    Map<String,Object> map = (Map)jsonObject.get("payload");
                                    List<Map<String,Object>> list = (List)map.get("bodies");
                                    for (Map<String,Object> mapObj:list){
                                        String type = mapObj.get("type").toString();
                                        if (type.equals("txt")){
                                            easemobMenage.setType(type);
                                            easemobMenage.setMsg(mapObj.get("msg").toString());
                                        }else if (type.equals("img")){
                                            easemobMenage.setType(type);
                                            easemobMenage.setFileLength(mapObj.get("file_length").toString());
                                            easemobMenage.setFilename(mapObj.get("filename").toString());
                                            easemobMenage.setSize(mapObj.get("size").toString());
                                            easemobMenage.setSecret(mapObj.get("secret").toString());
                                            easemobMenage.setUrl(mapObj.get("url").toString());
                                        }else if (type.equals("loc")){
                                            easemobMenage.setType(type);
                                            easemobMenage.setAddr(mapObj.get("addr").toString());
                                            easemobMenage.setLat(mapObj.get("lat").toString());
                                            easemobMenage.setLng(mapObj.get("lng").toString());
                                        }else if (type.equals("audio")){
                                            easemobMenage.setType(type);
                                            easemobMenage.setFileLength(mapObj.get("file_length").toString());
                                            easemobMenage.setFilename(mapObj.get("filename").toString());
                                            easemobMenage.setLength(mapObj.get("length").toString());
                                            easemobMenage.setSecret(mapObj.get("secret").toString());
                                            easemobMenage.setUrl(mapObj.get("url").toString());
                                        }else if (type.equals("video")){
                                            easemobMenage.setType(type);
                                            easemobMenage.setFileLength(mapObj.get("file_length").toString());
                                            easemobMenage.setFilename(mapObj.get("filename").toString());
                                            easemobMenage.setLength(mapObj.get("length").toString());
                                            easemobMenage.setSecret(mapObj.get("secret").toString());
                                            easemobMenage.setSize(mapObj.get("size").toString());
                                            easemobMenage.setThumb(mapObj.get("thumb").toString());
                                            easemobMenage.setThumbSecret(mapObj.get("thumb_secret").toString());
                                            easemobMenage.setUrl(mapObj.get("url").toString());
                                        }else if (type.equals("file")){
                                            easemobMenage.setType(type);
                                            easemobMenage.setFileLength(mapObj.get("file_length").toString());
                                            easemobMenage.setFilename(mapObj.get("filename").toString());
                                            easemobMenage.setSecret(mapObj.get("secret").toString());
                                            easemobMenage.setUrl(mapObj.get("url").toString());
                                        }else{
                                            easemobMenage.setType(type);
                                        }
                                    }
                                }
                                easemobMenageService.save(easemobMenage);
                            }
                        }
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            long end = System.currentTimeMillis();
            logger.info("当日定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
        } catch (Exception e) {
            logger.error("-------------解析信息发生异常--------------");
        }
    }*/

    @Scheduled(cron = "0 38 * * * ?")//每小时执行
    public void updateMeetingStatus() {
        try {
            List<Workmeetinginfo> workmeetinginfos = workmeetinginfoService.findListBystatus("1");
            if (workmeetinginfos!=null && workmeetinginfos.size()!=0){
                for (Workmeetinginfo workmeetinginfo:workmeetinginfos){
                    Date updateDate = workmeetinginfo.getUpdateDate();
                    int status = compareDate(updateDate,new Date());
                    if (status == -1){
                        Workmeetinguser select = new Workmeetinguser();
                        select.setMeetingId(workmeetinginfo.getRoomName());
                        select.setStatus("2");
                        select.preUpdate();
                        workmeetinguserService.updateByRoomName(select);
                        workmeetinginfo.setStatus("2");
                        workmeetinginfo.preUpdate();
                        workmeetinginfoService.updateByRoomName(workmeetinginfo);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("-------------解析信息发生异常--------------");
        }
    }

    public int compareDate(Date d1,Date d2){
        long d = d1.getTime()+2*60*60*1000;
        if (d > d2.getTime()) {
            System.out.println("dt1 在dt2前");
            return 1;
        } else if (d < d2.getTime()) {
            System.out.println("dt1在dt2后");
            return -1;
        } else {//相等
            return 0;
        }
    }
}  