package com.ruoyi.web.v2.v1.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.domain.EntranceBatch;
import com.ruoyi.app.domain.Pigpen;
import com.ruoyi.app.domain.ProductCategory;
import com.ruoyi.app.domain.Purchaser;
import com.ruoyi.app.mapper.EntranceBatchMapper;
import com.ruoyi.app.mapper.PigpenMapper;
import com.ruoyi.app.mapper.ProductCategoryMapper;
import com.ruoyi.app.mapper.PurchaserMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.v2.v1.entity.*;
import com.ruoyi.web.v2.v1.entity.vo.HarmlessVo;
import com.ruoyi.web.v2.v1.entity.vo.ProductionVo;
import com.ruoyi.web.v2.v1.mapper.*;
import com.ruoyi.web.v2.v1.service.IJsDistributionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.v2.v1.utils.PaginationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * <p>
 * v2.0分销登记 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-26
 */
@Service
public class JsDistributionServiceImpl extends ServiceImpl<JsDistributionMapper, JsDistribution> implements IJsDistributionService {

    @Autowired
    private JsDistributionMapper distributionMapper;
    @Autowired
    private JsDivideCircleMapper circleMapper;
    @Autowired
    private PigpenMapper pigpenMapper;
    @Autowired
    private EntranceBatchMapper entranceBatchMapper;
    @Autowired
    private PurchaserMapper purchaserMapper;
    @Autowired
    private ProductCategoryMapper categoryMapper;
    @Autowired
    private JsProduceCodeMapper produceCodeMapper;

    @Override
    public AjaxResult add(JsDistribution distribution) {
        Integer supplierId = distribution.getSupplierId();
//        QueryWrapper<JsDivideCircle> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("supplier_id", supplierId);
//        List<JsDivideCircle> divideCircles = circleMapper.selectList(queryWrapper);
//        for (JsDivideCircle divideCircle : divideCircles) {
//            Pigpen pigpen = pigpenMapper.selectPigpenById(divideCircle.getPigpenId().longValue());
//            pigpen.setIsUse(0);
//            pigpenMapper.updatePigpen(pigpen);
//        }
        UUID uuid = UUID.randomUUID();
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        String shortUUID = Base64.getUrlEncoder().withoutPadding().encodeToString(bb.array());
        JsProduceCode jsProduceCode = new JsProduceCode();
        jsProduceCode.setCreateTime(new Date());
        jsProduceCode.setOneCode(shortUUID);
        distribution.setOneCode(shortUUID);
        produceCodeMapper.insert(jsProduceCode);
        distributionMapper.insert(distribution);
        return success();
    }

    @Override
    public AjaxResult edit(JsDistribution distribution) {
        distributionMapper.updateById(distribution);
        return success();
    }

    @Override
    public AjaxResult delete(String ids) {
        String[] split = ids.split(",");
        for (String s : split) {
            JsDistribution jsDistribution = distributionMapper.selectById(s);
            QueryWrapper<JsProduceCode> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("one_code", jsDistribution.getOneCode());
            produceCodeMapper.delete(queryWrapper);
            distributionMapper.deleteById(s);
        }
        return success();
    }

    @Override
    public AjaxResult page(Integer pageNum, Integer pageSize, String startTime, String endTime, String supplierName, String purchaserName, Integer animalCertNo) {
        Page<JsDistribution> page = new Page<>(pageNum, pageSize);
        QueryWrapper<JsDistribution> queryWrapper = new QueryWrapper<>();
        if ("".equals(startTime) || null == startTime) {

        } else {
            queryWrapper.between("distribution_time", startTime + " 00:00:00", endTime + " 23:59:59");
        }

        queryWrapper.like(StringUtils.isNotEmpty(supplierName), "supplier_id", supplierName);
        queryWrapper.eq(StringUtils.isNotEmpty(purchaserName), "purchaser_name", purchaserName);

        if (null != animalCertNo) {
            queryWrapper.eq("animalCert_no", animalCertNo);
        }
        queryWrapper.orderByDesc("distribution_time");
        return success(distributionMapper.selectPage(page, queryWrapper));
    }

