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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
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.shop.entity.ShopConfig;
import cn.iocoder.yudao.module.shop.service.IShopConfigService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.inspection.entity.InspectionCategoryTemplate;
import cn.iocoder.yudao.module.inspection.entity.InspectionGoodsSku;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionCategory;
import cn.iocoder.yudao.module.inspection.mapper.ShopInspectionGoodsMapper;
import cn.iocoder.yudao.module.inspection.service.*;
import cn.iocoder.yudao.module.shop.entity.ShopMallPartners;
import cn.iocoder.yudao.module.shop.service.IShopMallPartnersService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionGoods;

/**
 * 检测商品Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-08
 */
@Service
public class ShopInspectionGoodsServiceImpl extends ServiceImpl<ShopInspectionGoodsMapper,ShopInspectionGoods> implements IShopInspectionGoodsService
{
    @Autowired
    private IShopConfigService configService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IShopMallPartnersService partnersService;
    @Autowired
    private IInspectionCategoryTemplateService categoryTemplateService;

    @Autowired
    private AppInspectionPartnerService appInspectionPartnerService;
    @Autowired
    private InspectionGoodsSkuService skuService;






    /*
     * @param id 检测商品主键
     * @return 检测商品
     */
    @Override
    public ShopInspectionGoods getByIdSystem(Long id)
    {
        ShopInspectionGoods good = baseMapper.selectShopInspectionGoodsById(id);
        //处理图片格式
        if (!StringUtils.isEmpty(good.getImages())){
            good.setImageList(good.getImages().split(","));
        }
        return good;
    }

    /**
     * 查询检测商品
     *
     * @param id 检测商品主键
     * @return 检测商品
     */
    @Override
    public ShopInspectionGoods selectShopInspectionGoodsById(Long id)
    {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO sysUser = userService.getUser(userId);
        Integer userLevel = sysUser.getUserLevel();
        ShopInspectionGoods good = baseMapper.selectShopInspectionGoodsById(id);
        //处理图片格式
        if (!StringUtils.isEmpty(good.getImages())){
            good.setImageList(good.getImages().split(","));
        }
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        //原价单位分
        Long priceFen = good.getPrice();
        Double priceYuan= priceFen.doubleValue()/100d;
        good.setOriginalPrice(BigDecimal.valueOf(priceYuan));
        if (good.getIsSpecial()==1||ObjectUtils.isEmpty(userLevel)||0==userLevel){
            //直接计算原价
            good.setRealPrice(BigDecimal.valueOf(priceYuan));
        }
        else if (userLevel==1){
            //白银会员
            //获取会员的优惠折扣
            BigDecimal inspectionPlatinum = shopConfig.getInspectionSilver();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            good.setRealPrice(BigDecimal.valueOf(priceYuan*ratio).setScale(2,BigDecimal.ROUND_HALF_UP));

        }else if (userLevel==2){
        //黄金会员
            BigDecimal inspectionPlatinum = shopConfig.getInspectionGold();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            good.setRealPrice(BigDecimal.valueOf(priceYuan*ratio).setScale(2,BigDecimal.ROUND_HALF_UP));
        }else if (userLevel==3){
        //白金会员
            BigDecimal inspectionPlatinum = shopConfig.getInspectionPlatinum();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            good.setRealPrice(BigDecimal.valueOf(priceYuan*ratio).setScale(2,BigDecimal.ROUND_HALF_UP));
        }


        return good;
    }

    /**
     * 查询检测商品列表
     *
     * @param shopInspectionGoods 检测商品
     * @return 检测商品
     */
    @Override
    public IPage<ShopInspectionGoods> selectShopInspectionGoodsListWx(Page<ShopInspectionGoods> page,ShopInspectionGoods shopInspectionGoods)
    {
        //默认蓝安的id为888
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        //获取最高会员的优惠折扣
        BigDecimal inspectionPlatinum = shopConfig.getInspectionPlatinum();
        Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
        IPage<ShopInspectionGoods> shopInspectionRes = baseMapper.selectShopInspectionGoodsListWx(page,shopInspectionGoods);
        for (ShopInspectionGoods good : shopInspectionRes.getRecords()) {
            if (good.getIsSpecial().equals(0)){
                //原价单位分
                Long priceFen = good.getPrice();
                Double priceYuan= priceFen.doubleValue()/100d;
                good.setLowPrice(BigDecimal.valueOf(priceYuan*ratio).setScale(2,BigDecimal.ROUND_HALF_UP));
            }else {
                good.setLowPrice(BigDecimal.valueOf(good.getPrice()/100d));
            }

        }
        return shopInspectionRes;
    }

    /**
     * 新增检测商品
     *
     * @param shopInspectionGoods 检测商品
     * @return 结果
     */
    @Override
    public int insertShopInspectionGoods(ShopInspectionGoods shopInspectionGoods)
    {
        shopInspectionGoods.setListingStatus("0");
        return baseMapper.insert(shopInspectionGoods);
    }

    /**
     * 修改检测商品
     *
     * @param shopInspectionGoods 检测商品
     * @return 结果
     */
    @Override
    public int updateShopInspectionGoods(ShopInspectionGoods shopInspectionGoods)
    {
        ShopInspectionGoods goods = baseMapper.selectById(shopInspectionGoods.getId());

        if (StringUtils.isNotEmpty(goods.getListingStatus())){
           if (!shopInspectionGoods.getIsListing().equals(goods.getIsListing())){
               shopInspectionGoods.setListingStatus("0");
           }
        }else {
            shopInspectionGoods.setListingStatus("0");
        }
        return baseMapper.updateById(shopInspectionGoods);
    }

