package org.dromara.zhishu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.zhishu.annotation.LogRecord;
import org.dromara.zhishu.domain.ZhishuShopGoods;
import org.dromara.zhishu.domain.dto.request.UpdateArtNoRequest;
import org.dromara.zhishu.domain.dto.request.ZhishuShopGoodsRequest;
import org.dromara.zhishu.domain.vo.FreightGoodsCountVo;
import org.dromara.zhishu.domain.vo.SaveGoodsVo;
import org.dromara.zhishu.domain.vo.ShopVo;
import org.dromara.zhishu.enums.TaskTypeEnum;
import org.dromara.zhishu.mapper.ZhishuShopGoodsMapper;
import org.dromara.zhishu.service.IZhishuShopGoodsService;
import org.dromara.zhishu.service.ZhishuShopGoodsAopService;
import org.dromara.zhishu.service.client.KfzClient;
import org.dromara.zhishu.util.CnumberUtils;
import org.dromara.zhishu.util.UrlUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequiredArgsConstructor
@Service
public class ZhishuShopGoodsAopServiceImpl implements ZhishuShopGoodsAopService {

    @Autowired
    private ZhishuShopGoodsMapper baseMapper;

    @Autowired
    private KfzClient kfzClient;

    @Autowired
    @Lazy
    private IZhishuShopGoodsService zhishuShopGoodsService;

    @Override
    @LogRecord(logResult = true)
    public void insertNewDataList(
            @Param("data") ZhishuShopGoodsRequest data, @Param("userId") Long userId,
            @Param("freightGoodsCountList") List<FreightGoodsCountVo> freightGoodsCountList,
            @Param("saveGoodsVo") SaveGoodsVo saveGoodsVo,
            @Param("failedList") List<ZhishuShopGoodsRequest> failedList,
            @Param("successList") List<ZhishuShopGoodsRequest> successList,
            @Param("successMarkI") AtomicInteger successMarkI, @Param("failMarkI") AtomicInteger failMarkI,
            @Param("shopVo") ShopVo shopVo, @Param("totalNum") Integer totalNum, @Param("time") long time,
            @Param("status") AtomicBoolean status,
            @Param("taskType") String taskType
    ) {
        try {
            ZhishuShopGoods zhishuShopGoods = new ZhishuShopGoods();
            BeanUtils.copyProperties(data, zhishuShopGoods);
            zhishuShopGoods.setCreateBy(Long.valueOf(data.getUserId()));
            zhishuShopGoods.setUserId(userId);
            // 处理品相码
            double conditionCode;
            if (ObjectUtil.isNotEmpty(data.getConditionCode())) {
                conditionCode = Math.round(data.getConditionCode().doubleValue()) / 10.0;
                String conditionCodeString = CnumberUtils.getConditionCode(conditionCode);
                zhishuShopGoods.setConditionCode(conditionCodeString);
            } else {
                conditionCode = 8.5;
            }
            // 处理价格
            if (ObjectUtil.isNotEmpty(data.getPrice())) {
                zhishuShopGoods.setPrice(data.getPrice() * 100);
            }
            if (ObjectUtil.isNotEmpty(data.getFixPrice())) {
                zhishuShopGoods.setFixPrice(data.getFixPrice() * 100);
            }
            // 处理库存
            if (ObjectUtil.isNotEmpty(data.getInventory())) {
                zhishuShopGoods.setInventory(Long.valueOf(data.getInventory()));
            }
            // 判断ISBN码是否为空
            if (ObjectUtil.isEmpty(data.getIsbn())) {
                String isbn = CnumberUtils.generateRandomIsbn();
                zhishuShopGoods.setIsbn(isbn);
            }

            // 自动为书籍分配一二三级存储区域
            FreightGoodsCountVo freightGoodsCountVo = CnumberUtils.autoAllocatingAreas(freightGoodsCountList);
            // 将freightGoodsCountList对应货区书籍数量+1
            for (FreightGoodsCountVo goodsCountVo : freightGoodsCountList) {
                if (goodsCountVo.getFreightId().equals(freightGoodsCountVo.getFreightId())) {
                    goodsCountVo.setGoodsCount(goodsCountVo.getGoodsCount() + 1);
                }
            }

            // 获取货号
            String artNo = zhishuShopGoodsService.artNoProcessing(saveGoodsVo.getSaveArtNoRule(), userId, zhishuShopGoods.getIsbn(), data.getArtNo(), conditionCode, freightGoodsCountVo);
            zhishuShopGoods.setArtNo(artNo);

            // 写入仓库id
            zhishuShopGoods.setDepotId(freightGoodsCountVo.getDepotId());
            TaskTypeEnum taskTypeEnum = TaskTypeEnum.valueOfCode(taskType);
            switch (taskTypeEnum) {
                case SYNC_GOODS_KFZ:
                    // 写入原始货号
                    zhishuShopGoods.setOriginalArtNo(data.getArtNo());
                    // 将新生成的货号同步到kfz
                    if (saveGoodsVo.getSaveArtNoRule() != 0) {
                        UpdateArtNoRequest request = new UpdateArtNoRequest();
                        request.setShopId(saveGoodsVo.getShopId());
                        request.setProductId(Long.valueOf(zhishuShopGoods.getProductId()));
                        request.setArtNo(zhishuShopGoods.getArtNo());
                        try {
                            Thread.sleep(1000L); // 在调用前休眠
                            // kfzClient.updateArtNo(UrlUtil.getKfzServiceUrl(), request);
                            // 是否已货号转换
                            zhishuShopGoods.setIsArtNoConversion(1);
                        } catch (Exception e) {
                            throw new ServiceException("同步货号失败：" + e.getMessage());
                        }
                    }
                    break;
                case SYNC_GOODS_WLN:
                    // 写入原始货号
                    zhishuShopGoods.setOriginalArtNo(data.getProductId());
                    break;
            }
            // 将这条数据插入到数据库
            baseMapper.insert(zhishuShopGoods);
            // 初始化该商品redis库存
            zhishuShopGoodsService.batchRedisInitInventory(List.of(zhishuShopGoods));
            successList.add(data);
        } catch (Exception e) {
            log.error(e.getMessage());
            failedList.add(data);
            status.set(false);
        }
    }

