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

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.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.shop.entity.ShopConfig;
import cn.iocoder.yudao.module.shop.entity.UserBalance;
import cn.iocoder.yudao.module.shop.service.IShopConfigService;
import cn.iocoder.yudao.module.shop.service.IUserBalanceService;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
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.InspectionGoodsSku;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionCategory;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionGoods;
import cn.iocoder.yudao.module.inspection.mapper.AppInspectionGoodsMapper;
import cn.iocoder.yudao.module.inspection.query.GoodsQuery;
import cn.iocoder.yudao.module.inspection.service.AppInspectionGoodsService;
import cn.iocoder.yudao.module.inspection.service.InspectionGoodsSkuService;
import cn.iocoder.yudao.module.inspection.service.ShopInspectionCategoryService;
import cn.iocoder.yudao.module.inspection.vo.*;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.shop.entity.ShopCoupon;
import cn.iocoder.yudao.module.shop.service.IShopCouponService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 车检商品表(ShopInspectionGoods)表服务实现类
 *
 * @author makejava
 * @since 2023-08-01 16:04:14
 */
@Service("shopInspectionGoodsService")
public class AppInspectionGoodsServiceImpl extends ServiceImpl<AppInspectionGoodsMapper, ShopInspectionGoods> implements AppInspectionGoodsService {

    @Autowired
    private ShopInspectionCategoryService categoryService;
    @Autowired
    private IShopConfigService configService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IShopCouponService shopCouponService;
    @Autowired
    private InspectionGoodsSkuService skuService;
    @Autowired
    private IUserBalanceService userBalanceService;
    @Autowired
    private IPartnerWorkerService workerService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;


    @Override
    public IPage<PartnerListVo> homePartner(Page<PartnerListVo> page, Double longitude, Double latitude) {
        IPage<PartnerListVo> partnerListVos = baseMapper.homePartners(page,longitude,latitude);
        partnerListVos.getRecords().forEach(item->{
            if (StringUtils.isNotEmpty(item.getAddress())){
                item.setAddress(item.getAddress().substring(item.getAddress().indexOf("市")+1));
            }

        });
        return partnerListVos;
    }

    @Override
    public List<ShopInspectionCategory> categoryList() {
        LambdaQueryWrapper<ShopInspectionCategory> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(ShopInspectionCategory::getOrderNum);
        return categoryService.list(queryWrapper);
    }

