package com.zhyc.module.frozen.service.impl;

import java.util.HashSet;
import java.util.List;

import com.zhyc.common.utils.DateUtils;
import com.zhyc.module.frozen.domain.DdFe;
import com.zhyc.module.frozen.domain.DdFs;
import com.zhyc.module.frozen.service.IDdFeService;
import com.zhyc.module.frozen.service.IDdFsService;
import lombok.val;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Set;

import com.zhyc.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.zhyc.module.frozen.domain.DdSaleItem;
import com.zhyc.module.frozen.mapper.DdSaleMapper;
import com.zhyc.module.frozen.domain.DdSale;
import com.zhyc.module.frozen.service.IDdSaleService;

/**
 * 销售主单Service业务层处理
 *
 * @author HashMap
 * @date 2025-12-01
 */
@Service
public class DdSaleServiceImpl implements IDdSaleService {
    private final DdSaleMapper ddSaleMapper;

    private final IDdFeService ddFeService;
    private final IDdFsService ddFsService;

    public DdSaleServiceImpl(DdSaleMapper ddSaleMapper, IDdFeService ddFeService, IDdFsService ddFsService) {
        this.ddSaleMapper = ddSaleMapper;
        this.ddFeService = ddFeService;
        this.ddFsService = ddFsService;
    }

    /**
     * 查询销售主单
     *
     * @param id 销售主单主键
     * @return 销售主单
     */
    @Override
    public DdSale selectDdSaleById(Long id) {
        return ddSaleMapper.selectDdSaleById(id);
    }

    /**
     * 查询销售主单列表
     *
     * @param ddSale 销售主单
     * @return 销售主单
     */
    @Override
    public List<DdSale> selectDdSaleList(DdSale ddSale) {
        return ddSaleMapper.selectDdSaleList(ddSale);
    }

    /**
     * 新增销售主单
     *
     * @param ddSale 销售主单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDdSale(DdSale ddSale) {
        ddSale.setCreateTime(DateUtils.getNowDate());
        int rows = ddSaleMapper.insertDdSale(ddSale);
        List<DdSaleItem> ddSaleItemList = ddSale.getDdSaleItemList();
        // 同步后写入
        ddSale.setDdSaleItemList(syncMateData(ddSaleItemList));
        updateStock(ddSaleItemList, -1);
        insertDdSaleItem(ddSale);
        return rows;
    }

    /**
     * 修改销售主单
     * 若依主子表更新逻辑为先删除所有子项，再填充更新项
     * 必须先批量恢复库存再执行插入操作完成更新
     *
     * @param ddSale 销售主单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDdSale(DdSale ddSale) {
        DdSale originalData = selectDdSaleById(ddSale.getId());
        List<DdSaleItem> originalDataSaleItemList = originalData.getDdSaleItemList();
        // 恢复库存
        updateStock(originalDataSaleItemList, 1);
        ddSaleMapper.deleteDdSaleItemBySaleId(ddSale.getId());
        // 更新元信息
        ddSale.setDdSaleItemList(syncMateData(ddSale.getDdSaleItemList()));
        insertDdSaleItem(ddSale);
        return ddSaleMapper.updateDdSale(ddSale);
    }

    /**
     * 批量删除销售主单
     *
     * @param ids 需要删除的销售主单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDdSaleByIds(Long[] ids) {
        // 删除前同步数据
        for (Long id : ids) {
            DdSale ddSale = selectDdSaleById(id);
            updateStock(ddSale.getDdSaleItemList(), 1);
        }
        ddSaleMapper.deleteDdSaleItemBySaleIds(ids);
        return ddSaleMapper.deleteDdSaleByIds(ids);
    }

    /**
     * 删除销售主单信息
     *
     * @param id 销售主单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDdSaleById(Long id) {
        DdSale ddSale = selectDdSaleById(id);
        if (ddSale != null) {
            // 删除前更新库存
            updateStock(ddSale.getDdSaleItemList(), 1);
        }
        ddSaleMapper.deleteDdSaleItemBySaleId(id);
        return ddSaleMapper.deleteDdSaleById(id);
    }

    /**
     * 新增销售明细信息
     *
     * @param ddSale 销售主单对象
     */
    public void insertDdSaleItem(DdSale ddSale) {
        List<DdSaleItem> ddSaleItemList = ddSale.getDdSaleItemList();
        Long id = ddSale.getId();
        // Set 检查重复项
        Set<String> replaceVal = new HashSet<>();
        if (StringUtils.isNotNull(ddSaleItemList)) {
            List<DdSaleItem> list = new ArrayList<DdSaleItem>();
            // 插入前更新库存
            updateStock(ddSaleItemList, -1);
            for (DdSaleItem ddSaleItem : ddSaleItemList) {
                ddSaleItem.setSaleId(id);
                list.add(ddSaleItem);
                if (!replaceVal.contains(ddSaleItem.getItemCode())) {
                    replaceVal.add(ddSaleItem.getItemCode());
                } else {
                    throw new RuntimeException("存在重复项");
                }
            }
            if (!list.isEmpty()) {
                ddSaleMapper.batchDdSaleItem(list);
            }
        }
    }

    /**
     *
     * @param ddSaleItemList 销售子项列表
     * @param type           更新类型 1 入库 -1 出库
     */
    public void updateStock(List<DdSaleItem> ddSaleItemList, long type) {
        if (ddSaleItemList == null || type != 1 && type != -1) {
            throw new RuntimeException("错误数据");
        }
        String status = type == 1 ? "正常" : "销售";
        for (DdSaleItem ddSaleItem : ddSaleItemList) {
            if (ddSaleItem.getItemType().equals("embryo")) {
                DdFe fe = new DdFe();
                fe.setCode(ddSaleItem.getItemCode());
                fe.setId(ddFeService.selectDdFeList(fe).get(0).getId());
                fe.setStatus(status);
                ddFeService.updateDdFe(fe);
            }
            if (ddSaleItem.getItemType().equals("semen")) {
                DdFs fs = new DdFs();
                fs.setCode(ddSaleItem.getItemCode());
                fs.setId(ddFsService.selectDdFsList(fs).get(0).getId());
                fs.setStat(status);
                ddFsService.updateDdFs(fs);
            }
        }
    }

    public List<DdSaleItem> syncMateData(List<DdSaleItem> ddSaleItemList) {
        for (DdSaleItem saleItem : ddSaleItemList) {
            if (saleItem.getItemType().equals("embryo")) {
                DdFe query = new DdFe();
                query.setCode(saleItem.getItemCode());
                DdFe result = ddFeService.selectDdFeList(query).get(0);
                if (result == null || result.getStatus().equals("1")) {
                    throw new RuntimeException("不存在的项");
                }
                // 同步销售项信息
                saleItem.setQty(result.getQty());
                saleItem.setBucketId(result.getBucketId());
                saleItem.setTankId(result.getTankId());
                saleItem.setRackId(result.getRackId());
            } else if (saleItem.getItemType().equals("semen")) {
                DdFs query = new DdFs();
                query.setCode(saleItem.getItemCode());
                DdFs result = ddFsService.selectDdFsList(query).get(0);
                if (result == null || result.getStat().equals("1")) {
                    throw new RuntimeException("不存在的项");
                }
                // 同步销售项信息
                saleItem.setQty(result.getQty());
                saleItem.setBucketId(result.getBucketId());
                saleItem.setTankId(result.getTankId());
                saleItem.setRackId(result.getRackId());
            }

        }
        return ddSaleItemList;
    }
}
