package com.galaxis.manatee.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.galaxis.manatee.constant.ChuanYunConstant;
import com.galaxis.manatee.constant.DingTalkConstant;
import com.galaxis.manatee.dao.DingTalkProcessInstanceDao;
import com.galaxis.manatee.dao.ProjectDao;
import com.galaxis.manatee.entity.chuanyun.ChuanyunFindAllResponse;
import com.galaxis.manatee.entity.chuanyun.ChuanyunSaveAllResponse;
import com.galaxis.manatee.entity.chuanyun.Filter;
import com.galaxis.manatee.entity.chuanyun.data.object.ProjectDO;
import com.galaxis.manatee.entity.chuanyun.bo.MaterialResendBO;
import com.galaxis.manatee.entity.ding.DingTalkProcessInstance;
import com.galaxis.manatee.manager.ChuanYunManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zcj
 * @version 0.1
 * @date 2020/2/13 11:53 上午
 */
@Service
@Slf4j
public class ChuanyunScheduledTask {

    private ChuanYunManager chuanYunManager;
    private ProjectDao projectDao;
    private DingTalkProcessInstanceDao dingTalkProcessInstanceDao;

    public ChuanyunScheduledTask(ChuanYunManager chuanYunManager, ProjectDao projectDao, DingTalkProcessInstanceDao dingTalkProcessInstanceDao) {
        this.chuanYunManager = chuanYunManager;
        this.projectDao = projectDao;
        this.dingTalkProcessInstanceDao = dingTalkProcessInstanceDao;
    }


    /**
     * 定时将氚云中的数据保存到
     */
    @Scheduled(fixedDelay = 300000L)
    private void getProcessInstanceFromChuanyun(){
        //获取项目数据
        getProjectInformationFromChuanyun();
    }

    /**
     * 定时将钉钉同步的审批记录同步到氚云当中
     */
    @Scheduled(fixedDelay = 600000L)
    private void putProcessInstanceToChuanyun(){
        //同步物料补发数据
        putMaterialResendInstance();
    }

    /**
     * 将物料补发数据同步到氚云
     * 预计2020年4月份之后逐步将各个部门物料补发数据迁移到氚云进行审批，这个功能逐步废弃
     */
    private void putMaterialResendInstance(){
        int currentPage=0;
        int totalPage=Integer.MAX_VALUE;

        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        while (currentPage<totalPage){
            List<String> strings=new ArrayList<>();
            PageRequest pageRequest=PageRequest.of(currentPage,20);
            DingTalkProcessInstance dingTalkProcessInstance=new DingTalkProcessInstance();
            dingTalkProcessInstance.setProcessInstanceId(DingTalkConstant.PROCESS_CODE_MATERIAL_RESEND);
            dingTalkProcessInstance.setUpdatedInChuanyun(false);
            Page<DingTalkProcessInstance> pageList=dingTalkProcessInstanceDao.findAll(Example.of(dingTalkProcessInstance),pageRequest);
            if(totalPage==Integer.MAX_VALUE){
                totalPage=pageList.getTotalPages();
            }

            pageList.getContent().forEach(content->{
                if(content.getProcessInstance()==null){
                    log.info("观察异常内容"+content+"");
                }else {
                    if (content.getProcessInstanceId().equals(DingTalkConstant.PROCESS_CODE_MATERIAL_RESEND)){
                        MaterialResendBO materialResendBO = MaterialResendBO.fromDingTak(content.getProcessInstance());
                        try {
                            strings.add(objectMapper.writeValueAsString(materialResendBO));
                        } catch (JsonProcessingException e) {
                            log.error(e.getMessage());
                        }
                    }
                }
            });
            ChuanyunSaveAllResponse chuanyunSaveAllResponse= chuanYunManager.saveAll(MaterialResendBO.SCHEMA_CODE,strings,true);
            log.info("氚云保存物料补发数据结果的错误信息为 "+chuanyunSaveAllResponse.getErrorMessage());
            log.info(chuanyunSaveAllResponse+"");
            pageList.getContent().forEach(content->content.setUpdatedInChuanyun(true));
            log.info("开始更新钉钉审批数据上传状态");
            log.info(dingTalkProcessInstanceDao.saveAll(pageList.getContent())+"");
            log.info("已更新上传状态的钉钉审批数据");
            currentPage++;
        }
    }

    /**
     * 定时更新项目信息
     */
    private void getProjectInformationFromChuanyun(){
        int start=0;
        long totalCount=0;
        boolean flag=true;
        while (flag){
            try {
                //从氚云查询数据
                Filter filter=Filter.instance(start,start+20,true);
                ChuanyunFindAllResponse<ProjectDO> chuanyunFindAllResponse=chuanYunManager.findAll(ProjectDO.SCHEMA_CODE,filter);
                if(chuanyunFindAllResponse.getReturnData().getTotalCount()>=start+20){
                    start+=20;
                }else{
                    flag=false;
                }
                //转化为POJO
                ObjectMapper objectMapper=new ObjectMapper();
                List<ProjectDO> result=objectMapper.convertValue(chuanyunFindAllResponse.getReturnData().getBizObjectArray(), new TypeReference<>(){});
                //更新缓存中的项目映射表
                result.forEach(projectBO -> ChuanYunConstant.PROJECT_CODE.put(projectBO.getProjectCode(),projectBO.getObjectId()));
                totalCount=chuanyunFindAllResponse.getReturnData().getTotalCount();
                //保存
                projectDao.saveAll(result);
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
        log.info("项目信息保存保存"+totalCount+"项目映射更新完成");
    }

}