    @Override
    public List<GoodsVo> goodsList(GoodsQuery goodsQuery) {
        List<GoodsVo> goodsVoList = baseMapper.goodsList(goodsQuery);
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(loginUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roleKeys = roleList.stream().map(item->item.getCode()).collect(Collectors.toList());
        for (GoodsVo goodsVo : goodsVoList) {
            LambdaQueryWrapper<InspectionGoodsSku> queryWrapper =new LambdaQueryWrapper();
            queryWrapper.eq(InspectionGoodsSku::getGoodsId,goodsVo.getGoodsId()).orderByAsc(InspectionGoodsSku::getOrderNum);
            List<InspectionGoodsSku> list = skuService.list(queryWrapper);
            Integer goodsId = list.get(0).getGoodsId();
            ShopInspectionGoods goods = this.getById(goodsId);
            try {
                if (roleKeys.contains("jcdb")){
                    //先判断是否为代办
                    for (InspectionGoodsSku skuItem : list) {
                        skuItem.setPrice(skuItem.getDbPrice());
                    }
                }else if (roleKeys.contains("jcdwgly")){
                    //单位管理员
                    for (InspectionGoodsSku skuItem : list) {
                        skuItem.setPrice(skuItem.getDwPrice());
                    }
                }else if (roleKeys.contains("jcworker")||roleKeys.contains("jcshop")){
                    //检测工人
                    //判断是否为当前店铺的工人
                    LambdaQueryWrapper<PartnerWorker> queryWrapper1 =new LambdaQueryWrapper<>();
                    queryWrapper1.eq(PartnerWorker::getUserId,loginUser.getId()).eq(PartnerWorker::getPartnerId,goods.getPartnerId()).last("limit 1");
                    PartnerWorker one = workerService.getOne(queryWrapper1);
                    if (ObjectUtils.isNotEmpty(one)){
                        for (InspectionGoodsSku skuItem : list) {
                            skuItem.setPrice(skuItem.getYgPrice());
                        }
                    }
                }

            }catch (Exception e){
                log.error(e.getMessage());
            }

            goodsVo.setSkuList(list);
        }
        return goodsVoList;
    }

    /**
     * 商品详情信息
     * @param goodsQuery
     * @return
     */
    @Override
    public GoodsDetail goodsDetail(GoodsQuery goodsQuery) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        GoodsDetail resInfo =new GoodsDetail();
        AdminUserDO sysUser = userService.getUser(userId);
        Integer userLevel = sysUser.getUserLevel();
        ShopInspectionGoods goods = baseMapper.selectById(goodsQuery.getGoodsId());
        //处理图片格式
        if (!StringUtils.isEmpty(goods.getImages())){
            goods.setImageList(goods.getImages().split(","));
        }
        BeanUtils.copyProperties(goods,resInfo);
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        //原价单位分
        Long priceFen = goods.getPrice();
        resInfo.setOriginalPrice(priceFen);
        if (goods.getIsAttend().equals("0")||goods.getIsSpecial()==1|| ObjectUtils.isEmpty(userLevel)||0==userLevel){
            //直接计算原价
            resInfo.setRealPrice(priceFen);
            Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(userId);
            List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
            List<String> roleKeys = roleList.stream().map(item->item.getCode()).collect(Collectors.toList());
            LambdaQueryWrapper<InspectionGoodsSku> queryWrapper =new LambdaQueryWrapper();
            queryWrapper.eq(InspectionGoodsSku::getGoodsId,goods.getId()).orderByDesc(InspectionGoodsSku::getOrderNum).last("limit 1");
            InspectionGoodsSku sku = skuService.getOne(queryWrapper);
            try {
                if (roleKeys.contains("jcdb")){
                    //先判断是否为代办
                    resInfo.setRealPrice(sku.getDbPrice());
                }else if (roleKeys.contains("jcdwgly")){
                    //单位管理员
                    resInfo.setRealPrice(sku.getDwPrice());
                }else if (roleKeys.contains("jcworker")||roleKeys.contains("jcshop")){
                    //检测工人
                    //判断是否为当前店铺的工人
                    LambdaQueryWrapper<PartnerWorker> queryWrapper1 =new LambdaQueryWrapper<>();
                    queryWrapper1.eq(PartnerWorker::getUserId,userId).eq(PartnerWorker::getPartnerId,goods.getPartnerId()).last("limit 1");
                    PartnerWorker one = workerService.getOne(queryWrapper1);
                    if (ObjectUtils.isNotEmpty(one)){
                        resInfo.setRealPrice(sku.getYgPrice());
                    }
                }

            }catch (Exception e){
                log.error(e.getMessage());
            }

        }
//        else if (userLevel==1){
//            //白银会员
//            //获取会员的优惠折扣
//            BigDecimal inspectionPlatinum = shopConfig.getInspectionSilver();
//            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
//            Double priceTmp =  priceFen*ratio;
//            resInfo.setRealPrice(priceTmp.longValue());
//
//        }else if (userLevel==2){
//            //黄金会员
//            BigDecimal inspectionPlatinum = shopConfig.getInspectionGold();
//            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
//            Double priceTmp =  priceFen*ratio;
//            resInfo.setRealPrice(priceTmp.longValue());
//        }else if (userLevel==3){
//            //白金会员
//            BigDecimal inspectionPlatinum = shopConfig.getInspectionPlatinum();
//            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
//            Double priceTmp =  priceFen*ratio;
//            resInfo.setRealPrice(priceTmp.longValue());
//        }
        String[] ratioStr ={shopConfig.getInspectionSilver().toString(),shopConfig.getInspectionGold().toString(),shopConfig.getInspectionPlatinum().toString()};
        resInfo.setRatioStr(ratioStr);
        //查询当前可用的优惠券
        List<ShopCoupon> shopCoupons = shopCouponService.canUseCoupon(goods.getId(), "检测项目现金券");
        if (CollectionUtil.isNotEmpty(shopCoupons)){
            resInfo.setCouponList(shopCoupons);
        }else {
            resInfo.setCouponList(new ArrayList<>());
        }
        return resInfo;
    }

