package com.malk.pake.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.malk.pake.service.PkMaintenanceWarningService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Notice;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilEnv;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.*;

@Service
@Slf4j
public class PkMaintenanceWarningServiceImpl implements PkMaintenanceWarningService {

    @Autowired
    private DDClient ddClient;
    @Autowired
    private DDClient_Notice ddClient_notice;
    @Autowired
    private YDClient ydClient;

    private static String FORM_UUID="FORM-NO96679107GDYGUK9SM8T42G95KA2KZOMUELL4";

    @Override
    public void warning() {
        LocalDate now=LocalDate.now();
        int weekDay=now.getDayOfWeek().getValue();
        List<Map> list= (List<Map>)ydClient.queryData(YDParam.builder().formUuid(FORM_UUID)
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_lleuoajr","工程维保")))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();
        for (int i = 0; i < list.size(); i++) {
            Map formData=UtilMap.getMap(list.get(i),"formData");
            String formInstanceId=UtilMap.getString(list.get(i),"formInstanceId");
            log.info("进度：{}/{}",i+1,list.size());
            if(formData.containsKey("dateField_lvkegbgm")&&formData.containsKey("dateField_lvkegbgp")){
                // 重新计算 维保剩余天数
                LocalDateTime startTime= UtilDateTime.getLocalDateTimeFromTimestamp(UtilMap.getLong(formData,"dateField_lvkegbgm"));
                LocalDateTime endTime=UtilDateTime.getLocalDateTimeFromTimestamp(UtilMap.getLong(formData,"dateField_lvkegbgp"));
                if(startTime.isAfter(LocalDate.now().atStartOfDay())){
                    startTime=LocalDate.now().atStartOfDay();
                }
                Period period=Period.between(startTime.toLocalDate(),endTime.toLocalDate());
                int days=period.getDays();
                String stats="";
                // 提醒人员 仰洪波[033069386520314088]  肖林[810]
                List<String> users=Arrays.asList("033069386520314088","810");
                users.addAll(UtilMap.getList(formData,"employeeField_lqq12vtb_id"));
                users.addAll(UtilMap.getList(formData,"employeeField_llemcq8c_id"));
                String projectName=UtilMap.getString(formData,"textField_llemcq7b");
                String url="https://bmogyb.aliwork.com/APP_UNSAR4O4Y7NBDUYXLIP4/formDetail/FORM-NO96679107GDYGUK9SM8T42G95KA2KZOMUELL4?formInstId="+formInstanceId;
                boolean isSend=!"关闭".equals(UtilMap.getString(formData,"radioField_lw4p0nnl"));
                if(days<0){
                    stats="已过期";
                    // 每天提醒
                    sendNotice(users,"维保已过期，请及时续约，如无需继续维保，请及时更新系统维保信息。",url,isSend,projectName);
                }else if(days>=0 && days<=90){
                    stats="3个月内到期";
                    // 周一到周五
                    if(weekDay >= 1 && weekDay <= 5){
                        sendNotice(users,"维保即将到期，请及时续约",url,isSend,projectName);
                    }
                }else if(days>=91 && days<=180){
                    stats="6个月内到期";
                    // 周一
                    if(weekDay == 1){
                        sendNotice(users,"维保即将到期，请做好维保合同续约准备",url,isSend,projectName);
                    }
                }else{
                    stats="未到期";
                    // 每年7-12月，每月1号10:00提醒1次
                    if(now.getDayOfMonth()==1&&now.getMonthValue()>=7){
                        sendNotice(users,"请提醒客户做好相关维保预算",url,isSend,projectName);
                    }
                }
                Map upMap=new HashMap();
                upMap.put("numberField_lvkegbgk",days);
                upMap.put("selectField_lvkegbgn",stats);
                ydClient.operateData(YDParam.builder().formInstId(formInstanceId).updateFormDataJson(JSONObject.toJSONString(upMap)).build(), YDConf.FORM_OPERATION.update);
            }else{
                log.info("未配置时间！");
            }
        }
    }

    private void sendNotice(List<String> users,String msg,String url,boolean isSend,String name){
        if(!isSend){
            return;
        }
        if(users==null||users.size()<1){
            log.info("提醒用户列表为空");
            return;
        }
        if(!UtilEnv.ENV_PROD.equals(UtilEnv.getActiveProfile())){
            log.info("非生产环境，消息转发到开发人员。应收到人员列表：{}",users);
            users= Arrays.asList("153620324221442254");
        }
        Map cardMap=new HashMap();
        cardMap.put("btn_json_list",Arrays.asList(UtilMap.map("title, action_url","查看详情",url)));
        cardMap.put("title","项目维保预警提醒");
        cardMap.put("markdown","### 项目维保预警提醒  \n  项目【"+name+"】  \n  "+msg);
        cardMap.put("btn_orientation",1);
        Map msgMap=new HashMap();
        msgMap.put("msgtype","action_card");
        msgMap.put("action_card",cardMap);
        ddClient_notice.sendNotification(ddClient.getAccessToken(),users,null,false,msgMap);
    }
}