    @Override
    @LogRecord(logResult = true)
    public void updateChangedDataList(
            @Param("data") ZhishuShopGoodsRequest data, @Param("userId") Long userId,
            @Param("freightGoodsCountList") List<FreightGoodsCountVo> freightGoodsCountList,
            @Param("saveGoodsVo") SaveGoodsVo saveGoodsVo,
            @Param("failedList") List<ZhishuShopGoodsRequest> failedList,
            @Param("successList") List<ZhishuShopGoodsRequest> successList,
            @Param("successMarkI") AtomicInteger successMarkI, @Param("failMarkI") AtomicInteger failMarkI,
            @Param("shopVo") ShopVo shopVo, @Param("totalNum") Integer totalNum, @Param("newTime") long time,
            @Param("status") AtomicBoolean status
    ) {
        List<ZhishuShopGoods> originalList = new LambdaQueryChainWrapper<>(baseMapper)
                .eq(ZhishuShopGoods::getId, data.getId())
                .list();
        if (ObjectUtil.isNotEmpty(originalList)) {
            ZhishuShopGoods zhishuShopGoods = new ZhishuShopGoods();
            zhishuShopGoods.setId(data.getId());
            zhishuShopGoods.setUserId(userId);
            // 判断ISBN码是否为空
            if (ObjectUtil.isEmpty(data.getIsbn())) {
                String isbn = CnumberUtils.generateRandomIsbn();
                zhishuShopGoods.setIsbn(isbn);
            }
            // 处理品相码
            double conditionCode = Math.round(data.getConditionCode().doubleValue()) / 10.0;
            String conditionCodeString = CnumberUtils.getConditionCode(conditionCode);
            zhishuShopGoods.setConditionCode(conditionCodeString);
            // 处理库存
            zhishuShopGoods.setInventory(Long.valueOf(data.getInventory()));
            // 更新数据
            baseMapper.updateById(zhishuShopGoods);
            successList.add(data);
        }
    }

}