    @Override
    public List<InspectionGoodsSku> goodsSkuList(GoodsQuery goodsQuery) {
        LambdaQueryWrapper<InspectionGoodsSku> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionGoodsSku::getGoodsId,goodsQuery.getGoodsId()).orderByDesc(InspectionGoodsSku::getOrderNum);
        List<InspectionGoodsSku> list = skuService.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)){
            list =new ArrayList<>();
        }
        Integer goodsId = list.get(0).getGoodsId();
        ShopInspectionGoods goods = this.getById(goodsId);
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(loginUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roleKeys = roleList.stream().map(item->item.getCode()).collect(Collectors.toList());
        try {
            if (roleKeys.contains("jcdb")){
                //先判断是否为代办
                for (InspectionGoodsSku skuItem : list) {
                    skuItem.setPrice(skuItem.getDbPrice());
                }
            }else if (roleKeys.contains("jcdwgly")){
                //单位管理员
                for (InspectionGoodsSku skuItem : list) {
                    skuItem.setPrice(skuItem.getDwPrice());
                }
            }else if (roleKeys.contains("jcworker")||roleKeys.contains("jcshop")){
                //检测工人
                //判断是否为当前店铺的工人
                LambdaQueryWrapper<PartnerWorker> queryWrapper1 =new LambdaQueryWrapper<>();
                queryWrapper1.eq(PartnerWorker::getUserId,loginUser.getId()).eq(PartnerWorker::getPartnerId,goods.getPartnerId()).last("limit 1");
                PartnerWorker one = workerService.getOne(queryWrapper1);
                if (ObjectUtils.isNotEmpty(one)){
                    for (InspectionGoodsSku skuItem : list) {
                        skuItem.setPrice(skuItem.getYgPrice());
                    }
                }
            }

        }catch (Exception e){
            log.error(e.getMessage());
        }
        return list;
    }

    @Override
    public OrderGoodsInfo orderGoodsInfo(GoodsQuery goodsQuery) {
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        OrderGoodsInfo res =new OrderGoodsInfo();
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        ShopInspectionGoods goods = this.getById(goodsQuery.getGoodsId());
        AdminUserDO sysUser = userService.getUser(userId);
        Integer userLevel = sysUser.getUserLevel();
        res.setGoodsId(goods.getId());
        res.setGoodsName(goods.getTitle());
        res.setGoodsImage(goods.getImage());
        res.setPrice(goods.getPrice());
        res.setType("goods");
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(sysUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roleKeys = roleList.stream().map(item->item.getCode()).collect(Collectors.toList());
        //计算折扣
        if (goods.getIsSpecial()==1||goods.getIsAttend().equals("0")||ObjectUtils.isEmpty(userLevel)||0==userLevel){
            //直接计算原价
            res.setRatio(1d);
        }
        else if(roleKeys.contains("jcdwgly")){
            //如果是单位管理员
            Double jcdwglyRatio = shopConfig.getJcdwglyRatio();
            res.setRatio(jcdwglyRatio/10);
        }
        else if (userLevel==1){
            //白银会员
            //获取会员的优惠折扣
            BigDecimal inspectionPlatinum = shopConfig.getInspectionSilver();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            res.setRatio(ratio);

        }else if (userLevel==2){
            //黄金会员
            BigDecimal inspectionPlatinum = shopConfig.getInspectionGold();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            res.setRatio(ratio);
        }else if (userLevel==3){
            //白金会员
            BigDecimal inspectionPlatinum = shopConfig.getInspectionPlatinum();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            res.setRatio(ratio);
        }
        //计算可用优惠券个数
        Integer count = shopCouponService.canUseCouponCount(goods.getId(), "检测项目现金券");
        res.setCouponNum(count);
        //计算积分余额
        UserBalance shopUserBalance = userBalanceService.selectShopUserBalanceByUserId(userId);
        res.setBalance(shopUserBalance.getBalance());
        return res;
    }

    @Override
    public OrderGoodsInfo orderSkuInfo(GoodsQuery goodsQuery) {
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        OrderGoodsInfo res =new OrderGoodsInfo();
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        InspectionGoodsSku goodsSku = skuService.getById(goodsQuery.getGoodsId());
        ShopInspectionGoods goodsInfo = this.getById(goodsSku.getGoodsId());
        AdminUserDO sysUser = userService.getUser(userId);
        Integer userLevel = sysUser.getUserLevel();
        res.setGoodsId(goodsSku.getId());
        res.setGoodsName(goodsSku.getSkuName());
        res.setGoodsImage(goodsInfo.getImage());
        res.setPrice(goodsSku.getPrice());
        res.setType("sku");
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(userId);
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        List<String> roleKeys = roleList.stream().map(item->item.getCode()).collect(Collectors.toList());

        //计算折扣
        if (goodsInfo.getIsSpecial()==1||goodsInfo.getIsAttend().equals("0")||ObjectUtils.isEmpty(userLevel)||0==userLevel){
            //直接计算原价
            try {
                if (roleKeys.contains("jcdb")){
                    //先判断是否为代办
                    res.setPrice(goodsSku.getDbPrice());
                }else if (roleKeys.contains("jcdwgly")){
                    //单位管理员
                    res.setPrice(goodsSku.getDwPrice());
                }else if (roleKeys.contains("jcworker")||roleKeys.contains("jcshop")){
                    //检测工人
                    //判断是否为当前店铺的工人
                    LambdaQueryWrapper<PartnerWorker> queryWrapper1 =new LambdaQueryWrapper<>();
                    queryWrapper1.eq(PartnerWorker::getUserId,userId).eq(PartnerWorker::getPartnerId,goodsInfo.getPartnerId()).last("limit 1");
                    PartnerWorker one = workerService.getOne(queryWrapper1);
                    if (ObjectUtils.isNotEmpty(one)){
                        res.setPrice(goodsSku.getYgPrice());
                    }
                }


            }catch (Exception e){
                log.error(e.getMessage());
            }
            res.setRatio(1d);
        }
        else if (userLevel==1){
            //白银会员
            //获取会员的优惠折扣
            BigDecimal inspectionPlatinum = shopConfig.getInspectionSilver();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            res.setRatio(ratio);

        }else if (userLevel==2){
            //黄金会员
            BigDecimal inspectionPlatinum = shopConfig.getInspectionGold();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            res.setRatio(ratio);
        }else if (userLevel==3){
            //白金会员
            BigDecimal inspectionPlatinum = shopConfig.getInspectionPlatinum();
            Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
            res.setRatio(ratio);
        }
        //计算可用优惠券个数
        Integer count = shopCouponService.canUseCouponCount(goodsInfo.getId(), "检测项目现金券");
        res.setCouponNum(count);
        //计算积分余额
        UserBalance shopUserBalance = userBalanceService.selectShopUserBalanceByUserId(userId);
        res.setBalance(ObjectUtils.isEmpty(shopUserBalance)?0:shopUserBalance.getBalance());
        return res;
    }
}

