package com.td.Dawa.game.complayerbackpack.service;

import cn.hutool.core.util.ArrayUtil;
import com.td.Dawa.common.pojo.PageCondition;
import com.td.Dawa.common.pojo.PageInfo;
import com.td.Dawa.common.service.*;
import com.td.Dawa.config.enums.GameEnum;
import com.td.Dawa.game.complayerbackpack.pojo.ComPlayerBackpack;
import com.td.Dawa.game.complayerbackpack.vo.ComPlayerBackpackClientVo;
import com.td.Dawa.game.complayerbackpack.vo.ComPlayerBackpackVo;
import com.td.Dawa.game.complayerbackpack.repository.ComPlayerBackpackRepository;
import com.td.Dawa.game.excelprop.pojo.ExcelProp;
import com.td.Dawa.game.excelprop.service.ExcelPropService;
import com.td.Dawa.game.excelprop.vo.ExcelPropClientVo;
import com.td.Dawa.game.excelprop.vo.ExcelPropVo;
import com.td.Dawa.util.CopyUtil;
import com.td.Dawa.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ComPlayerBackpackServiceImpl extends CommonServiceImpl<ComPlayerBackpackVo, ComPlayerBackpack, String> implements ComPlayerBackpackService {

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private ComPlayerBackpackRepository comPlayerBackpackRepository;
    @Autowired
    private ExcelPropService excelPropService;

    @Override
    public ComPlayerBackpack findByUserIdAndItemId(String userId, Integer itemId) {
        ComPlayerBackpack comPlayerBackpack = comPlayerBackpackRepository.findByUserIdAndItemId(userId,itemId).orElse(null);
        return comPlayerBackpack;
    }

    /**
     * 根据userId对应的propIds保存全部物品
     *
     * @param propClientVoList
     * @param userId
     * @return
     */
    @Override
    public List<ComPlayerBackpack> saveAllByUserIdAndProps(String userId, List<ExcelPropClientVo> propClientVoList) {
        //对传入的数据去重，叠加
        List<ExcelPropClientVo> _difPropClientVoList = new ArrayList<>();
        for(ExcelPropClientVo _vo : propClientVoList){
            //createTime不一样，用时间做对比
            List<Integer> ids = _difPropClientVoList.stream().map(ExcelPropClientVo::getPropId).collect(Collectors.toList());
            if(ids.contains(_vo.getPropId())){
                //叠加
                ExcelPropClientVo _super = _difPropClientVoList.get(ids.indexOf(_vo.getPropId()));
                //log.info(_super.toString());
                _super.setItemNum(_super.getItemNum() + _vo.getItemNum());
            }else{
                _difPropClientVoList.add(_vo);
            }
        }
        //todo 如果传入的数据背包有一部分没有，则新增
        List<Integer> propIds = _difPropClientVoList.stream().map(ExcelPropClientVo::getPropId).collect(Collectors.toList());
        List<ComPlayerBackpack> comPlayerBackpackList = comPlayerBackpackRepository.findAllByItemIdInAndUserId(propIds, userId);
        List<Integer> itemArray = comPlayerBackpackList.stream().map(ComPlayerBackpack::getItemId).collect(Collectors.toList());
        //propIds 为原始prop id
        for (ExcelPropClientVo vo : _difPropClientVoList) {
            if (itemArray.contains(vo.getPropId())) {
                //如果存在，则为旧数据，+ itemNum
                ComPlayerBackpack comPlayerBackpack = comPlayerBackpackList.get(itemArray.indexOf(vo.getPropId()));
                comPlayerBackpack.setAmount(comPlayerBackpack.getAmount() + vo.getItemNum());
                log.info("1==>id:"+vo.getPropId());
                log.info(comPlayerBackpack.toString());
                super.save(CopyUtil.copy(comPlayerBackpack, ComPlayerBackpackVo.class));
            } else {
                //如果不存在，新增
                ComPlayerBackpack comPlayerBackpack = new ComPlayerBackpack();
                //comPlayerBackpack.setId(UUIDUtil.getUUID());
                comPlayerBackpack.setAmount(vo.getItemNum().doubleValue());
                comPlayerBackpack.setItemId(vo.getPropId());
                comPlayerBackpack.setUserId(userId);
                comPlayerBackpack.setItemName(vo.getName());
                comPlayerBackpack.setItemTag(vo.getItemType());
                comPlayerBackpack.setItemType(vo.getItemType());//分类和标识暂时设置一样
                comPlayerBackpack.setCreateTime(vo.getCreateTime());
                comPlayerBackpackList.add(comPlayerBackpack);
                log.info("2==>id:"+vo.getPropId());
                log.info(comPlayerBackpack.toString());
                super.save(CopyUtil.copy(comPlayerBackpack, ComPlayerBackpackVo.class));
            }
        }
        //comPlayerBackpackRepository.saveAll(comPlayerBackpackList);
        return comPlayerBackpackList;
    }


    @Override
    public ComPlayerBackpack saveByUserIdAndProp(String userId, ExcelPropClientVo vo) {

        //todo 如果传入的数据背包有一部分没有，则新增
        ComPlayerBackpack comPlayerBackpack = comPlayerBackpackRepository.findByUserIdAndItemId(userId, vo.getPropId()).orElse(null);
         //propIds 为原始prop id
        if (comPlayerBackpack != null) {
            //如果存在，则为旧数据，+ itemNum
            comPlayerBackpack.setAmount(comPlayerBackpack.getAmount() + 1d);
            log.info("1==>id:"+vo.getPropId());
            log.info(comPlayerBackpack.toString());
            super.save(CopyUtil.copy(comPlayerBackpack, ComPlayerBackpackVo.class));
        } else {
            //如果不存在，新增
            comPlayerBackpack = new ComPlayerBackpack();
            comPlayerBackpack.setAmount(1d);
            comPlayerBackpack.setItemId(vo.getPropId());
            comPlayerBackpack.setUserId(userId);
            comPlayerBackpack.setItemName(vo.getName());
            comPlayerBackpack.setItemTag(vo.getItemType());
            comPlayerBackpack.setItemType(vo.getItemType());//分类和标识暂时设置一样
            comPlayerBackpack.setCreateTime(vo.getCreateTime());
            log.info("2==>id:"+vo.getPropId());
            log.info(comPlayerBackpack.toString());
            super.save(CopyUtil.copy(comPlayerBackpack, ComPlayerBackpackVo.class));
        }
        return comPlayerBackpack;
    }


    @Override
    public PageInfo getPageAndProp(ComPlayerBackpackVo comPlayerBackpackVo) {

        if (!(comPlayerBackpackVo instanceof PageCondition)) {
            throw new RuntimeException("ComPlayerBackpackVo 未继承PageCondition。");
        }
        List<ExcelProp> excelPropVoList = excelPropService.getListFromCache(GameEnum.REDIS_KEY_EXCEL_PROP.getMessage());
        List<Integer> propIdList = excelPropVoList.stream().map(ExcelProp::getPropId).collect(Collectors.toList());

        PageCondition pageCondition = (PageCondition) comPlayerBackpackVo;
        Page<ComPlayerBackpack> page = comPlayerBackpackRepository.findAll(Example.of(CopyUtil.copy(comPlayerBackpackVo, ComPlayerBackpack.class)), pageCondition.getPageable());

        List<ComPlayerBackpackClientVo> comPlayerBackpackClientVos = page.getContent().stream().map(e -> {
            ComPlayerBackpackClientVo comPlayerBackpackClientVo = CopyUtil.copy(e, ComPlayerBackpackClientVo.class);
            comPlayerBackpackClientVo.setPropInfo(CopyUtil.copy(excelPropVoList.get(propIdList.indexOf(e.getItemId())), ExcelPropClientVo.class));
            return comPlayerBackpackClientVo;
        }).collect(Collectors.toList());

        return  PageInfo.customContent(page, comPlayerBackpackClientVos);
    }
}
