package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.module.hygf.api.Enum.AcceptanceStatusEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.ArrivalStateeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.FlowStatusEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.AcceptanceDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.WorkflowResultDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.AcceptanceCheckItem;
import com.yeejoin.amos.boot.module.hygf.api.entity.BasicGridAcceptance;
import com.yeejoin.amos.boot.module.hygf.api.entity.PeasantHousehold;
import com.yeejoin.amos.boot.module.hygf.api.mapper.AcceptanceCheckItemMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.AcceptanceMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.BasicGridAcceptanceMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.PeasantHouseholdMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IAcceptanceService;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import com.yeejoin.amos.boot.module.hygf.api.util.RedisLockUtil;
import com.yeejoin.amos.component.robot.BadRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AcceptanceServiceImpl implements IAcceptanceService {

    //    @Autowired
//    WorkflowImpl workflow;
    @Autowired
    WorkFlowService workFlowService;
    @Autowired
    private AcceptanceMapper acceptanceMapper;
    @Autowired
    private BasicGridAcceptanceMapper basicGridAcceptanceMapper;
    @Autowired
    private PeasantHouseholdMapper peasantHouseholdMapper;
    @Autowired
    private AcceptanceCheckItemMapper acceptanceCheckItemMapper;
    @Autowired
    private CommonServiceImpl commonService;

    @Resource(type = RedisLockUtil.class)
    private RedisLockUtil redisLockUtil;

    /**
     * 分页查询验收列表数据
     *
     * @param page          分页对象
     * @param acceptanceDto 查询参数
     * @return 分页结果
     */
    @Override
    public Page<AcceptanceDto> page(Integer current, Integer size, AcceptanceDto acceptanceDto) {
        if (Objects.nonNull(acceptanceDto)) {

            // 处理提交日期
            if (Objects.nonNull(acceptanceDto.getAcceptanceRecDate()) && acceptanceDto.getAcceptanceRecDate() instanceof List) {
                Object acceptanceRecDate = acceptanceDto.getAcceptanceRecDate();
                List<String> dates = ((ArrayList<String>) acceptanceRecDate).stream().map(String::trim).collect(Collectors.toList());
                if (!dates.isEmpty() && StringUtils.hasText(dates.get(0)) && StringUtils.hasText(dates.get(1))) {
                    acceptanceDto.setStartSubmitDate(dates.get(0) + " 00:00:00");
                    acceptanceDto.setEndSubmitDate(dates.get(1) + " 23:59:59");
                }
            }
        }

        PageHelper.startPage(current, size);
        List<AcceptanceDto> resultPage = acceptanceMapper.page(acceptanceDto);
        PageInfo<AcceptanceDto> page = new PageInfo(resultPage);
        Page<AcceptanceDto> pagenew = new Page<AcceptanceDto>();
        pagenew.setCurrent(current);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(size);
        pagenew.setRecords(page.getList());
        return pagenew;
    }

    /**
     * 根据sequenceNbr查询验收详情（线下验收）
     *
     * @param sequenceNbr sequenceNbr
     * @return Map
     */
    @Override
    public Map<String, Object> acceptanceDetails(Long sequenceNbr) {
        Assert.notNull(sequenceNbr, "sequenceNbr不能为空");
        BasicGridAcceptance basicGridAcceptance = basicGridAcceptanceMapper.selectById(sequenceNbr);
        Assert.notNull(basicGridAcceptance, "查询验收单不存在");
        Map<String, Object> result = new HashMap<>(2);
        // 检查项信息
        AcceptanceCheckItem acceptanceCheckItem = acceptanceCheckItemMapper.selectOne(
                Wrappers.<AcceptanceCheckItem>lambdaQuery()
                        .eq(AcceptanceCheckItem::getPeasantHouseholdId, basicGridAcceptance.getPeasantHouseholdId())
                        .orderByDesc(AcceptanceCheckItem::getRecDate)
                        .last("limit 1")
        );
        result.put("checkItem", acceptanceCheckItem);
        return result;
    }

    @Override
    public AcceptanceCheckItem saveEntity(AcceptanceCheckItem item, Long sequenceNbr) {
        BasicGridAcceptance acceptance = basicGridAcceptanceMapper.selectById(sequenceNbr);
        Assert.notNull(acceptance, "未查询到相关电站信息！");
        item.setWorkOrderId(acceptance.getWorkOrderId());
        item.setWorkOrderPowerStationId(acceptance.getWorkOrderPowerStationId());
        item.setPeasantHouseholdId(acceptance.getPeasantHouseholdId());
        acceptanceCheckItemMapper.insert(item);
        return Optional.ofNullable(item).orElse(new AcceptanceCheckItem());
    }

    @Override
    @Transactional
    public void checkAccept(Long basicGridAcceptanceId, String userId) {
        String lockName = String.format("LockName:checkAccept:%s", basicGridAcceptanceId);
        Boolean isLocked = redisLockUtil.tryLock(lockName, lockName, 10, 1);
        if (BooleanUtils.isNotTrue(isLocked)) {
            throw new BadRequest("其他用户正在操作，请刷新后再试！");
        }
        try {
            BasicGridAcceptance basicGridAcceptanc = basicGridAcceptanceMapper.selectById(basicGridAcceptanceId);
            if (AcceptanceStatusEnum.待投融验收.getCode().equals(basicGridAcceptanc.getAcceptanceStatus())) {
                throw new BadRequest("验收状态已变更为待投融验收，请稍后再试！");
            }
            basicGridAcceptanc.setAcceptanceStatus(AcceptanceStatusEnum.待投融验收.getCode());
            basicGridAcceptanc.setAcceptanceRecDate(new Date());
            //执行工作流
//        StandardDto standardDto=new StandardDto();
//        standardDto.setTaskId(basicGridAcceptanc.getNextTaskId());
//        workflow.standard(basicGridAcceptanc,standardDto,userId);
            //执行工作流
            TaskResultDTO taskResultDTO = new TaskResultDTO();
            taskResultDTO.setTaskId(basicGridAcceptanc.getNextTaskId());
            ProcessTaskDTO processTaskDTO = workFlowService.standard(basicGridAcceptanc, taskResultDTO, userId);
            //发起待办
//            WorkflowResultDto workflowResultDto = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO)).get(0);
//            workflowResultDto.setInstanceId(basicGridAcceptanc.getInstanceId());
//            commonService.updateTaskModelAndAddTask(basicGridAcceptanc, workflowResultDto,BusinessTypeEnum.HYGF_BWYS);
            basicGridAcceptanceMapper.updateById(basicGridAcceptanc);

            //线上验收
            LambdaUpdateWrapper<PeasantHousehold> up =new LambdaUpdateWrapper<>();
            up.set(PeasantHousehold::getConstructionState, ArrivalStateeEnum.线上验收.getCode());
            long idsk = basicGridAcceptanc.getPeasantHouseholdId();
            up.eq(PeasantHousehold::getSequenceNbr, idsk);
            peasantHouseholdMapper.update(null,up);
        } finally {
            redisLockUtil.releaseLock(lockName);
        }
    }

}
