package cn.pluss.platform.deviceDetail.impl;

import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.device.DeviceSpecService;
import cn.pluss.platform.device.DeviceStockGroupService;
import cn.pluss.platform.deviceDetail.DeviceDetailService;
import cn.pluss.platform.deviceStock.DeviceStockService;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.entity.DeviceDetail;
import cn.pluss.platform.entity.DeviceSpec;
import cn.pluss.platform.entity.DeviceStockGroup;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.DeviceDetailMapper;
import cn.pluss.platform.vo.DeviceDetailVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * [设备展示表] 服务实现类
 * </p>
 *
 * @author bzg
 * @since 2020-11-12
 */
@Service
public class DeviceDetailServiceImpl extends ServiceImpl<DeviceDetailMapper, DeviceDetail> implements DeviceDetailService {

    @Setter(onMethod_ = {@Autowired})
    private DeviceStockService deviceStockService;

    @Autowired
    private DeviceSpecService deviceSpecService;

    @Autowired
    private DeviceStockGroupService deviceStockGroupService;

    @Override
    public List<DeviceDetailVO> listByCode(List<String> codeList) {
        if (codeList == null || codeList.isEmpty()) {
            return new ArrayList<>();
        }

        List<DeviceDetailVO> result = new ArrayList<>();

        QueryWrapper<DeviceDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("dd.code", codeList);
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("seq");
        List<DeviceDetail> deviceDetails = baseMapper.selectListWithStock(queryWrapper);

        List<String> groupNoList = new ArrayList<>();
        deviceDetails.forEach( it -> groupNoList.add(it.getGroupNo()));

        List<Map<String, Object>> stockList = deviceStockService.getStockInfoMaps(groupNoList);

        // 查询已下单数量
        List<Map<String, Object>> soldList = deviceStockService.getSoldStockMaps(groupNoList);

        for (DeviceDetail deviceDetail : deviceDetails) {

            DeviceDetailVO ddVO = Converter.INSTANCE.toVO(deviceDetail);

//            for (Map<String, Object> stockMap : stockList) {
//                if (stockMap.get("groupNo").equals(deviceDetail.getGroupNo())) {
//                    ddVO.setTotalCount(((Long) stockMap.get("count")));
//                    // map.put("totalCount", new BigDecimal(stockMap.get("count").toString()));
//                    break;
//                }
//            }
            if (ddVO.getTotalCount() != null) {
                ddVO.setTotalCount(0L);
            }

            // map.putIfAbsent("totalCount", BigDecimal.ZERO);

            for (Map<String, Object> soldMap : soldList) {
                if (soldMap.get("groupNo").equals(deviceDetail.getGroupNo())) {
                    ddVO.setTotalSold((Long.parseLong(soldMap.get("soldCount").toString())));
                    // map.put("totalSold", );
                    break;
                }
            }

            if (ddVO.getTotalSold() != null) {
                ddVO.setTotalSold(0L);
            }

            result.add(ddVO);
        }

        return result;
    }

    @Override
    public List<DeviceDetailVO> listByCodeSimple(List<String> codeList) {
        if (codeList == null || codeList.isEmpty()) {
            return new ArrayList<>();
        }

        List<DeviceDetailVO> result = new ArrayList<>();

        QueryWrapper<DeviceDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("dd.code", codeList);
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("seq");
        List<DeviceDetail> deviceDetails = baseMapper.selectListWithStockWithNoDetail(queryWrapper);

        List<String> groupNoList = new ArrayList<>();
        deviceDetails.forEach( it -> groupNoList.add(it.getGroupNo()));

//        List<Map<String, Object>> stockList = deviceStockService.getStockInfoMaps(groupNoList);

        // 查询已下单数量
        List<Map<String, Object>> soldList = deviceStockService.getSoldStockMaps(groupNoList);

        for (DeviceDetail deviceDetail : deviceDetails) {

            DeviceDetailVO ddVO = Converter.INSTANCE.toVO(deviceDetail);

//            for (Map<String, Object> stockMap : stockList) {
//                if (stockMap.get("groupNo").equals(deviceDetail.getGroupNo())) {
//                    ddVO.setTotalCount(((Long) stockMap.get("count")));
//                    // map.put("totalCount", new BigDecimal(stockMap.get("count").toString()));
//                    break;
//                }
//            }
            if (ddVO.getTotalCount() != null) {
                ddVO.setTotalCount(0L);
            }

            // map.putIfAbsent("totalCount", BigDecimal.ZERO);

            for (Map<String, Object> soldMap : soldList) {
                if (soldMap.get("groupNo").equals(deviceDetail.getGroupNo())) {
                    ddVO.setTotalSold((Long.parseLong(soldMap.get("soldCount").toString())));
                    // map.put("totalSold", );
                    break;
                }
            }

            if (ddVO.getTotalSold() != null) {
                ddVO.setTotalSold(0L);
            }

            result.add(ddVO);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(DeviceDetail entity) {
        // 保存新的版本
        DeviceSpec deviceSpec = new DeviceSpec();
        deviceSpec.setSpecName(entity.getTypeDesc());
        deviceSpec.setSpecDesc(entity.getTypeDesc());

        deviceSpec.setCode(entity.getCode()).setSpec(entity.getType());
        DeviceSpec existType = deviceSpecService.getByCodeAndSpec(entity.getCode(), entity.getType());
        if (existType == null) {
            // 默认序号为999
            deviceSpec.setWeight(entity.getWeight());
            deviceSpecService.save(deviceSpec);
        } else {
            if (!existType.getSpecName().equals(deviceSpec.getSpecName())) {
                throw new MsgException("存在相同的版本编码，如需添加新的版本请使用不一样的版本编码");
            }
        }

        // 保存新的设备分组
        DeviceStockGroup deviceStockGroup = new DeviceStockGroup();
        deviceStockGroup.setGroupCode(entity.getGroupNo());
        DeviceStockGroup exist = deviceStockGroupService.getOne(new QueryWrapper<>(deviceStockGroup));

        if (exist == null) {
            deviceStockGroup.setSort(999);
            deviceStockGroup.setGroupName(entity.getGroupNoDesc());
            deviceStockGroup.setDesc(entity.getGroupNoDesc());
            deviceStockGroupService.save(deviceStockGroup);
        } else {
            if (!exist.getGroupName().equals(entity.getGroupNoDesc())) {
                throw new MsgException("存在相同的分组编码，如需添加新的分组请使用不一样的版本编码");
            }
        }

        return super.saveOrUpdate(entity);
    }
}