    @Override
    public AjaxResult listAll() {
        return success(distributionMapper.selectList(null));
    }

    @Override
    public PaginationUtil.PageResult<JsProduction> productionPage(Integer pageNum, Integer pageSize, String startTime, String endTime, String animalCertNo) {
        QueryWrapper<JsDistribution> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(animalCertNo), "animal_cert_no", animalCertNo).groupBy("supplier_name,purchaser_name");
        if ("".equals(startTime) || null == startTime) {

        } else {
            queryWrapper.between("distribution_time", startTime + " 00:00:00", endTime + " 23:59:59");
        }
        queryWrapper.orderByDesc("distribution_time");
        List<JsDistribution> jsDistributions = distributionMapper.selectList(queryWrapper);
        List<JsProduction> productions = new ArrayList<>();
        for (JsDistribution jsDistribution : jsDistributions) {
            JsProduction jsProduction = new JsProduction();
            jsProduction.setOneCode(jsDistribution.getOneCode());
            jsProduction.setCreateTime(jsDistribution.getDistributionTime());
            jsProduction.setSupplierName(jsDistribution.getSupplierName());
            jsProduction.setPurchaserName(jsDistribution.getPurchaserName());
            jsProduction.setAnimalCertNo(jsDistribution.getAnimalCertNo());
            QueryWrapper<JsProduceCode> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("one_code", jsDistribution.getOneCode());
            JsProduceCode jsProduceCode = produceCodeMapper.selectOne(queryWrapper1);
            if (ObjectUtil.isNotEmpty(jsProduceCode)) {
                jsProduction.setAnimalCert(jsProduceCode.getAnimalCert());
                jsProduction.setMeatCert(jsProduceCode.getMeatCert());
            }
            Purchaser purchaser = purchaserMapper.selectPurchaserById((long) jsDistribution.getPurchaserId());
            jsProduction.setSalePlace(purchaser.getSalePlace());
            EntranceBatch entranceBatch = entranceBatchMapper.selectEntranceBatchById(jsDistribution.getEntranceBatchId().longValue());
            if (ObjectUtil.isNotEmpty(entranceBatch)) {
                jsProduction.setAmount(entranceBatch.getAmount());
                jsProduction.setVariety(entranceBatch.getVariety());
            }
            List<ProductionVo> list = new ArrayList<>();
            if ("".equals(startTime) || null == startTime) {
                list = distributionMapper.getAllList1(jsDistribution.getPurchaserName(), null, null,jsDistribution.getSupplierName());
            } else {
                list = distributionMapper.getAllList1(jsDistribution.getPurchaserName(), startTime + " 00:00:00", endTime + " 23:59:59",jsDistribution.getSupplierName());
            }
            jsProduction.setProductionVos(list);
            productions.add(jsProduction);
        }
        return PaginationUtil.paginate(productions, pageNum, pageSize);
    }

    @Override
    public AjaxResult editProduce(JsProduceCode jsProduceCode) {
        QueryWrapper<JsProduceCode> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("purchaser_name",jsProduceCode.getPurchaserName()).eq("supplier_name",jsProduceCode.getSupplierName());
        List<JsProduceCode> jsProduceCodes = produceCodeMapper.selectList(queryWrapper1);
        for (JsProduceCode produceCode : jsProduceCodes) {
            if ("".equals(produceCode.getAnimalCert()) || null == produceCode.getAnimalCert()) {

            } else {
                produceCode.setAnimalCert(jsProduceCode.getAnimalCert());
                produceCode.setMeatCert(jsProduceCode.getMeatCert());
                produceCodeMapper.updateById(produceCode);
            }

        }
        return success();
    }
}
