package com.xisc.pm.infra.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.hzero.boot.scheduler.infra.annotation.JobHandler;
import org.hzero.boot.scheduler.infra.enums.ReturnT;
import org.hzero.boot.scheduler.infra.handler.IJobHandler;
import org.hzero.boot.scheduler.infra.tool.SchedulerTool;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xisc.pm.app.service.autoboard.config.CalcLog;
import com.xisc.pm.domain.entity.PmRequestInfo;
import com.xisc.pm.domain.repository.PmAutoPdContractRepository;
import com.xisc.pm.domain.repository.PmAutoPdPositionRepository;
import com.xisc.pm.domain.repository.PmAutoPdResultRepository;
import com.xisc.pm.domain.repository.PmRequestInfoRepository;
import com.xisc.pm.domain.repository.PmRuntimeContractRepository;
import com.xisc.pm.infra.enums.AutoPdRequestStatus;

@JobHandler("autoPdClearJobHandler")
public class AutoPdExecJobHandler implements IJobHandler {

    @Autowired
    private PmRequestInfoRepository pmRequestInfoRepository;

    @Autowired
    private PmAutoPdPositionRepository pmAutoPdPositionRepository;

    @Autowired
    private PmAutoPdContractRepository pmAutoPdContractRepository;

    @Autowired
    private PmRuntimeContractRepository pmRuntimeContractRepository;

    @Autowired
    private PmAutoPdResultRepository pmAutoPdResultRepository;

    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnT execute(Map<String, String> map, SchedulerTool tool) {
        int day = 7;
        String requestIdStrs = null ;
        if (map.containsKey("day")) {
            day = Integer.parseInt(map.get("day"));
        }
        if (map.containsKey("requestIds")) {
            requestIdStrs = map.get("requestIds");
        }
        Date date = DateUtils.addDays(new Date(), day * -1);
        List<String> requestStatus = new ArrayList<>();
        requestStatus.add(AutoPdRequestStatus.EXECUTION.name());
        requestStatus.add(AutoPdRequestStatus.UNPUBLISHED.name());
        requestStatus.add(AutoPdRequestStatus.EXEC_ERROR.name());
        List<PmRequestInfo> pmRequestInfos = pmRequestInfoRepository
                .selectByCondition(Condition.builder(PmRequestInfo.class)
                        .andWhere(Sqls.custom().andIn(PmRequestInfo.FIELD_REQUEST_STTUS, requestStatus)
                                .andLessThanOrEqualTo(PmRequestInfo.FIELD_EXEC_START_DATE, date))
                        .build());
        List<Long> requestIds = new ArrayList<>();
        List<String> requestCodeList = new ArrayList<>();
        if(StringUtils.isNotBlank(requestIdStrs)) {
            for (String requesrId : requestIdStrs.split(",")) {
                requestIds.add(Long.valueOf(requesrId));
            }
        }
        if (pmRequestInfos == null || pmRequestInfos.isEmpty()) {
            return ReturnT.SUCCESS;
        } else {
            for (PmRequestInfo pmRequestInfo : pmRequestInfos) {
                requestIds.add(pmRequestInfo.getRequestId());
                requestCodeList.add(pmRequestInfo.getRequestCode());
            }
        }
        
        tool.info("开始删除小板位置表");
        int posCount = pmAutoPdPositionRepository.deleteByRequestId(requestIds);
        tool.info("删除小板位置表：" + posCount);
        
        tool.info("开始删除组板结果表");
        int resultCount = pmAutoPdResultRepository.deleteByRequestId(requestIds);
        tool.info("删除组板结果表:" + resultCount);
        
        tool.info("开始删除组板合同信息表");
        int contractCount = pmAutoPdContractRepository.deleteByRequestId(requestIds);
        tool.info("删除合同信息表" + contractCount);

        tool.info("开始删除合同范围表");
        int runtimeContractCount = pmRuntimeContractRepository.deleteByRequestId(requestIds);
        tool.info("删除合同范围表" + runtimeContractCount);

        pmRequestInfoRepository.batchDelete(pmRequestInfos);
        try {
            Query query = new Query();
            Criteria criteriaDefinition = Criteria.where("requestId").in(requestIds);
            query.addCriteria(criteriaDefinition);
            mongoTemplate.remove(query, CalcLog.COLLECTION_AUTO_PD_LOG);
            tool.info("删除请求信息成功：" + objectMapper.writeValueAsString(requestCodeList));
        } catch (JsonProcessingException e) {
            tool.error(e.getMessage());
        }
        return ReturnT.SUCCESS;
    }

}