package com.zhgd.xmgl.modules.basicdata.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhgd.jeecg.common.util.PageUtil;
import com.zhgd.xmgl.modules.basicdata.dto.EngineeringDeviceDto;
import com.zhgd.xmgl.modules.basicdata.entity.*;
import com.zhgd.xmgl.modules.basicdata.mapper.EngineeringMapper;
import com.zhgd.xmgl.modules.basicdata.service.*;
import com.zhgd.xmgl.modules.basicdata.statistics.EngineeringStat;
import com.zhgd.xmgl.modules.basicdata.vo.EngineeringVo;
import com.zhgd.xmgl.security.SecurityUser;
import com.zhgd.xmgl.security.SecurityUtil;
import com.zhgd.xmgl.util.ParamEnum;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Description: 项目工程表
 * @author： pds
 * @date： 2023-02-22
 * @version： V1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EngineeringServiceImpl extends ServiceImpl<EngineeringMapper, Engineering> implements IEngineeringService {

    @Autowired
    private ISystemDictDataService systemDictDataService;

    @Autowired
    private IEngineeringSingleService engineeringSingleService;

    @Autowired
    private IAnnexFileService engineeringFileService;

    @Autowired
    private IEngineeringMainService engineeringMainService;

    @Autowired
    private IEngineeringMainPersonService engineeringMainPersonService;

    @Override
    public Page<Engineering> getPageList(Page page, Wrapper<Engineering> wrapper) {
        Page<Engineering> pageList = this.page(page, wrapper);
        List<SystemDictData> engineeringTypes = systemDictDataService.getByType(ParamEnum.SysDictType.ENGINEERING_TYPE.getValue());
        List<SystemDictData> engineeringStates = systemDictDataService.getByType(ParamEnum.SysDictType.ENGINEERING_STATE.getValue());
        pageList.getRecords().stream().forEach(s -> {
            List<SystemDictData> type = engineeringTypes.stream().filter(e -> e.getDictLabel().equals(s.getEngineeringType().toString())).collect(Collectors.toList());
            List<SystemDictData> state = engineeringStates.stream().filter(e -> e.getDictLabel().equals(s.getState().toString())).collect(Collectors.toList());
            if (type.size() > 0) {
                s.setEngineeringTypeName(type.get(0).getDictValue());
            }
            if (state.size() > 0) {
                s.setStateName(state.get(0).getDictValue());
            }
        });
        return pageList;
    }

    @Override
    public Page<EngineeringDeviceDto> pageListForGov(Map<String, Object> map) {
        LambdaQueryWrapper<Engineering> wrapper = Wrappers.<Engineering>lambdaQuery();
        String engineeringName = MapUtils.getString(map, "engineeringName");
//        SecurityUser user = SecurityUtil.getUser();
//        List<String> engineeringSnList = baseMapper.getSnListByGov(user.getSn());
//        if (engineeringSnList.size() > 0) {
//            wrapper.in(Engineering::getEngineeringSn, engineeringSnList);
//        }
        if (StringUtils.isNotBlank(engineeringName)) {
            wrapper.like(Engineering::getEngineeringName, engineeringName);
        }
        Page<Engineering> page = PageUtil.getPage(map);
        return baseMapper.pageListForSuperior(page, wrapper);
    }

    @Override
    public Page<EngineeringDeviceDto> pageListForEnt(Map<String, Object> map) {
        LambdaQueryWrapper<Engineering> wrapper = Wrappers.<Engineering>lambdaQuery();
        String engineeringName = MapUtils.getString(map, "engineeringName");
//        SecurityUser user = SecurityUtil.getUser();
//        List<String> engineeringSn = baseMapper.getSnListByEnterprise(user.getSn());
//        if (engineeringSn.size() > 0) {
//            wrapper.in(Engineering::getEngineeringSn, engineeringSn);
//        }
        if (StringUtils.isNotBlank(engineeringName)) {
            wrapper.like(Engineering::getEngineeringName, engineeringName);
        }
        Page<EnvironmentDev> page = PageUtil.getPage(map);
        return baseMapper.pageListForSuperior(page, wrapper);
    }

    @Override
    public boolean updateInfo(Engineering engineering) {
        LambdaUpdateWrapper<Engineering> wrapper = Wrappers.<Engineering>lambdaUpdate();
        wrapper.set(Engineering::getExamineState, 1);
        wrapper.set(Engineering::getRejectReason, "");
        wrapper.eq(Engineering::getId, engineering.getId());
        return this.update(wrapper);
    }

    @Override
    public boolean saveInfo(EngineeringVo engineeringVo) {
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        SecurityUser user = SecurityUtil.getUser();
        engineeringVo.setState(1);
        engineeringVo.setCreateTime(new Date());
        engineeringVo.setProjectSn(user.getSn());
        engineeringVo.setEngineeringSn(uuid);
        this.save(engineeringVo);
        for (EngineeringSingle engineeringSingle : engineeringVo.getEngineeringSingles()) {
            engineeringSingle.setEngineeringSn(engineeringVo.getEngineeringSn());
        }
        engineeringSingleService.saveBatch(engineeringVo.getEngineeringSingles());
        for (AnnexFile annexFile : engineeringVo.getAnnexFiles()) {
            annexFile.setRelevanceId(engineeringVo.getEngineeringSn());
        }
        engineeringFileService.saveBatch(engineeringVo.getAnnexFiles());
        for (EngineeringMain engineeringMain : engineeringVo.getEngineeringMains()) {
            engineeringMain.setEngineeringSn(engineeringVo.getEngineeringSn());
            engineeringMainService.save(engineeringMain);
            for (EngineeringMainPerson engineeringMainPerson : engineeringMain.getEngineeringMainPersonList()) {
                engineeringMainPerson.setEngineeringMainId(engineeringMain.getId());
            }
            engineeringMainPersonService.saveBatch(engineeringMain.getEngineeringMainPersonList());
        }
        return true;
    }

    @Override
    public boolean examine(Map<String, Object> map) {
        Integer id = MapUtils.getInteger(map, "id");
        Integer examineState = MapUtils.getInteger(map, "suggest");
        Integer rejectReason = MapUtils.getInteger(map, "rejectReason");
        LambdaUpdateWrapper<Engineering> wrapper = Wrappers.<Engineering>lambdaUpdate();
        wrapper.set(Engineering::getExamineState, examineState);
        wrapper.set(Engineering::getRejectReason, rejectReason);
        wrapper.eq(Engineering::getId, id);
        // 项目报监审核通过
        if (examineState == 3) {
            wrapper.set(Engineering::getState, 1);
            // 生成五方主体账号

        }
        this.update(wrapper);
        return true;
    }

    @Override
    public List<String> getSnListByGov(String governmentSn) {
        return baseMapper.getSnListByGov(governmentSn);
    }

    @Override
    public List<String> getSnListByEnterprise(String enterpriseSn) {
        return baseMapper.getSnListByEnterprise(enterpriseSn);
    }

    @Override
    public Engineering queryDetailById(Engineering engineering) {
        List<EngineeringSingle> engineeringSingles = engineeringSingleService.list(Wrappers.<EngineeringSingle>lambdaQuery().eq(EngineeringSingle::getEngineeringSn, engineering.getEngineeringSn()));
        engineering.setEngineeringSingleList(engineeringSingles);
        return engineering;
    }

    @Override
    public Page<EngineeringStat> engineeringStat(Page page, Wrapper<Engineering> wrapper) {
        Page<EngineeringStat> engineeringStatPage = baseMapper.engineeringStat(page, wrapper);
        List<EngineeringMain> engineeringMains = engineeringMainService.getByEngineeringSn(engineeringStatPage.getRecords().stream().map(e -> e.getEngineeringSn()).collect(Collectors.toList()));
        List<SystemDictData> state = systemDictDataService.getByType(ParamEnum.SysDictType.ENGINEERING_STATE.getValue());
        List<SystemDictData> type = systemDictDataService.getByType(ParamEnum.SysDictType.ENGINEERING_TYPE.getValue());
        for (EngineeringStat stat : engineeringStatPage.getRecords()) {
            List<EngineeringMain> buildEnt = engineeringMains.stream().filter(m -> m.getEngineeringSn().equals(stat.getEngineeringSn())
             && m.getType() == 1).collect(Collectors.toList());
            stat.setBuildEnt(buildEnt.size() == 0 ? "" : buildEnt.get(0).getEnterpriseName());
            List<EngineeringMain> opEnt = engineeringMains.stream().filter(m -> m.getEngineeringSn().equals(stat.getEngineeringSn())
                    && m.getType() == 2).collect(Collectors.toList());
            stat.setOpEnt(opEnt.size() == 0 ? "" : opEnt.get(0).getEnterpriseName());
            SystemDictData stateData = state.stream().filter(m -> m.getDictLabel().equals(stat.getState().toString())).findFirst().get();
            stat.setState(stateData == null ? "" : stateData.getDictValue());
            SystemDictData styleData = type.stream().filter(m -> m.getDictLabel().equals(stat.getEngineeringType().toString())).findFirst().get();
            stat.setEngineeringType(styleData == null ? "" : styleData.getDictValue());
        }
        return engineeringStatPage;
    }
}
