package com.malk.huagao;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.malk.huagao.entity.YdUserInput;
import com.malk.huagao.mapper.YdUserInputMapper;
import com.malk.huagao.service.HuaGaoService;
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.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Alibtrip;
import com.malk.service.dingtalk.DDClient_Attendance;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/***
 * 逸耀宜搭
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class YyYdTest {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private HuaGaoService huaGaoService;

    @Autowired
    private YdUserInputMapper ydUserInputMapper;

    @Autowired
    private YDService ydService;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Attendance ddClientAttendance;

    @Test
    public void test() {
        List<Map> list=(List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-0D560B9D8B64464C8C885FE20B7C7C95T4IA")                .pageSize(1)
        .searchFieldJson(JSONObject.toJSONString(UtilMap.map("selectField_m8nud6t3","待处理"))).build(), YDConf.FORM_QUERY.retrieve_list).getData();
        if(list==null||list.size()<1){
            return;
        }
        Map data=list.get(0);
        log.info("{}",data);
        String formInstanceId=String.valueOf(data.get("formInstanceId"));
        processing(formInstanceId);
        Map formData=UtilMap.getMap(data,"formData");
        try {
            List<String> timeList=UtilMap.getList(formData,"cascadeDateField_m8nud6sy");
            LocalDateTime startTime=UtilDateTime.getLocalDateTimeFromTimestamp(Long.parseLong(timeList.get(0)));
            LocalDateTime endTime=UtilDateTime.getLocalDateTimeFromTimestamp(Long.parseLong(timeList.get(1)));
            huaGaoService.syncKqData(startTime,endTime);
            comp(formInstanceId,"同步成功！","");
        }catch (Exception e){
            e.printStackTrace();
            comp(formInstanceId,"异常",e.getMessage());
        }
    }

    private void processing(String id){
        ydClient.operateData(YDParam.builder().formInstanceId(id)
                .updateFormDataJson(JSON.toJSONString(UtilMap.map("selectField_m8nud6t3", "处理中")))
                .build(), YDConf.FORM_OPERATION.update);
    }

    private void comp(String id,String result,String msg){
        ydClient.operateData(YDParam.builder().formInstanceId(id)
                .updateFormDataJson(JSON.toJSONString(UtilMap.map("selectField_m8nud6t3, textField_m8nud6t9, textareaField_m8nud6tb", "已完成",result,msg)))
                .build(), YDConf.FORM_OPERATION.update);
    }

    @Test
    public void test1() {
//        List<Map> attColumns = ddClientAttendance.getAttColumns(ddClient.getAccessToken());
//        System.out.println(attColumns);
    }

    @Test
    public void test2() {
        //同步员工投入历史数据
//        huaGaoService.syncUserInput(LocalDateTime.now(),LocalDateTime.now());
    }

    @Test
    public void test3() {
        LocalDateTime startTime= LocalDate.now().minusDays(4).atTime(LocalTime.MIN);
//        LocalDateTime endTime= LocalDate.now().minusDays(4).atTime(LocalTime.MIN);
        LocalDateTime endTime= LocalDate.now().atTime(LocalTime.MIN);

        huaGaoService.syncKqData(startTime,endTime);
    }

    @Test
    public void test4() {
        LambdaQueryWrapper<YdUserInput> ydUserInputLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ydUserInputLambdaQueryWrapper.eq(YdUserInput::getUserId,"16992517127785448");
        List<YdUserInput> ydUserInputs = ydUserInputMapper.selectList(ydUserInputLambdaQueryWrapper);

    }

    @Test
    public void test5(){
        String stTime="2025-10-23 00:00:00";
        String edTime="2025-10-24 00:00:00";
        List<Map> list=ydService.queryAllFormData(YDParam.builder().formUuid("FORM-5061F7AE543B429C8241EC730A6F31653NNK").build());
        for(Map map:list){
            Map formData= UtilMap.getMap(map,"formData");
            String deptId=String.valueOf(UtilMap.getList(formData,"departmentSelectField_m8e4zaju_id").get(0));
            String price=UtilMap.getString(formData,"numberField_m8e4zajw_value");
            List<String> users=ddClient_contacts.listDepartmentUserId(ddClient.getAccessToken(),Long.parseLong(deptId));
            for (String user : users) {
                List<Map> valList=ddClientAttendance.getAttColumnVal(ddClient.getAccessToken(),user, Arrays.asList("82772106","89349019","82772125"),stTime,edTime);
                if(valList!=null&&valList.size()==3){
                    Map<String,Map<String,String>> dateMap=toDateMap(valList);
                    for (String date:dateMap.keySet()) {
                        Map<String,String> dataMap=dateMap.get(date);
                        String workTime="休息".equals(dataMap.get("82772125"))?
                                dataMap.get("89349019"): NumberUtil.add(dataMap.get("89349019"),dataMap.get("82772106")).toString();

                        //查询用户详情
                        String userName = "";

                        LambdaQueryWrapper<YdUserInput> ydUserInputLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                        ydUserInputLambdaQueryWrapper2.eq(YdUserInput::getUserId,user)
                                .isNotNull(YdUserInput::getUserName);

                        Page<YdUserInput> page = new Page<>(1, 1);
                        IPage<YdUserInput> result = ydUserInputMapper.selectPage(page, ydUserInputLambdaQueryWrapper2);

                        YdUserInput ydUserInput2 = result.getRecords().isEmpty() ? null : result.getRecords().get(0);

                        if (Objects.nonNull(ydUserInput2)){
                            userName = ydUserInput2.getUserName();
                        }else {
                            DDR_New ddrNew1 = (DDR_New) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/v2/user/get", null, ddClient.initTokenParams(), UtilMap.map("userid", user), DDR_New.class);
                            Map result1 = (Map) ddrNew1.getResult();
                            userName = UtilMap.getString(result1, "name");
                        }

                        log.info("user：{},userName:{},date：{},workTime：{},price：{}",user,userName,date,workTime,price);

                        //同步到数据库
                        LambdaQueryWrapper<YdUserInput> ydUserInputLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        ydUserInputLambdaQueryWrapper.eq(YdUserInput::getUserId,user)
                                .eq(YdUserInput::getDate, date);

                        YdUserInput ydUserInput = ydUserInputMapper.selectOne(ydUserInputLambdaQueryWrapper);

                        if (Objects.nonNull(ydUserInput)){
                            ydUserInput.setUserName(userName);
                            ydUserInput.setWorkHours(workTime);
                            ydUserInput.setPrice(price);
                            ydUserInput.setTotalPrice(NumberUtil.mul(workTime,price));

                            ydUserInputMapper.update(ydUserInput,ydUserInputLambdaQueryWrapper);
                        }else {
                            try {
                                ydUserInput = new YdUserInput();
                                ydUserInput.setUserId(user);
                                ydUserInput.setUserName(userName);
                                SimpleDateFormat formatter = new SimpleDateFormat(UtilDateTime.DATE_TIME_PATTERN);
                                ydUserInput.setDate(formatter.parse(date));
                                ydUserInput.setWorkHours(workTime);
                                ydUserInput.setPrice(price);
                                ydUserInput.setTotalPrice(NumberUtil.mul(workTime,price));

                                ydUserInputMapper.insert(ydUserInput);
                            }catch (ParseException e){
                                log.info("无法解析日期字符串: {}",e.getMessage());
                            }
                        }
                    }
                }
            }
        }
    }

    private Map<String,Map<String,String>> toDateMap(List<Map> valList){
        Map<String,Map<String,String>>  result = new HashMap<>();
        for(Map map:valList){
            String columnId=UtilMap.getString(UtilMap.getMap(map,"column_vo"),"id");
            List<Map> list=UtilMap.getList(map,"column_vals");
            for(Map map1:list){
                String date=UtilMap.getString(map1,"date");
                String value=UtilMap.getString(map1,"value");
                value=columnId.equals("82772106")?NumberUtil.round(NumberUtil.div(value,"60"),2).toString():value; // 工作时长 分钟转小时
                if(result.containsKey(date)){
                    result.get(date).put(columnId,value);
                }else{
                    result.put(date,UtilMap.map(columnId,value));
                }
            }
        }
        return result;
    }
}
