package com.malk.pake.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.malk.pake.service.PkWorkingHoursService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Notice;
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.LocalDate;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PkWorkingHoursServiceImpl implements PkWorkingHoursService {

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

    private static String FORM_UUID="FORM-F50C31C6F5F34955870B2454275C7846TNPF";
    private static String NOTICE_MONTH="请及时填写上月工时!";
    private static String NOTICE_DAY="请及时填写今日工时!";
    private static String NOTICE_PEOPLE="请及时上传工时填写人员实际出勤时长!";

    @Override
    public void fillInReminderMonth() {
        Long lastMonth= LocalDate.now().minusMonths(1).withDayOfMonth(1).atStartOfDay().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        int i=0;
        long total;
        do {
            i++;
            DDR_New ddr_new = ydClient.queryData(YDParam.builder().formUuid(FORM_UUID).pageNumber(i)
                            .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_lvyvp4ab", "按月"))).build(),
                    YDConf.FORM_QUERY.retrieve_list);
            List<Map> list =(List<Map>) ddr_new.getData();
            total=ddr_new.getTotalCount();
            log.info("数量，{}",list.size());
            for (Map map:list){
                Map formData=UtilMap.getMap(map,"formData");
                log.info("formData:{}",formData);
                String url=UtilMap.getString(formData,"textField_lvyvp4at");
                List<String> users=UtilMap.getList(formData,"employeeField_lvyvp4a9_id");
                // 判断是否填写
                List<Map> list2 =(List<Map>) ydClient.queryData(YDParam.builder().formUuid(url.substring(url.indexOf("FORM-"),url.indexOf("?")))
                                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("employeeField_ls2x7t46, dateField_ls2x7t40", users.get(0),Arrays.asList(lastMonth,lastMonth)))).build(),
                        YDConf.FORM_QUERY.retrieve_list).getData();
                if(list2.size()>0){
                    log.info("{}已填写，跳过",formData.get("employeeField_lvyvp4a9"));
                    continue;
                }
                sendNotice(users,NOTICE_MONTH,url);
            }
        }while (i*100<total);
    }

    @Override
    public void fillInReminderDay() {
        Long now= LocalDate.now().atStartOfDay().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        int i=0;
        long total;
        do {
            i++;
            DDR_New ddr_new = ydClient.queryData(YDParam.builder().formUuid(FORM_UUID).pageNumber(i)
                            .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_lvyvp4ab", "按天"))).build(),
                    YDConf.FORM_QUERY.retrieve_list);
            List<Map> list =(List<Map>) ddr_new.getData();
            total=ddr_new.getTotalCount();
            log.info("数量，{}",list.size());
            for (Map map:list){
                Map formData=UtilMap.getMap(map,"formData");
                log.info("formData:{}",formData);
                String url=UtilMap.getString(formData,"textField_lvyvp4at");
                List<String> users=UtilMap.getList(formData,"employeeField_lvyvp4a9_id");
                // 判断是否填写
                List<Map> list2 =(List<Map>) ydClient.queryData(YDParam.builder().formUuid(url.substring(url.indexOf("FORM-"),url.indexOf("?")))
                                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("employeeField_lrhjd0eq, dateField_lrhl6dm1", users.get(0),Arrays.asList(now,now)))).build(),
                        YDConf.FORM_QUERY.retrieve_list).getData();
                if(list2.size()>0){
                    log.info("{}已填写，跳过",formData.get("employeeField_lvyvp4a9"));
                    continue;
                }
                sendNotice(users,NOTICE_DAY,url);
            }
        }while (i*100<total);
    }

    @Override
    public void fillInReminderPeople() {
        Long lastMonth= LocalDate.now().minusMonths(1).withDayOfMonth(1).atStartOfDay().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        List<Map> list2 =(List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-275444E476654714A0B8E5AC8EDC2735LDZK")
                        .searchFieldJson(JSONObject.toJSONString(UtilMap.map("dateField_ls72x2hs", Arrays.asList(lastMonth,lastMonth)))).build(),
                YDConf.FORM_QUERY.retrieve_list).getData();
        log.info("数量，{}",list2.size());
        if(list2.size()>0){
            log.info("已填写，跳过");
            return;
        }
        // 指定接收人员 陈柳润[17101209603456094]
        sendNotice(Arrays.asList("17101209603456094"),NOTICE_PEOPLE,"https://bmogyb.aliwork.com/APP_UNSAR4O4Y7NBDUYXLIP4/submission/FORM-275444E476654714A0B8E5AC8EDC2735LDZK?corpid=ding2ef56b69014fbfec35c2f4657eb6378f");
    }


    private void sendNotice(List<String> users,String msg,String url){
        if(!UtilEnv.ENV_PROD.equals(UtilEnv.getActiveProfile())){
            log.info("非生产环境，消息转发到开发人员。应收到人员列表：{}",users);
            users=Arrays.asList("153620324221442254");
        }
        Map linkMap=new HashMap();
        linkMap.put("messageUrl",url);
        linkMap.put("picUrl","@lALOACZwe2Rk");
        linkMap.put("title","工时填写提醒");
        linkMap.put("text",msg);
        Map msgMap=new HashMap();
        msgMap.put("msgtype","link");
        msgMap.put("link",linkMap);
        ddClient_notice.sendNotification(ddClient.getAccessToken(),users,null,false,msgMap);
    }
}