    @Override
    public int examine(ShopInspectionGoods shopInspectionGoods)
    {
        ShopInspectionGoods goods = baseMapper.selectById(shopInspectionGoods.getId());

        if (StringUtils.isNotEmpty(goods.getListingStatus())){
          if (goods.getListingStatus().equals("1")){
              goods.setRejectReason(shopInspectionGoods.getRejectReason());
              if (shopInspectionGoods.getListingStatus().equals("2")){
                  goods.setIsListing("1");
              }else {
                  goods.setIsListing("0");
              }
              goods.setListingStatus(shopInspectionGoods.getListingStatus());
          }

        }
        return baseMapper.updateById(goods);
    }


    /**
     * 批量删除检测商品
     *
     * @param ids 需要删除的检测商品主键
     * @return 结果
     */
    @Override
    public int deleteShopInspectionGoodsByIds(Long[] ids)
    {
        return baseMapper.deleteByList(Arrays.asList(ids));
    }

    /**
     * 删除检测商品信息
     *
     * @param id 检测商品主键
     * @return 结果
     */
    @Override
    public int deleteShopInspectionGoodsById(Long id)
    {
        return baseMapper.deleteById(id);
    }
    //后台管理的列表查询部分
    @Override
    public IPage<ShopInspectionGoods> listSystem(Page<ShopInspectionGoods> page,ShopInspectionGoods shopInspectionGoods) {
        return baseMapper.listSystem(page,shopInspectionGoods);

    }

    @Override
    public IPage<ShopInspectionGoods> listPartnerGoods(Page<ShopInspectionGoods> page,ShopInspectionGoods shopInspectionGoods) throws Exception {

        return baseMapper.listPartnerGoods(page,shopInspectionGoods);
    }

    @Override
    public List<ShopInspectionCategory> categoryList() throws Exception {
        ShopMallPartners one = appInspectionPartnerService.shopInfoByUserId();
        List<ShopInspectionCategory> shopInspectionCategories = appInspectionPartnerService.categoryList(one.getPartnerId());
        for (ShopInspectionCategory shopInspectionCategory : shopInspectionCategories) {
            LambdaQueryWrapper<InspectionCategoryTemplate> templateLambdaQueryWrapper =new LambdaQueryWrapper<>();
            templateLambdaQueryWrapper.eq(InspectionCategoryTemplate::getCategoryId,shopInspectionCategory.getId()).orderByAsc(InspectionCategoryTemplate::getSkuPrice);
            List<InspectionCategoryTemplate> list = categoryTemplateService.list(templateLambdaQueryWrapper);
            shopInspectionCategory.setTemplates(list);
        }
        return shopInspectionCategories;
    }

    @Override
    public void partnerAddGoods(ShopInspectionGoods shopInspectionGoods) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopMallPartners::getUserId,loginUser.getId()).eq(ShopMallPartners::getType,"jc").last("limit 1");
        ShopMallPartners one = partnersService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)){
            throw new Exception("您不是商户");
        }
        shopInspectionGoods.setPartnerId(one.getPartnerId().intValue());
        appInspectionPartnerService.addGoods(shopInspectionGoods);

    }

    @Override
    public JSONObject partnerGoodsListCol(Long partnerId) {
        JSONObject res =new JSONObject();
        List<JSONObject> listGoods = new ArrayList<>();
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopInspectionGoods::getPartnerId,partnerId).eq(ShopInspectionGoods::getIsListing,"1").orderByAsc(ShopInspectionGoods::getOrderNum);
        List<ShopInspectionGoods> list = this.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            listGoods = list.stream().map(it -> {
                JSONObject item = new JSONObject();
                item.put("label", it.getTitle());
                item.put("value", it.getId());
                return item;
            }).collect(Collectors.toList());
        }
        res.put("goodsList",listGoods);
        List<List<JSONObject>> skuList = new ArrayList<>();
        for (ShopInspectionGoods goods : list) {
            LambdaQueryWrapper<InspectionGoodsSku> queryWrapper1 =new LambdaQueryWrapper<>();
            queryWrapper1.eq(InspectionGoodsSku::getGoodsId,goods.getId()).orderByDesc(InspectionGoodsSku::getOrderNum);
            List<InspectionGoodsSku> list1 = skuService.list(queryWrapper1);
            List<JSONObject> collect = list1.stream().map(it -> {
                JSONObject item = new JSONObject();
                item.put("label", it.getSkuName());
                item.put("value", it.getId());
                return item;
            }).collect(Collectors.toList());
            skuList.add(collect);
        }
        res.put("skuList",skuList);
        return res;
    }

    @Override
    public List<ShopInspectionGoods> partnerGoodsListTree(Long partnerId) {
        LambdaQueryWrapper<ShopInspectionGoods> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopInspectionGoods::getPartnerId,partnerId).eq(ShopInspectionGoods::getIsListing,"1").orderByAsc(ShopInspectionGoods::getOrderNum);
        List<ShopInspectionGoods> list = this.list(queryWrapper);
        for (ShopInspectionGoods goods : list) {
            LambdaQueryWrapper<InspectionGoodsSku> queryWrapper1 =new LambdaQueryWrapper<>();
            queryWrapper1.eq(InspectionGoodsSku::getGoodsId,goods.getId()).orderByDesc(InspectionGoodsSku::getOrderNum);
            List<InspectionGoodsSku> list1 = skuService.list(queryWrapper1);
            goods.setSkuList(list1);
        }
        return list;
    }
}
