package com.ruoyi.zdsz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.annotation.DynamicName;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.framework.handler.MonthTableNameHandler;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.zdsz.domain.ZEngineeringCivil;
import com.ruoyi.zdsz.domain.ZEngineeringNode;
import com.ruoyi.zdsz.domain.bo.ZEngineeringCivilBo;
import com.ruoyi.zdsz.domain.bo.ZEngineeringInfoBo;
import com.ruoyi.zdsz.domain.bo.ZEngineeringNodeBo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringCivilVo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringNodeVo;
import com.ruoyi.zdsz.mapper.ZEngineeringCivilMapper;
import com.ruoyi.zdsz.mapper.ZEngineeringNodeMapper;
import com.ruoyi.zdsz.service.IZEngineeringNodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.ruoyi.zdsz.domain.bo.ZEngineeringReviewBo;
import com.ruoyi.zdsz.domain.vo.ZEngineeringReviewVo;
import com.ruoyi.zdsz.domain.ZEngineeringReview;
import com.ruoyi.zdsz.mapper.ZEngineeringReviewMapper;
import com.ruoyi.zdsz.service.IZEngineeringReviewService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.hutool.core.date.DateUtil.format;

/**
 * 工程审核Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-27
 */
@RequiredArgsConstructor
@Service
public class ZEngineeringReviewServiceImpl implements IZEngineeringReviewService {

    private final ZEngineeringReviewMapper baseMapper;
    @Resource
    private final ZEngineeringNodeMapper zEngineeringNodeMapper;
    @Resource
    private ISysDictTypeService dictTypeService;
    @Resource
    private ZEngineeringCivilMapper zEngineeringCivilMapper;


    /**
     * 查询工程审核
     */
    @Override
    public ZEngineeringReviewVo queryById(String id){
        return baseMapper.selectVoById(id);
    }



