package cn.pluss.platform.device.impl;

import cn.pluss.platform.DeviceGoodsService;
import cn.pluss.platform.device.DeviceOrderInfoService;
import cn.pluss.platform.device.MercOrderDetailService;
import cn.pluss.platform.device.MercShopTrolleyService;
import cn.pluss.platform.deviceDetail.DeviceDetailService;
import cn.pluss.platform.deviceMerchantBuy.DeviceMerchantBuyService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MercShopTrolleyMapper;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.vo.DeviceDetailVO;
import cn.pluss.platform.vo.DeviceGoodsVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2022-03-16
 */
@Service
public class MercShopTrolleyServiceImpl extends ServiceImpl<MercShopTrolleyMapper, MercShopTrolley> implements MercShopTrolleyService {

    @Autowired
    private UserAppService uaService;

    @Autowired
    private DeviceDetailService ddService;

    @Autowired
    private DeviceGoodsService deviceGoodsService;

    @Autowired
    private DeviceOrderInfoService doiService;

    @Autowired
    private MerchantChannelStatusService mcsService;

    @Autowired
    private DeviceMerchantBuyService dmbService;

    @Autowired
    private MercOrderDetailService orderDetailService;

    @Override
    public void apiAdd(MercShopTrolley entity) {
        UserApp tokenUa = uaService.queryUserAppByToken();

        add(entity);

        if (!tokenUa.getUserId().equals(entity.getUserId())) {
            throw new MsgException("加入购物车失败！");
        }

        if ("MP_NEW".equals(entity.getCode())) {
            final MerchantChannelStatus mcs = mcsService.getValidData(tokenUa.getMerchantCode());
            if (mcs == null) {
                throw new MsgException("非商户不允许购买新商户礼包");
            }

            if (!Objects.equals(mcs.getStatus(), MerchantChannelStatus.AUDIT_STATUS_SUCCESS) && !Objects.equals(mcs.getStatus(), MerchantChannelStatus.AUDIT_STATUS_SUCCESS)) {
                throw new MsgException("非商户不允许购买新商户礼包");
            }

            if (!Objects.equals(entity.getNum(), 1L)) {
                throw new MsgException("新商户礼包只能下单一个");
            }

            QueryWrapper<DeviceOrderInfo> qWrapper = new QueryWrapper<DeviceOrderInfo>()
                    .eq("userId", tokenUa.getUserId())
                    .eq("code", "MP_NEW");
            List<DeviceOrderInfo> data = doiService.list(qWrapper);
            for (DeviceOrderInfo datum : data) {
                QueryWrapper<DeviceMerchantBuy> qWrapper2 = new QueryWrapper<>();
                qWrapper2.eq("orderNo", datum.getOrderNo());
                DeviceMerchantBuy one = dmbService.getOne(qWrapper2);
                if (one != null && "1".equals(one.getStatus())) {
                    throw new MsgException("新商户礼包只能下单一次");
                }
            }

            LambdaQueryWrapper<MercOrderDetail> qWrapper2= Wrappers.lambdaQuery();
            qWrapper2.eq(MercOrderDetail::getCode, "MP_NEW");
            qWrapper2.ne(MercOrderDetail::getStatus, MercOrderDetail.STATUS_NO_PAY);
            final int count = orderDetailService.count(qWrapper2);
            if (count > 0) {
                throw new MsgException("新商户礼包只能下单一次");
            }
        }
    }

    @Override
    public void add(MercShopTrolley entity) {
        DeviceGoods deviceGoods = new DeviceGoods();
        deviceGoods.setCode(entity.getCode());
        deviceGoods = deviceGoodsService.getOne(new QueryWrapper<>(deviceGoods));
        entity.setName(deviceGoods.getName());

        MercShopTrolley exist = new MercShopTrolley();
        exist.setCode(entity.getCode());
        exist.setUserId(entity.getUserId());
        exist.setType(entity.getType());
        exist = getOne(new QueryWrapper<>(exist));

        if (exist == null) {
            baseMapper.insert(entity);
        } else {
            long total = exist.getNum() + entity.getNum();
            exist.setNum(total > 10? 10: total);
            entity.setNum(exist.getNum());
            baseMapper.updateById(exist);
        }
    }

    @Override
    public void apiUpdate(MercShopTrolley entity) {
        UserApp tokenUa = uaService.queryUserAppByToken();

        if (!tokenUa.getUserId().equals(entity.getUserId())) {
            throw new MsgException("操作失败！");
        }

        update(entity);
    }

    @Override
    public void update(MercShopTrolley entity) {
        MercShopTrolley exist = new MercShopTrolley();
        exist.setCode(entity.getCode());
        exist.setUserId(entity.getUserId());
        exist.setType(entity.getType());
        exist = getOne(new QueryWrapper<>(exist));

        if (exist != null && !exist.getId().equals(entity.getId())) {
            exist.setNum(exist.getNum() + entity.getNum());
            baseMapper.updateById(exist);
            baseMapper.deleteById(entity.getId());
        } else {
            baseMapper.updateById(entity);
        }

    }

    @Override
    public List<MercShopTrolley> listByUserId(Long userId) {
        LambdaQueryWrapper<MercShopTrolley> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MercShopTrolley::getUserId, userId);

        return baseMapper.selectList(qWrapper);
    }

    @Override
    public List<MercShopTrolley> apiList() {
        UserApp tokenUa = uaService.queryUserAppByToken();
        return listByUserId(tokenUa.getUserId());
    }

    @Override
    public List<DeviceGoodsVO> shopTrolleyListByUserId(Long userId) {
        List<MercShopTrolley> mercShopTrolleys = listByUserId(userId);

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

        List<String> codeList = new ArrayList<>();

        for (MercShopTrolley item : mercShopTrolleys) {
            codeList.add(item.getCode());
        }

        List<DeviceDetailVO> deviceDetailVOList = ddService.listByCode(codeList);

        for (MercShopTrolley item : mercShopTrolleys) {
            DeviceGoodsVO resultItem = new DeviceGoodsVO();

            DeviceGoods dgCondition = new DeviceGoods();
            dgCondition.setCode(item.getCode());

            DeviceGoods dg = deviceGoodsService.getOne(new QueryWrapper<>(dgCondition));

            resultItem.setId(item.getId());
            resultItem.setName(dg.getName());
            resultItem.setCode(dg.getCode());
            resultItem.setCodeName(dg.getCodeName());
            resultItem.setDetail(dg.getDetail());
            resultItem.setIntroDesc(dg.getIntroDesc());
            resultItem.setDeviceLogo(dg.getDeviceLogo());
            resultItem.setUserId(userId);

            if (resultItem.getTypeList() == null) {
                resultItem.setTypeList(new ArrayList<>());
            }

            for (DeviceDetailVO deviceDetailVO : deviceDetailVOList) {
                if (resultItem.getCode().equals(deviceDetailVO.getCode())) {
                    resultItem.getTypeList().add(deviceDetailVO);

                    if (item.getType().equals(deviceDetailVO.getType())) {
                        resultItem.setCurrentType(deviceDetailVO);
                    }
                }
            }

            resultItem.setNum(item.getNum());

            result.add(resultItem);
        }

        return result;
    }

    @Override
    public List<DeviceGoodsVO> apiShopTrolleyList() {
        UserApp tokenUa = uaService.queryUserAppByToken();
        return shopTrolleyListByUserId(tokenUa.getUserId());
    }
}
