package cn.pluss.platform.impl;

import cn.pluss.platform.DeviceGoodsService;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.deviceDetail.DeviceDetailService;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.entity.Device;
import cn.pluss.platform.entity.DeviceGoods;
import cn.pluss.platform.entity.Dict;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.DeviceGoodsMapper;
import cn.pluss.platform.vo.DeviceDetailVO;
import cn.pluss.platform.vo.DeviceGoodsVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.springframework.beans.BeanUtils;
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.function.Predicate;

/**
 * <p>
 * 设备商品展示表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2020-11-11
 */
@Service
public class DeviceGoodsServiceImpl extends ServiceImpl<DeviceGoodsMapper, DeviceGoods> implements DeviceGoodsService {

    @Setter(onMethod_ = {@Autowired})
    private DeviceDetailService deviceDetailService;

    @Setter(onMethod_ = {@Autowired})
    private DictService dictService;

    @Override
    public PageInfo<DeviceGoodsVO> goodList(Integer pageNum, Integer size, DeviceGoods condition) {
        OrderItem orderItem = new OrderItem().setAsc(true).setColumn("sort");
        Page<DeviceGoods> pageInfo = new Page<>();
        pageInfo.addOrder(orderItem);
        pageInfo.setCurrent(pageNum);

        condition.setStatus(1);
        List<DeviceGoodsVO> result = new ArrayList<>();

        Page<DeviceGoods> devList = baseMapper.selectPage(pageInfo, new QueryWrapper<>(condition));

        // 获取商品规格信息
        List<String> devCodeList = new ArrayList<>();
        for (DeviceGoods item : devList.getRecords()) {
            devCodeList.add(item.getCode());
        }

        List<DeviceDetailVO> deviceDetailsList = deviceDetailService.listByCode(devCodeList);

        for (DeviceGoods devItem : devList.getRecords()) {
            DeviceGoodsVO deviceGoodsVO = new DeviceGoodsVO();
            BeanUtils.copyProperties(devItem, deviceGoodsVO);
            result.add(deviceGoodsVO);

            for (DeviceDetailVO item : deviceDetailsList) {
                if (devItem.getCode().equals(item.getCode())) {
                    item.setStockNum(10L);
                    deviceGoodsVO.getTypeList().add(item);

                    if (deviceGoodsVO.getUnitPrice() == null) {
                        deviceGoodsVO.setUnitPrice(item.getUnitPrice());
                    } else {
                        if (item.getUnitPrice().compareTo(deviceGoodsVO.getUnitPrice()) < 0) {
                            deviceGoodsVO.setUnitPrice(item.getUnitPrice());
                        }
                    }
                }
            }
        }

        return new PageInfo<>(devList.getTotal(), devList.getPages(), devList.getCurrent(), devList.getSize(), result);
    }

    @Override
    public PageInfo<DeviceGoodsVO> goodListSimple(Integer pageNum, Integer size, DeviceGoods condition) {
        OrderItem orderItem = new OrderItem().setAsc(true).setColumn("sort");
        Page<DeviceGoods> pageInfo = new Page<>();
        pageInfo.addOrder(orderItem);
        pageInfo.setCurrent(pageNum);

        condition.setStatus(1);
        List<DeviceGoodsVO> result = new ArrayList<>();

        QueryWrapper<DeviceGoods> qWrapper = new QueryWrapper<>(condition);
        qWrapper.select(DeviceGoods.class, i -> !"detail".equals(i.getColumn()));
        Page<DeviceGoods> devList = baseMapper.selectPage(pageInfo, qWrapper);

        // 获取商品规格信息
        List<String> devCodeList = new ArrayList<>();
        for (DeviceGoods item : devList.getRecords()) {
            devCodeList.add(item.getCode());
        }

        List<DeviceDetailVO> deviceDetailsList = deviceDetailService.listByCodeSimple(devCodeList);

        for (DeviceGoods devItem : devList.getRecords()) {
            DeviceGoodsVO deviceGoodsVO = new DeviceGoodsVO();
            BeanUtils.copyProperties(devItem, deviceGoodsVO);
            result.add(deviceGoodsVO);

            for (DeviceDetailVO item : deviceDetailsList) {
                if (devItem.getCode().equals(item.getCode())) {
                    item.setStockNum(10L);
                    deviceGoodsVO.getTypeList().add(item);

                    if (deviceGoodsVO.getUnitPrice() == null) {
                        deviceGoodsVO.setUnitPrice(item.getUnitPrice());
                    } else {
                        if (item.getUnitPrice().compareTo(deviceGoodsVO.getUnitPrice()) < 0) {
                            deviceGoodsVO.setUnitPrice(item.getUnitPrice());
                        }
                    }
                }
            }
        }

        return new PageInfo<>(devList.getTotal(), devList.getPages(), devList.getCurrent(), devList.getSize(), result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(DeviceGoods entity) {

        Dict pDict = new Dict();
        pDict.setCode("DEVICE_TYPE");
        pDict = dictService.getOne(new QueryWrapper<>(pDict));

        final String code = entity.getCode();
        final Dict dict = new Dict();
        dict.setPId(pDict.getId());
        dict.setValue(entity.getCode());

        final Dict exist = dictService.getOne(new QueryWrapper<>(dict));

        if (exist != null && !entity.getCodeName().equals(exist.getName())) {
            // 已经存在的商品类型，名称不同，不能添加
            throw new MsgException("已经存在的商品编码，编码名称必须和现有名称保持一致");
        }

        if (exist == null) {
            Dict maxSort = dictService.getMaxSortElem("DEVICE_TYPE");

            dict.setName(entity.getCodeName());
            dict.setDesc(entity.getCodeName());
            dict.setSort(maxSort.getSort() + 1);
            dict.setPId(maxSort.getId());
            dictService.save(dict);
        }

        if (entity.getId() == null) {
            DeviceGoods existData = new DeviceGoods();
            existData.setCode(code);
            existData = getOne(new QueryWrapper<>(existData));

            // 本质上商品code是唯一编码，商品名称只是一个别名
            if (existData != null) {
                throw new MsgException("已存在相同类型的商品数据");
            }
        }

        if (entity.getSort() == null) {
            entity.setSort(-1);
        }

        return super.saveOrUpdate(entity);
    }
}