    @Override
    @DynamicName(spel = "#bo.createTime")
    public ZEngineeringReviewBo query(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringReview::getEngInfoId, bo.getId()).orderByDesc(ZEngineeringReview::getUpdateInfoTime);
        List<ZEngineeringReview> zEngineeringReviewList=baseMapper.selectList(lqw);
        if (zEngineeringReviewList.size()==0)
        {
            return null;
        }else
        {
            ZEngineeringReviewBo zEngineeringReviewbo = BeanUtil.toBean(zEngineeringReviewList.get(0), ZEngineeringReviewBo.class);
           return zEngineeringReviewbo;
        }

    }

    /**
     * 查询工程审核列表
     */
    @Override
    public TableDataInfo<ZEngineeringReviewVo> queryPageList(ZEngineeringReviewBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZEngineeringReview> lqw = buildQueryWrapper(bo);
        Page<ZEngineeringReviewVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询工程审核列表
     */
    @Override
    public List<ZEngineeringReviewVo> queryList(ZEngineeringReviewBo bo) {
        LambdaQueryWrapper<ZEngineeringReview> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZEngineeringReview> buildQueryWrapper(ZEngineeringReviewBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getReviewTime() != null, ZEngineeringReview::getReviewTime, bo.getReviewTime());
        lqw.eq(StringUtils.isNotBlank(bo.getReviewUser()), ZEngineeringReview::getReviewUser, bo.getReviewUser());
        lqw.eq(StringUtils.isNotBlank(bo.getReviewStatus()), ZEngineeringReview::getReviewStatus, bo.getReviewStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getReviewContent()), ZEngineeringReview::getReviewContent, bo.getReviewContent());
        lqw.eq(StringUtils.isNotBlank(bo.getEngInfoId()), ZEngineeringReview::getEngInfoId, bo.getEngInfoId());
        return lqw;
    }

    /**
     * 新增工程审核
     */
    @Override
    public Boolean insertByBo(ZEngineeringReviewBo bo) {
        ZEngineeringReview add = BeanUtil.toBean(bo, ZEngineeringReview.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    public Boolean insert(ZEngineeringReviewBo bo) {
        bo.setReviewTime(new Date());
        bo.setReviewUser(String.valueOf(LoginHelper.getLoginUser().getUserId()));
        ZEngineeringReview add = BeanUtil.toBean(bo, ZEngineeringReview.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add)> 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @DynamicName(spel = "#zEngineeringCivil.createTime")
    public Boolean Civilinsert(ZEngineeringCivil zEngineeringCivil,ZEngineeringReviewBo bo) {
       ZEngineeringReview zEngineeringReview= BeanUtil.copyProperties(bo,ZEngineeringReview.class);
       zEngineeringReview.setReviewUser(LoginHelper.getLoginUser().getUserId().toString());
       zEngineeringReview.setReviewTime(new Date());
        zEngineeringReview.setUpdateTime(new Date());
//        LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
//        lqw.eq(StringUtils.isNotBlank(bo.getEngInfoId()), ZEngineeringReview::getEngInfoId, bo.getEngInfoId());
//        lqw.eq(ZEngineeringReview::getReviewStatus, '1');
        boolean flag =false;
//        if (!baseMapper.exists(lqw))
//        {
            flag=  baseMapper.insert(zEngineeringReview)> 0;
//        }
        MonthTableNameHandler.setData(new SimpleDateFormat("yyyy_MM").format(bo.getCreateTime()));
        updateCivilStatus(zEngineeringCivil);
        MonthTableNameHandler.removeData();
        return flag;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    @Transactional(rollbackFor = Exception.class)
    public Boolean Bacthinsert(ZEngineeringReview bo) {
        LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getEngInfoId()), ZEngineeringReview::getEngInfoId, bo.getEngInfoId());
           boolean flag =false;
        if (!baseMapper.exists(lqw))
            {
                flag=  baseMapper.insert(bo)> 0;
//                if(flag)
//                {
//                    LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
//                    lqw2.eq(StringUtils.isNotBlank(bo.getEngInfoId()), ZEngineeringReview::getEngInfoId, bo.getEngInfoId());
//                    lqw2.eq(ZEngineeringReview::getReviewStatus, 1);
//                   if (baseMapper.selectCount(lqw2)>=6)
//                   {
//
//                   }
//                }
            }


        return flag;
    }

    @Override
    public Boolean insertBacth(List<ZEngineeringReviewBo> bo) {
        bo.stream().forEach(item->{
            LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(item.getEngInfoId()), ZEngineeringReview::getEngInfoId, item.getEngInfoId());
                if (!baseMapper.exists(lqw))
                {
                    ZEngineeringReview add = BeanUtil.toBean(item, ZEngineeringReview.class);
                    validEntityBeforeSave(add);
                     baseMapper.insert(add);
                }


        });



        return null;
    }


    /**
     * 修改工程审核
     */
    @Override
    public Boolean updateByBo(ZEngineeringReviewBo bo) {
        ZEngineeringReview update = BeanUtil.toBean(bo, ZEngineeringReview.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZEngineeringReview entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除工程审核
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @DynamicName(spel = "#bo.createTime")
    public Boolean deleteByNodeId(ZEngineeringInfoBo bo) {
        LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getEngInfoId()), ZEngineeringReview::getEngInfoId, bo.getEngInfoId());
        return baseMapper.delete(lqw)>0;
    }
    @Override
    @DynamicName(spel = "#bo.createTime")
    public Boolean deleteByInfoId(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringReview::getEngInfoId, bo.getId()).eq(ZEngineeringReview::getReviewStatus,1);
        return baseMapper.delete(lqw)>0;
    }
    @Override
    @DynamicName(spel = "#bo.createTime")
    public Boolean deleteByNodeBoId(ZEngineeringNodeBo bo) {
        LambdaQueryWrapper<ZEngineeringReview> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getId()), ZEngineeringReview::getEngInfoId, bo.getId());
        return baseMapper.delete(lqw)>0;
    }

    @Override
    @DynamicName(spel = "#zEngineeringCivil.createTime")
    public Boolean updateCivilStatus(ZEngineeringCivil zEngineeringCivil) {
        List<SysDictData> sysDictDataList=dictTypeService.selectDictDataByType(zEngineeringCivil.getEnginType()+"_"+zEngineeringCivil.getEnginClassification());
        AtomicInteger sum= new AtomicInteger();
        sysDictDataList.forEach(item->{
            LambdaQueryWrapper<ZEngineeringNode> lqw = Wrappers.lambdaQuery();
            lqw.eq(StringUtils.isNotBlank(zEngineeringCivil.getId()), ZEngineeringNode::getCivliId, zEngineeringCivil.getId());
            lqw.eq( ZEngineeringNode::getType, item.getDictLabel());
            ZEngineeringNode zEngineeringNode= zEngineeringNodeMapper.selectOne(lqw);
            if (!ObjectUtils.isEmpty(zEngineeringNode))
            {
                LambdaQueryWrapper<ZEngineeringReview> lqw2 = Wrappers.lambdaQuery();
                lqw2.eq(StringUtils.isNotBlank(zEngineeringNode.getId()), ZEngineeringReview::getEngInfoId, zEngineeringNode.getId());
                lqw2.eq(ZEngineeringReview::getReviewStatus,1);
                if (baseMapper.selectCount(lqw2)>0)
                {
                    sum.addAndGet(1);
                }

            }

        });
        if (sum.get() ==sysDictDataList.size())
        {
            //完工
            zEngineeringCivil.setCompletionStatus("竣工");
            zEngineeringCivilMapper.updateById(zEngineeringCivil);
            return true;
        }else
        {
            //未完工
            return false;
        }

    }



}
