package cn.iocoder.yudao.module.tickets.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.project.entity.RepairWares;
import cn.iocoder.yudao.module.project.service.RepairWaresService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.tickets.entity.DlTwItem;
import cn.iocoder.yudao.module.tickets.mapper.DlTwItemMapper;
import cn.iocoder.yudao.module.tickets.service.DlTicketWaresService;
import cn.iocoder.yudao.module.tickets.service.DlTwItemService;
import cn.iocoder.yudao.module.tickets.vo.AddTwiVO;
import cn.iocoder.yudao.module.tickets.vo.AppWaresGroupVO;
import cn.iocoder.yudao.module.tickets.vo.DlTwItemReqVO;
import cn.iocoder.yudao.module.tickets.vo.DlTwItemRespVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.common.RepairCons.DICT_REPAIR_UNIT;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;

/**
 * 针对表【dl_tw_item(工单配件申请/退回子表)】的数据库操作Service实现
 *
 * @author 小李
 * @date 11:57 2024/10/15
**/
@Service
public class DlTwItemServiceImpl extends ServiceImpl<DlTwItemMapper, DlTwItem>
    implements DlTwItemService {

    @Resource
    private DlTwItemMapper dlTwItemMapper;
    @Resource
    private RepairWaresService repairWaresService;
    @Resource
    private DictDataApi dictDataApi;
    @Resource
    @Lazy
    private RepairWaresService waresService;
    @Resource
    @Lazy
    private DlTicketWaresService ticketWaresService;

    /**
     * 根据主表查看全部
     *
     * @author 小李
     * @date 12:25 2024/10/15
     * @param reqVO 请求对象
     **/
    @Override
    public List<DlTwItemRespVO> listTwItem(DlTwItemReqVO reqVO){
        // 查记录
        List<DlTwItem> dlTwItems = baseMapper.listTwItem(reqVO);
        //所有有配件的分类
        List<Map<String,String>> typeMapList = waresService.getAllTypeList();
        Map<String,String> typeMap = new HashMap<>();
        for(Map<String,String> map:typeMapList){
            typeMap.put(map.get("id"),map.get("name"));
        }
        // 单位字典
        List<DictDataRespDTO> recordTypeList = dictDataApi.getDictDataList(DICT_REPAIR_UNIT);
        Map<String,String> unitMap = recordTypeList.stream().collect(Collectors.toMap(DictDataRespDTO::getValue,DictDataRespDTO::getLabel));
        // 查配件详情
        List<String> ids = dlTwItems.stream().map(DlTwItem::getWaresId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(ids)){
            List<RepairWares> repairWares = repairWaresService.listByIds(ids);
            return dlTwItems.stream().map(item -> {
                DlTwItemRespVO bean = BeanUtil.toBean(item, DlTwItemRespVO.class);
                repairWares.stream()
                        .filter(i -> i.getId().equals(bean.getWaresId()))
                        .findFirst()
                        .ifPresent(bean::setWares);
                bean.setTypeName(typeMap.get(bean.getWares().getType()));
                bean.getWares().setUnit(unitMap.get(bean.getWares().getUnit()));
                return bean;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 给配件申请表子表添加数据
     *
     * @author 小李
     * @date 17:47 2024/11/13
     * @param addTwiVO 对象
     **/
    @Override
    public void addTwi(AddTwiVO addTwiVO){
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        // 构建子表数据
        if (CollectionUtil.isEmpty(addTwiVO.getItems())){
            throw exception0(500, "请选择配件");
        }
        if(addTwiVO.getIfHouseAdd()){
            //仓管添加
            List<DlTwItem> twItems = addTwiVO.getItems().stream().map(item -> {
                DlTwItem twItem = new DlTwItem();
                twItem.setTwId(addTwiVO.getId());
                twItem.setWaresId(item.getId());
                twItem.setWaresName(item.getName());
                twItem.setWaresCount(item.getCount());
                twItem.setAddUserId(loginUser.getId());
                twItem.setAddUserName(loginUser.getInfo().get("nickname"));
                twItem.setIfHouseAdd(true);
                twItem.setWaresAlreadyCount(0);
                twItem.setWaresStatus("1");
                twItem.setHandleId(loginUser.getId());
                twItem.setHandleName(loginUser.getInfo().get("nickname"));
                twItem.setRemark(item.getRemark());
                return twItem;
            }).collect(Collectors.toList());
            // 新增
            baseMapper.insert(twItems);
        }else{
            //服务顾问添加
            // 查出该配件申请单已有的所有配件，这里只取没有审核过（通过、驳回的不要，同一个配件如果已经审核过了又添加，还是算新的）
            List<DlTwItem> oldData = baseMapper.selectList(new LambdaQueryWrapper<DlTwItem>().and(i -> {
                i.in(DlTwItem::getTwId, addTwiVO.getId())
                        .eq(DlTwItem::getWaresStatus, "");
            }));
            if (CollectionUtil.isNotEmpty(oldData)){
                // 取配件ID
                List<String> ids = oldData.stream().map(DlTwItem::getWaresId).collect(Collectors.toList());
                // 过滤添加的
                List<AddTwiVO.AddTwiVoItem> add = addTwiVO.getItems().stream().filter(item -> !ids.contains(item.getId())).collect(Collectors.toList());
                // 过滤存在的
                List<AddTwiVO.AddTwiVoItem> update = addTwiVO.getItems().stream().filter(item -> ids.contains(item.getId())).collect(Collectors.toList());
                // 添加
                if (CollectionUtil.isNotEmpty(add)){
                    List<DlTwItem> twItems = add.stream().map(item -> {
                        DlTwItem twItem = new DlTwItem();
                        twItem.setTwId(addTwiVO.getId());
                        twItem.setWaresId(item.getId());
                        twItem.setWaresName(item.getName());
                        twItem.setWaresCount(item.getCount());
                        twItem.setAddUserId(loginUser.getId());
                        twItem.setAddUserName(loginUser.getInfo().get("nickname"));
                        twItem.setIfHouseAdd(false);
                        twItem.setWaresAlreadyCount(0);
                        twItem.setWaresStatus("");
                        twItem.setRemark(item.getRemark());
                        return twItem;
                    }).collect(Collectors.toList());
                    // 新增
                    baseMapper.insert(twItems);
                }
                // 更新
                if (CollectionUtil.isNotEmpty(update)){
                    List<DlTwItem> twItems = update.stream().map(item -> {
                        DlTwItem twItem = oldData.stream().filter(i -> i.getWaresId().equals(item.getId())).findFirst().orElse(null);
                        // 只更新数量，其他不变
                        if (twItem != null) {
                            twItem.setWaresCount(twItem.getWaresCount() + item.getCount());
                        }
                        return twItem;
                    }).collect(Collectors.toList());
                    baseMapper.updateById(twItems);
                }
            }else {
                List<DlTwItem> twItems = addTwiVO.getItems().stream().map(item -> {
                    DlTwItem twItem = new DlTwItem();
                    twItem.setTwId(addTwiVO.getId());
                    twItem.setWaresId(item.getId());
                    twItem.setWaresName(item.getName());
                    twItem.setWaresCount(item.getCount());
                    twItem.setAddUserId(loginUser.getId());
                    twItem.setAddUserName(loginUser.getInfo().get("nickname"));
                    twItem.setIfHouseAdd(false);
                    twItem.setWaresAlreadyCount(0);
                    twItem.setWaresStatus("");
                    twItem.setRemark(item.getRemark());
                    return twItem;
                }).collect(Collectors.toList());
                // 新增
                baseMapper.insert(twItems);
            }
        }
    }

    /**
     * APP查询配件申请单列表-按配件分类进行分组
     *
     * @param reqVO
     * @return java.lang.Object
     * @author vinjor-M
     * @date 14:03 2024/11/20
     **/
    @Override
    public Object listApp(DlTwItemReqVO reqVO) {
        // 查记录
        List<DlTwItemRespVO> dlTwItemRespVOList = dlTwItemMapper.listTwItemApp(reqVO);
        List<AppWaresGroupVO> waresGroupList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(dlTwItemRespVOList)) {
            //先过滤出itenTypeId为null或空，或者itemTypeName为null或空的，为单独一个组
            List<DlTwItemRespVO> nullList = dlTwItemRespVOList.stream().filter(item-> StringUtils.isEmpty(item.getTypeId()) || StringUtils.isEmpty(item.getTypeName())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(nullList)) {
                AppWaresGroupVO waresGroupVO = new AppWaresGroupVO();
                //审核通过数量、不通过数量、待审核数量
                final int[] numArray= {0,0,0};
                waresGroupVO.setTwItemList(nullList.stream().peek(item->{
                    if(StringUtils.isEmpty(item.getWaresStatus())){
                        //待审核
                        numArray[2]++;
                        item.setSelected(false);
                    }else{
                        if("1".equals(item.getWaresStatus())){
                            //通过
                            numArray[0]++;
                        }else{
                            //不通过
                            numArray[1]++;
                        }
                        item.setApprovalTime(item.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    }
                }).collect(Collectors.toList()));
                waresGroupVO.setGroupName("未知分组");
                waresGroupVO.setTypeNums(nullList.size());
                waresGroupVO.setNums(nullList.stream().mapToInt(DlTwItem::getWaresCount).sum());
                waresGroupVO.setAllowNum(numArray[0]);
                waresGroupVO.setNoNum(numArray[1]);
                waresGroupVO.setWaitingNum(numArray[2]);
                waresGroupList.add(waresGroupVO);
            }
            //过滤出有分类的进行分组
            Map<String,List<DlTwItemRespVO>> groupListMap = dlTwItemRespVOList.stream().filter(item->StringUtils.isNotEmpty(item.getTypeId()) && StringUtils.isNotEmpty(item.getTypeName())).collect(Collectors.groupingBy(DlTwItemRespVO::getTypeId));
            for (String key:groupListMap.keySet()){
                AppWaresGroupVO waresGroupVO = new AppWaresGroupVO();
                //审核通过数量、不通过数量、待审核数量
                final int[] numArray= {0,0,0};
                waresGroupVO.setTwItemList(groupListMap.get(key).stream().peek(item->{
                    if(StringUtils.isEmpty(item.getWaresStatus())){
                        //待审核
                        numArray[2]++;
                        item.setSelected(false);
                    }else{
                        if("1".equals(item.getWaresStatus())){
                            //通过
                            numArray[0]++;
                        }else{
                            //不通过
                            numArray[1]++;
                        }
                        item.setApprovalTime(item.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    }
                }).collect(Collectors.toList()));
                waresGroupVO.setGroupName(groupListMap.get(key).get(0).getTypeName());
                waresGroupVO.setGroupId(key);
                waresGroupVO.setTypeNums(groupListMap.get(key).size());
                waresGroupVO.setNums(groupListMap.get(key).stream().mapToInt(DlTwItem::getWaresCount).sum());
                waresGroupVO.setAllowNum(numArray[0]);
                waresGroupVO.setNoNum(numArray[1]);
                waresGroupVO.setWaitingNum(numArray[2]);
                waresGroupList.add(waresGroupVO);
            }
        }
        return waresGroupList;
    }
}




