package com.malk.mc.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.mc.entity.PocTbTask;
import com.malk.mc.entity.PocTbWeekly;
import com.malk.mc.entity.PocTbWorkTime;
import com.malk.mc.mapper.PocTbTaskMapper;
import com.malk.mc.mapper.PocTbUserMapper;
import com.malk.mc.mapper.PocTbWeeklyMapper;
import com.malk.mc.mapper.PocTbWorkTimeMapper;
import com.malk.mc.service.McPocTbService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.teambition.TBClient;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
public class McPocTbServiceImpl implements McPocTbService {

    @Autowired
    private TBClient tbClient;
    @Autowired
    private PocTbWorkTimeMapper pocTbWorkTimeMapper;
    @Autowired
    private PocTbTaskMapper pocTbTaskMapper;
    @Autowired
    private PocTbUserMapper pocTbUserMapper;
    @Autowired
    private YDClient ydClient;
    @Autowired
    private PocTbWeeklyMapper pocTbWeeklyMapper;

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
    private SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void saveWorkTimes(String taskId, String userId, List<String> ids) {
        MDC.put("MDC_KEY_PID","1000");
        Map task=tbClient.queryTaskDetail(taskId,"","").get(0);
        String projectId=UtilMap.getString(task,"projectId");
        if(!projectId.equals("66124f3f6f4d77e0259b40d5")){
            return;
        }
        PocTbTask pocTbTask=pocTbTaskMapper.selectById(taskId);
        if(pocTbTask==null){
            pocTbTask=new PocTbTask();
            pocTbTask.setTaskId(taskId);
            pocTbTask.setTaskName(UtilMap.getString(task,"content"));
            pocTbTaskMapper.insert(pocTbTask);
        }
        String ddUserId = pocTbUserMapper.selectById(userId).getDdUserId();
        for(String id:ids){
            Map map=tbClient.queryWorktime(id);
            PocTbWorkTime pocTbWorkTime=new PocTbWorkTime();
            pocTbWorkTime.setId(id);
            pocTbWorkTime.setUserId(userId);
            pocTbWorkTime.setTaskId(taskId);
            pocTbWorkTime.setDescription(UtilMap.getString(map,"description"));
            pocTbWorkTime.setWorkTime(UtilMap.getString(map,"worktime"));
            pocTbWorkTime.setCreatedAt(timeFormat(UtilMap.getString(map,"createdAt")));
            String workData=timeFormat(UtilMap.getString(map,"date"));
            pocTbWorkTime.setWorkData(workData.split(" ")[0]);
            pocTbWorkTimeMapper.insert(pocTbWorkTime);
            Map data=new HashMap();
            data.put("employeeField_lxk6f7i2", Arrays.asList(ddUserId));//
            data.put("dateField_lxk6f7i3", UtilDateTime.getLocalDateTimeTimeStamp(UtilDateTime.parseLocalDateTime(workData)));//
            data.put("textField_lxk6f7i5",pocTbTask.getTaskName());//
            data.put("numberField_lxk6f7i4", NumberUtil.div(pocTbWorkTime.getWorkTime(),"3600000"));//
            data.put("textareaField_lxk6f7i6",pocTbWorkTime.getDescription());//
            if (Strings.isNotBlank(MDC.get("MDC_KEY_PID"))){
                log.info(MDC.get("MDC_KEY_PID"));
            }
            ydClient.operateData(YDParam.builder().formUuid("FORM-EDFDBFBE08F149AAB4FD7A9BA00FAFD8DQER").formDataJson(JSONObject.toJSONString(data)).build(), YDConf.FORM_OPERATION.create);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWeekly(String activityId, Map content, String creatorId, String taskId, String createDate, String updateDate) {
        MDC.put("MDC_KEY_PID","1000");
        Map task=tbClient.queryTaskDetail(taskId,"","").get(0);
        String projectId=UtilMap.getString(task,"projectId");
        if(!projectId.equals("66124f3f6f4d77e0259b40d5")){
            return;
        }
        //若任务不存在则创建
        PocTbTask pocTbTask=pocTbTaskMapper.selectById(taskId);
        if(pocTbTask==null){
            pocTbTask=new PocTbTask();
            pocTbTask.setTaskId(taskId);
            pocTbTask.setTaskName(UtilMap.getString(task,"content"));
            pocTbTaskMapper.insert(pocTbTask);
        }
        String ddUserId = pocTbUserMapper.selectById(creatorId).getDdUserId();
        //创建周报
        PocTbWeekly pocTbWeekly = pocTbWeeklyMapper.selectById(activityId);
        if (Objects.isNull(pocTbWeekly)){
            pocTbWeekly = new PocTbWeekly();
            pocTbWeekly.setId(activityId);
            pocTbWeekly.setContent(String.valueOf(content.get("text")));
            pocTbWeekly.setTaskId(taskId);
            pocTbWeekly.setCreatorId(creatorId);
            pocTbWeekly.setCreateDate(createDate);
            pocTbWeekly.setUpdateDate(updateDate);
            pocTbWeeklyMapper.insert(pocTbWeekly);

            //在宜搭周报表中新增数据
            Map data=new HashMap();
            data.put("employeeField_lxu7g60o", Arrays.asList(ddUserId));//员工
            data.put("textField_lxu7g60r", pocTbTask.getTaskName());//项目名称
            data.put("textareaField_lxu7g60p",String.valueOf(content.get("text")));//周报内容
            data.put("dateField_lxu7g60q",DateUtil.parse(createDate));//周报创建日期

            if (Strings.isNotBlank(MDC.get("MDC_KEY_PID"))){
                log.info(MDC.get("MDC_KEY_PID"));
            }

            ydClient.operateData(YDParam.builder().formUuid("FORM-4EFCFB6F0E3D4187BCDEBEEA60F4F555RTIK").formDataJson(JSONObject.toJSONString(data)).build(), YDConf.FORM_OPERATION.create);
        }


    }

    private String timeFormat(String startDate){
        String result = "";
        Date rwStateTime = null;
        if (startDate == null) {
            System.out.println("该项目没有获取到任务开始时间！");
        } else {
            startDate = startDate.replace("Z", " UTC");
            try {
                rwStateTime = format.parse(startDate);
                result = defaultFormat.format(rwStateTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
