package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.utils.DateUtil;
import com.ruoyi.system.utils.HttpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.ZsOperationGoodsBo;
import com.ruoyi.system.domain.vo.ZsOperationGoodsVo;
import com.ruoyi.system.domain.ZsOperationGoods;
import com.ruoyi.system.mapper.ZsOperationGoodsMapper;
import com.ruoyi.system.service.IZsOperationGoodsService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 商品配置Service业务层处理
 *
 * @author 王强
 * @date 2025-05-08
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class ZsOperationGoodsServiceImpl implements IZsOperationGoodsService {

    private final ZsOperationGoodsMapper baseMapper;

    /**
     * 查询商品配置
     */
    @Override
    public ZsOperationGoodsVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询商品配置列表
     */
    @Override
    public TableDataInfo<ZsOperationGoodsVo> queryPageList(ZsOperationGoodsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZsOperationGoods> lqw = buildQueryWrapper(bo);
        Page<ZsOperationGoodsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询商品配置列表
     */
    @Override
    public List<ZsOperationGoodsVo> queryList(ZsOperationGoodsBo bo) {
        LambdaQueryWrapper<ZsOperationGoods> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZsOperationGoods> buildQueryWrapper(ZsOperationGoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZsOperationGoods> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getGoodsSkuName()), ZsOperationGoods::getGoodsSkuName, bo.getGoodsSkuName());
        lqw.like(StringUtils.isNotBlank(bo.getGoodsSkuSn()), ZsOperationGoods::getGoodsSkuSn, bo.getGoodsSkuSn());
        lqw.eq(StringUtils.isNotBlank(bo.getPlatform()), ZsOperationGoods::getPlatform, bo.getPlatform());
        lqw.eq(StringUtils.isNotBlank(bo.getIsDisabled()), ZsOperationGoods::getIsDisabled, bo.getIsDisabled());
        //按照创建时间倒叙查询
        lqw.orderByDesc(ZsOperationGoods::getCreateDate);
        return lqw;
    }

    /**
     * 新增商品配置
     */
    @Override
    public Boolean insertByBo(ZsOperationGoodsBo bo) {
        ZsOperationGoods add = BeanUtil.toBean(bo, ZsOperationGoods.class);
        if (StringUtils.isBlank(add.getGoodsSkuUrl())) {
            throw new RuntimeException("商品url不能为空");
        }
        //去空
        add.setGoodsSkuUrl(add.getGoodsSkuUrl().trim());
        //相同url商品只能录入一个
        QueryWrapper<ZsOperationGoods> queryWrapper = new QueryWrapper();
        queryWrapper.eq("goods_sku_url",add.getGoodsSkuUrl());
        List<ZsOperationGoods> list = baseMapper.selectList(queryWrapper);
        if (list!=null&&list.size()>0) {
            throw new RuntimeException("商品url已经存在了！");
        }

        //获取抓取的信息
        Map<String, Object> reMap =  HttpUtil.sendGetRequest(bo.getGoodsSkuUrl(),false,bo.getPlatform());
        if ((boolean)reMap.get("success")) {
            List dataList = (List)reMap.get("data");
            Map dataMap = (Map)dataList.get(0);
            String title = (String)dataMap.get("title");
            String price = (String)dataMap.get("price");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(price)) {
                price =price.replace(",","").trim();
            }
            String sku = (String)dataMap.get("sku");
            String remark = (String)dataMap.get("remark");
            add.setGoodsSkuName(title);
            add.setGoodsSkuSn(sku);
            add.setRemark(remark);
            add.setInitPrice(new BigDecimal(price));
            validEntityBeforeSave(add);
            add.setCreateDate(new Date(DateUtil.getShanghaiTimestamp()));
            boolean flag = baseMapper.insert(add) > 0;
            return flag;
        } else {
            log.info("新增商品同步数据失败！reMap="+reMap.toString());
            return false;
        }
    }

    /**
     * 修改商品配置
     */
    @Override
    public Boolean updateByBo(ZsOperationGoodsBo bo) {
        ZsOperationGoods update = BeanUtil.toBean(bo, ZsOperationGoods.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZsOperationGoods entity){
        //TODO 做一些数据校验,如唯一约束
        String errMessage = "";
        if (StringUtils.isBlank(entity.getGoodsSkuName())) {
            errMessage= "商品名称不能为空";
        }
        if (StringUtils.isBlank(entity.getGoodsSkuSn())) {
            errMessage= "商品编码不能为空";
        }
        if (StringUtils.isBlank(entity.getGoodsSkuUrl())) {
            errMessage= "商品url不能为空";
        }
        if (entity.getInitPrice()==null) {
            errMessage= "基准价格不能为空";
        }
        if (StringUtils.isBlank(entity.getIsDisabled())) {
            errMessage= "是否启用不能为空";
        }
        if (StringUtils.isBlank(entity.getPlatform())) {
            errMessage= "平台不能为空";
        }

        if (!"".equals(errMessage)) {
            throw new RuntimeException(errMessage);
        }
    }

    /**
     * 批量删除商品配置
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
