package com.gic.haoban.manage.service.service.notify.out;

import cn.hutool.core.date.DateUtil;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.PageHelperUtils;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.dto.notify.dto.PendingTaskDetailDTO;
import com.gic.haoban.manage.api.dto.notify.qdto.PendingListQDTO;
import com.gic.haoban.manage.api.dto.notify.qdto.PendingTaskQDTO;
import com.gic.haoban.manage.api.enums.PendingStatusFlagEnum;
import com.gic.haoban.manage.api.enums.PendingTaskTypeEnum;
import com.gic.haoban.manage.api.service.notify.PendingTaskApiService;
import com.gic.haoban.manage.service.pojo.bo.PendingTaskBO;
import com.gic.haoban.manage.service.service.notify.PendingTaskService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created 2021/12/16.
 *
 * @author hua
 */
@Service
public class PendingTaskApiServiceImpl implements PendingTaskApiService {

    @Autowired
    private PendingTaskService pendingTaskService;

    @Override
    public ServiceResponse<Boolean> addPendingTask(PendingTaskQDTO qdto) {
        //新增待办  todo 后续优化以及完善
        pendingTaskService.addOrUpdatePendingTask(EntityUtil.changeEntityByOrika(PendingTaskBO.class, qdto));
        return ServiceResponse.success(true);
    }

    @Override
    public ServiceResponse<Boolean> addPendingTaskBatch(List<PendingTaskQDTO> qdto) {
        if (CollectionUtils.isEmpty(qdto)) {
            return ServiceResponse.success(true);
        }

        List<PendingTaskBO> list = EntityUtil.changeEntityListByJSON(PendingTaskBO.class, qdto);
        pendingTaskService.addOrUpdateBatchPendingTask(list);
        return ServiceResponse.success(true);
    }
    
    @Override
    public ServiceResponse<Boolean> insertPendingTaskBatch(List<PendingTaskQDTO> qdto) {
        if (CollectionUtils.isEmpty(qdto)) {
            return ServiceResponse.success(true);
        }
        List<PendingTaskBO> list = EntityUtil.changeEntityListByJSON(PendingTaskBO.class, qdto);
        pendingTaskService.insertPendingTaskBatch(list);
        return ServiceResponse.success(true);
    }

    @Override
    public ServiceResponse<Page<PendingTaskDetailDTO>> pagePendingTask(PendingListQDTO listQDTO, BasePageInfo pageInfo) {
        Page<PendingTaskBO> pendingTask = pendingTaskService.pagePendingTask(listQDTO.getEnterpriseId(), listQDTO.getStoreId()
                , listQDTO.getClerkId(), listQDTO.getTaskType(), listQDTO.getFinishFlag()
                , listQDTO.getOverdueFlag(), pageInfo);
        //转化
        Page<PendingTaskDetailDTO> retPage = PageHelperUtils.changePageToCurrentPage(pendingTask, PendingTaskDetailDTO.class);
        if (CollectionUtils.isEmpty(retPage.getResult())) {
            return ServiceResponse.success(retPage);
        }
        buildPending(retPage.getResult());
        return ServiceResponse.success(retPage);
    }

    /**
     * 组装 防止后面变更需求
     *
     * @param list
     */
    private void buildPending(List<PendingTaskDetailDTO> list) {
        Date currentDate = new Date();
        String pattern = ".*([0-9]{6}).*";
        list.forEach(dto -> {
            String title = dto.getTitle();
            PendingTaskTypeEnum taskTypeEnum = PendingTaskTypeEnum.getByType(dto.getTaskType());
            if (null == taskTypeEnum) {
                return;
            }
            dto.setDescription(taskTypeEnum.getDescription().replace("{}", title));

            long betweenOverdueDay = dto.getOverdueTime() != null ? DateUtil.betweenDay(currentDate, dto.getOverdueTime(), true) : -1;

            long betweenInvalidDay = dto.getInvalidTime() != null ? DateUtil.betweenDay(currentDate, dto.getInvalidTime(), true) : -1;
            if (betweenInvalidDay == 1 || betweenInvalidDay == 0) {
                dto.setStatusFlag(PendingStatusFlagEnum.PRE_INVALID.getType());
            } else if (betweenOverdueDay == 0 || betweenOverdueDay == 1) {
                dto.setStatusFlag(dto.getOverdueFlag() == 1 ? PendingStatusFlagEnum.OVERDUE.getType() : PendingStatusFlagEnum.PRE_OVERDUE.getType());
            } else if (betweenOverdueDay > 1 && dto.getOverdueFlag()==1) {
                dto.setStatusFlag(PendingStatusFlagEnum.OVERDUE.getType());
            }else{
                dto.setStatusFlag(PendingStatusFlagEnum.NORMAL.getType());
            }
            dto.setTitle(taskTypeEnum.getName());

            if (dto.getTaskType() == PendingTaskTypeEnum.PERFORMANCE.getType()) {
                Pattern r = Pattern.compile(pattern);
                Matcher matcher = r.matcher(title);
                String s = matcher.find() ? matcher.group(1) : "";
                String content = s.substring(0, 4) + "-" + s.substring(4);
                dto.setExtendContent(content);
            }


        });
    }

