package com.zbf.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbf.common.annotation.DataScope;
import com.zbf.common.annotation.DataSource;
import com.zbf.common.enums.DataSourceType;
import com.zbf.common.exception.ServiceException;
import com.zbf.common.utils.OrderCodeFactory;
import com.zbf.common.utils.SecurityUtils;
import com.zbf.common.utils.StringUtils;
import com.zbf.system.domain.TBaseStorage;
import com.zbf.system.domain.TMiStock;
import com.zbf.system.domain.TMiStockUpdate;
import com.zbf.system.domain.TMiXnStock;
import com.zbf.system.mapper.TMiStockMapper;
import com.zbf.system.mapper.TMiXnStockMapper;
import com.zbf.system.service.ITBaseStorageService;
import com.zbf.system.service.ITMiStockService;
import com.zbf.system.service.ITMiXnStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 库存Service业务层处理
 *
 * @author tony
 * @date 2024-06-12
 */
@Service
public class TMiXnStockServiceImpl extends ServiceImpl<TMiXnStockMapper, TMiXnStock> implements ITMiXnStockService {

    @Autowired
    private TMiXnStockMapper tMiStockMapper;
    @Autowired
    private ITBaseStorageService baseStorageService;

    /**
     * 根据库存ID列表冻结库存
     *
     * @param stockIds 库存ID列表
     * @return 如果更新成功返回true，否则返回false
     */
    public boolean freezeStockByIds(List<String> stockIds, String value) {
        String userNick = SecurityUtils.getUserNick();
        LambdaUpdateWrapper<TMiXnStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiXnStock::getId, stockIds)  // 指定条件：库存ID在提供的列表中
                .set(TMiXnStock::getIsFreeze, "1").set(TMiXnStock::getConsignment, value).set(TMiXnStock::getFrostMan,userNick);// 设置冻结字段为true

        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }

    private List<TBaseStorage> getStorageList(Long deptId) {
        TBaseStorage baseStorage = new TBaseStorage();
        baseStorage.setDeptId(deptId);
        return baseStorageService.selectTBaseStorageList(baseStorage);

    }

    /**
     * 解冻
     *
     * @param ids
     * @return
     */
    @Override
    public boolean thawStockByIds(List<String> ids) {
        LambdaUpdateWrapper<TMiXnStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiXnStock::getId, ids)  // 指定条件：库存ID在提供的列表中
                .set(TMiXnStock::getIsFreeze, "0").
                set(TMiXnStock::getConsignment, "").set(TMiXnStock::getFrostMan, "");

        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }

    /**
     * 批次号修改
     *
     * @param ids
     * @param value
     * @return
     */
    @Override
    public boolean updates(List<String> ids, String value) {
        LambdaUpdateWrapper<TMiXnStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiXnStock::getId, ids)
                .set(TMiXnStock::getBatchNo, value);
        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }


    /**
     * 生产日期修改
     *
     * @param ids
     * @param value
     * @return
     */
    @Override
    public boolean updateDate(List<String> ids, Date value) {
        LambdaUpdateWrapper<TMiXnStock> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(TMiXnStock::getId, ids)
                .set(TMiXnStock::getProductionDate, value);
        // 执行更新操作，返回更新的记录数
        int updatedCount = tMiStockMapper.update(null, updateWrapper);
        return updatedCount > 0;
    }

    @Override
    public boolean updateShelvesNum(TMiXnStock tMiStock) {

        int i = tMiStockMapper.updateShelvesNum(tMiStock);
        return i > 0;
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<TMiXnStock> selectTMiStockList(TMiXnStock tMiStock) {
        return tMiStockMapper.selectTMiStockList(tMiStock);
    }

    @DataScope(deptAlias = "d")
    public List<TMiXnStock> selectTMiStockLists(TMiXnStock tMiStock) {
        // List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
        // if(storageList.size() > 0){
        //     tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
        // }
        return tMiStockMapper.selectTMiStockList(tMiStock);
    }

    @Override
    public List<TMiXnStock> select(TMiXnStock tMiStock) {
        List<TMiXnStock> tMiStocks = tMiStockMapper.selectTMiStockList(tMiStock);
        return tMiStocks;
    }

    @Override
    public String importData(List<TMiXnStock> appList,String s) {
        if (StringUtils.isNull(appList) || appList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TMiXnStock basSku: appList) {
            try {

                //是否存在这个编号
                TMiXnStock tDevices = tMiStockMapper.selectById(basSku.getId());
                if (StringUtils.isNull(tDevices)){
                    tMiStockMapper.insertTMiStock(basSku);
                    successNum++;
                    successMsg.append("<br/>第" + successNum + "行、编号 " + basSku.getId() + " 导入成功");
                }else{
                    basSku.setId(tDevices.getId());
                    tMiStockMapper.updateById(basSku);
                    successNum++;
                    successMsg.append("<br/>第" + successNum + "行、编号 " + basSku.getId() + " 更新成功");
                }
            }catch (Exception e){
                failureNum++;
                String msg = "<br/>第" + failureNum + "行、编号 " + basSku.getId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());

            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    @Override
    public BigDecimal getTotal(TMiXnStock tMiStock) {
   /*     LambdaQueryWrapper<TMiXnStock> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TMiStock::getStorageId,tMiStock.getStorageId())
                .eq(TMiStock::getGoodsId,tMiStock.getGoodsId());
        if(StringUtils.isNotBlank(tMiStock.getStorageAreaId())){
            queryWrapper.eq(TMiStock::getStorageAreaId,tMiStock.getStorageAreaId());
        }

        // 执行查询并计算总金额
        BigDecimal total = tMiStockMapper.selectList(queryWrapper)
                .stream().map(TMiStock::getShelvesNum).
                reduce(BigDecimal.ZERO, BigDecimal::add);*/
        BigDecimal total = selectTMiStockList(tMiStock)
                .stream().map(TMiXnStock::getShelvesNum).
                reduce(BigDecimal.ZERO, BigDecimal::add);


        return total;
    }

    @Override
    public List<TMiXnStock> inventoryStatisticsGoods(TMiXnStock tMiStock) {
        List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
        if (storageList.size() > 0) {
            tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
        }
        return tMiStockMapper.inventoryStatisticsGoods(tMiStock);
    }

    /**
     * 盘点库存查询
     *
     * @param tMiStock
     * @return
     */
    @Override
    public List<TMiXnStock> selectPanGoodsList(TMiXnStock tMiStock) {
        List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
        if (storageList.size() > 0) {
            tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
        }
        return tMiStockMapper.selectPanGoodsList(tMiStock);
    }

    /**
     * 获取当日变化的库位
     *
     * @return
     */
    public List<String> selectPanTimeLocation() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String queryDate = df.format(new Date());
        return tMiStockMapper.selectPanTimeLocation(queryDate);
    }

    @Override
    public int changeLocation(TMiStockUpdate tMiStockUpdate) {
        try {

            for (String s : tMiStockUpdate.getLocal()) {
                TMiXnStock tMiStock = tMiStockMapper.selectOne(new LambdaQueryWrapper<TMiXnStock>().eq(TMiXnStock::getId, s));
                TMiStockUpdate update = new TMiStockUpdate();
                update.setFromLoc(tMiStock.getLocationId());
                update.setToLoc(tMiStockUpdate.getToLoc());
                update.setId(s);
                tMiStockMapper.changeLocation(update);

                /*update.setFromLoc(s);
                tMiStockUpdate.setUpdateTime(new Date());
                tMiStockMapper.changeLocation(update);*/
            }
        } catch (Exception e) {
            return -1;
        }
        return 0;
    }

    @Override
    public List<TMiXnStock> selectTMiStockListByCtl(TMiXnStock tMiStock) {
        return tMiStockMapper.selectTMiStockList(tMiStock);
    }

    @Override
    public int changeCtlNo(TMiStockUpdate tMiStockUpdate) {
        try {
            tMiStockUpdate.setUpdateTime(new Date());
            tMiStockMapper.changeCtlNo(tMiStockUpdate);
        } catch (Exception e) {
            return -1;
        }
        return 0;
    }

    /**
     * 容器拆分修改数量
     *
     * @param tMiStockUpdate
     * @return
     */
    @Override
    public int splitCtlNo(TMiStockUpdate tMiStockUpdate) {
        if (ObjectUtil.isEmpty(tMiStockUpdate.getFromCtlNo()) || ObjectUtil.isEmpty(tMiStockUpdate.getToCtlNo())) {
            return -1;
        }

        for (TMiStock tMiStock : tMiStockUpdate.gettMiStockList()) {
            LambdaUpdateWrapper<TMiXnStock> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(TMiXnStock::getId, tMiStock.getId());
            TMiXnStock old = tMiStockMapper.selectOne(wrapper);

            BigDecimal oldShelvesNum = old.getShelvesNum();
            BigDecimal newShelvesNum = tMiStock.getShelvesNum();

            if (oldShelvesNum.compareTo(newShelvesNum) == 0) {
                // 数量相同，只更新托盘号
                tMiStock.setCtl(tMiStockUpdate.getToCtlNo());
                tMiStock.setUpdateBy(tMiStockUpdate.getUpdateBy());
                tMiStock.setUpdateTime(new Date());
                tMiStockMapper.updateTMiStockSplitCtl(tMiStock);
            } else {
                // 数量不同，进行库存拆分
                BigDecimal difference = oldShelvesNum.subtract(newShelvesNum);
                old.setShelvesNum(difference);
                tMiStockMapper.updateTMiStockNum(old);

                tMiStock.setShelvesNum(newShelvesNum);
                tMiStock.setCtl(tMiStockUpdate.getToCtlNo());
                tMiStock.setUpdateBy(tMiStockUpdate.getUpdateBy());
                tMiStock.setUpdateTime(new Date());
                tMiStock.setId(OrderCodeFactory.getOrderCode("TMI", ""));
                tMiStock.setCreateTime(new Date());
                tMiStock.setCreateBy(tMiStockUpdate.getUpdateBy());
                tMiStockMapper.insertTMiStock(new TMiXnStock());
            }
        }

        return 0;
    }


    @Override
    public List<TMiXnStock> selectCountStockList(TMiXnStock tMiStock) {
//        QueryWrapper<TMiStock> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("status","0");
//        queryWrapper.select("goods_id","goods_name","sum(shelves_num) as shelvesNums").groupBy("goods_id","goods_name");
//        List<TMiStock> tMiStocks = tMiStockMapper.selectList(queryWrapper);
        if (StringUtils.isBlank(tMiStock.getStorageId())) {
            List<TBaseStorage> storageList = getStorageList(tMiStock.getDeptId());
            if (storageList.size() > 0) {
                tMiStock.setStorageList(storageList.stream().map(TBaseStorage::getStorageId).collect(Collectors.toList()));
            }
        }
        return tMiStockMapper.inventoryStatisticsGoods(tMiStock);
    }

    @DataSource(value = DataSourceType.MASTER)
    @Override
    public List<TMiXnStock> overInsured(TMiXnStock tMiStock) {
        QueryWrapper<TMiXnStock> wrapper = new QueryWrapper<>(tMiStock);
        wrapper.isNotNull("mark");
        return list(wrapper);
    }
}