    @Override
    public ServiceResponse<List<PendingTaskDetailDTO>> listPendingTaskToday(String enterpriseId, String storeId, String clerkId, boolean seeSelf) {
        String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        String startDate = yyyyMMdd + " 00:00:00";
        String endDate = yyyyMMdd + " 23:59:59";
        List<PendingTaskBO> todayPending = pendingTaskService.listPendingTaskByCreateTime(enterpriseId, storeId, clerkId, startDate, endDate);
        List<PendingTaskDetailDTO> retList = EntityUtil.changeEntityListByJSON(PendingTaskDetailDTO.class, todayPending);
        if (CollectionUtils.isEmpty(retList)) {
            return ServiceResponse.success(retList);
        }
        buildPending(retList);
        return ServiceResponse.success(retList);
    }

    @Override
    public ServiceResponse<Boolean> finishPending(String relationId) {
        boolean b = pendingTaskService.updateFinish(relationId);
        return ServiceResponse.success(b);
    }

    @Override
    public ServiceResponse<Boolean> changeExecutiveClerkId(String relationId, String newExeutiveClerkId) {
        PendingTaskBO pendingTaskBO = new PendingTaskBO();
        pendingTaskBO.setRelationId(relationId);
        pendingTaskBO.setClerkId(newExeutiveClerkId);
        boolean b = pendingTaskService.changeByRelationId(pendingTaskBO);
        return ServiceResponse.success(b);
    }

    @Override
    public ServiceResponse<Boolean> changeExecutiveClerkAndFinishStatus(String relationId, String newExeutiveClerkId) {
        PendingTaskBO pendingTaskBO = new PendingTaskBO();
        pendingTaskBO.setRelationId(relationId);
        pendingTaskBO.setClerkId(newExeutiveClerkId);
        pendingTaskBO.setFinishFlag(1);
        pendingTaskBO.setFinishTime(new Date());
        boolean b = pendingTaskService.changeByRelationId(pendingTaskBO);
        return ServiceResponse.success(b);
    }

    @Override
    public ServiceResponse<Boolean> deletePendingTask(List<String> relationIds) {
        boolean b = pendingTaskService.deletePendingTask(relationIds);
        return ServiceResponse.success(b);
    }

//    @Override
//    public ServiceResponse<Boolean> deletePendingTaskByRelationId(String relationId) {
//        if (StringUtils.isBlank(relationId)) {
//            return ServiceResponse.success();
//        }
//        List<String> relationIds = new ArrayList<String>();
//        relationIds.add(relationId);
//        boolean b = pendingTaskService.deletePendingTask(relationIds);
//        return ServiceResponse.success(b);
//    }

    @Override
    public ServiceResponse<Boolean> deletePendingTaskByBusinessId(String businessId) {
        pendingTaskService.deletePendingTaskByBusinessId(businessId);
        return ServiceResponse.success(true);
    }

//    @Override
//    public ServiceResponse<Boolean> updateInvalidTime(String relationId, Date endTime) {
//        PendingTaskBO pendingTaskBO = new PendingTaskBO();
//        pendingTaskBO.setRelationId(relationId);
//        pendingTaskBO.setInvalidTime(endTime);
//        boolean b = pendingTaskService.changeByRelationId(pendingTaskBO);
//        return ServiceResponse.success(b);
//    }

    @Override
    public ServiceResponse<Boolean> updateInvalidTimeByBusinessId(String businessId, Date endTime) {
        boolean b = pendingTaskService.updateInvalidTimeByBusinessId(businessId, endTime);
        return ServiceResponse.success(b);
    }
}
