/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.stocks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.common.service.IFileInfoService;
import com.tofly.stocks.dto.InstockInfoDto;
import com.tofly.stocks.dto.InstockInfoQuery;
import com.tofly.stocks.entity.*;
import com.tofly.stocks.service.InstockDetailService;
import com.tofly.stocks.service.InstockInfoService;
import com.tofly.stocks.service.StockInfoService;
import com.tofly.stocks.vo.InstockDetailVo;
import com.tofly.stocks.vo.InstockInfoVo;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.tofly.stocks.mapper.InstockInfoMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 库存入库信息表
 *
 * @author admin
 * @date Fri Nov 25 00:00:00 CST 2022
 */
@Service("instockInfoService")
public class InstockInfoServiceImpl extends ServiceImpl<InstockInfoMapper, InstockInfo> implements InstockInfoService {
    @Autowired
    private InstockDetailService instockDetailService;
    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private StockInfoService stockInfoService;

    @Value("${flow.ftp.stocks.instock}")
    private String path;

    private String getRkType(Integer type){
        String str="";
         switch (type){
             case 1:
                 str="WZRK";
                 break;
             case 2:
                 str="SBRK";
                 break;
             case 3:
                 str="YPRK";
                 break;
             default:
                 break;
         }
         if(StringUtil.isEmpty(str)){
             throw new RuntimeException("入库类型错误");
         }
        return str;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveInstockInfo(InstockInfoDto instockInfoDto, List<MultipartFile> files) {
        boolean flag;
        if (CollectionUtils.isEmpty(instockInfoDto.getInstockDetails())) {
            throw new RuntimeException("入库明细单数据不能为空");
        }
        String baseNo=getRkType(instockInfoDto.getInstockCategory());

        Date now = new Date(); // 创建一个Date对象，获取当前时间
        String strDateFormat = "yyyyMM";
        String start_no = baseNo + DateFormatUtils.format(now, strDateFormat);
        //获取当天最大的采样编号
        String Sample_No = this.baseMapper.getInstockMaxNo(start_no);

        int firstNum = 1;
        if (Sample_No.length() == 14) {
            firstNum = Integer.parseInt(Sample_No.substring(11)) + 1;
        }

        String end_no = String.format("%04d", firstNum); //补全数字，不足用0补位

        String instockNo = start_no + end_no;

        InstockInfo data = new InstockInfo();
        BeanUtils.copyProperties(instockInfoDto, data);
        data.setInstockNo(instockNo); //赋值单号

        data.setInstockUserId(SecurityUtils.getUserId()); //默认入库人为当前登录人
        data.setInstockDpt(SecurityUtils.getUserDeptId());

        //附件
        data.setAnnex(fileInfoService.uploadFiles(files,data.getAnnex()
                ,data.getAnnex(),path,"TF_STOCKS_INSTOCK_INFO"));

        flag = this.save(data);
        //保存入库明细数据

        for (InstockDetail instockDetail : instockInfoDto.getInstockDetails()){
            instockDetail.setInstockInfoId(data.getId());
            if(instockDetail.getTotalPrice()==null || instockDetail.getTotalPrice()==0){
               double totalPrice=instockDetail.getInstockNum()*instockDetail.getUnitPrice();
               instockDetail.setTotalPrice(totalPrice);
            }
            instockDetail.setCurrentPrice(instockDetail.getInstockNum()*instockDetail.getUnitPrice());
            instockDetailService.save(instockDetail);
        }
        if(data.getInstockStatus()==2){  //已确认的
            AddStockInfo(instockInfoDto.getInstockDetails(),data.getStoreId()); //加入库存
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editInstockInfo(InstockInfoDto instockInfoDto, List<MultipartFile> files) {
        boolean flag;
        InstockInfo instockInfo = this.getById(instockInfoDto.getId());
        if (instockInfo == null) {
            throw new RuntimeException("修改，参数Id错误");
        }
        if (instockInfo.getInstockStatus()==2) {
            throw new RuntimeException("已确认入库的数据不能修改");
        }
        if (!instockInfoDto.getInstockUserId().equals(SecurityUtils.getUserId())) {
            throw new RuntimeException("只能修改自己创建的数据");
        }
        instockInfoDto.setInstockNo(instockInfo.getInstockNo());
        InstockInfo data = new InstockInfo();
        BeanUtils.copyProperties(instockInfoDto, data);

        data.setAnnex(fileInfoService.uploadFiles(files,data.getAnnex()
                ,instockInfo.getAnnex(),path,"TF_STOCKS_INSTOCK_INFO"));

        flag = this.updateById(data);
        
        instockDetailService.remove(Wrappers.<InstockDetail>lambdaQuery()
				.eq(InstockDetail::getInstockInfoId,data.getId()));
        
        for (InstockDetail instockDetail : instockInfoDto.getInstockDetails()) {
            instockDetail.setInstockInfoId(data.getId());
            if(instockDetail.getTotalPrice()==null || instockDetail.getTotalPrice()==0){
                double totalPrice=instockDetail.getInstockNum()*instockDetail.getUnitPrice();
                instockDetail.setTotalPrice(totalPrice);
            }
            instockDetail.setCurrentPrice(instockDetail.getTotalPrice());
            instockDetailService.save(instockDetail);
        }
        if(data.getInstockStatus()==2){  //已确认的
            AddStockInfo(instockInfoDto.getInstockDetails(),data.getStoreId()); //加入库存
        }

        return flag;
    }



    /**
     * 加入库存
     * @param instockDetails
     */
    private  void  AddStockInfo(List<InstockDetailVo> instockDetails, Long storeId){

        for (InstockDetail detail: instockDetails) {
            List<StockInfo> list =new ArrayList<>();
            if(detail.getShelvesId()!=null && detail.getShelvesId()>0) {
                list = stockInfoService.list(Wrappers.<StockInfo>lambdaQuery()
                        .eq(StockInfo::getStoreId, storeId)
                        .eq(StockInfo::getShelvesId, detail.getShelvesId())
                        .eq(StockInfo::getDeviceId, detail.getDeviceId()));
            }
   else{
        	list = stockInfoService.list(Wrappers.<StockInfo>lambdaQuery()
    				.eq(StockInfo::getStoreId,storeId)
    				.eq(StockInfo::getDeviceId,detail.getDeviceId()));
            }

            StockInfo stockInfo=new StockInfo();
           
            if(list.stream().count()>0){
               //修改
               stockInfo.setId(list.get(0).getId());
               stockInfo.setDeviceId(list.get(0).getDeviceId());
               stockInfo.setStoreId(storeId);
               stockInfo.setInstockTotalNum(detail.getInstockNum()+list.get(0).getInstockTotalNum());
               stockInfo.setStockNum(detail.getInstockNum()+list.get(0).getStockNum());

            }else{
               //新增
               stockInfo.setDeviceId(detail.getDeviceId());
                stockInfo.setShelvesId(detail.getShelvesId());
               stockInfo.setStockNum(detail.getInstockNum());
               stockInfo.setInstockTotalNum(detail.getInstockNum());
               stockInfo.setOutstockTotalNum(0D);
               stockInfo.setUsestockTotalNum(0D);
               stockInfo.setTransTotalNum(0D);
               stockInfo.setHandleTotalNum(0D);
               stockInfo.setStoreId(storeId);
            }
            stockInfoService.saveOrUpdate(stockInfo);
            detail.setStockInfoId(stockInfo.getId());
            instockDetailService.updateById(detail);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(String ids) {

        List<String> lstIds = Arrays.asList(ids.split(","));
        Integer count= this.count(Wrappers.<InstockInfo>lambdaQuery()
                .in(InstockInfo::getId,lstIds)
                        .and(a->a.eq(InstockInfo::getInstockStatus,2)
                                .or().ne(InstockInfo::getInstockUserId,SecurityUtils.getUserId()))


        );
        if(count>0){
            throw new RuntimeException("只能删除自己创建的并且没有确认的数据");
        }


        //删除明细
        instockDetailService.remove(Wrappers.<InstockDetail>lambdaQuery()
                .in(InstockDetail::getInstockInfoId,lstIds));

        //删除主表
        return this.removeByIds(lstIds);

    }

    @Override
    public Page<InstockInfoVo> getDataPage(Page page, InstockInfoQuery instockInfoQuery) {
        QueryWrapper<InstockInfo> queryWrapper = getInstockInfoQueryWrapper(instockInfoQuery);
        return super.page(page,queryWrapper);

    }

    /**
     * 查询条件拼接
     * @param instockInfoQuery
     * @return
     */
    private  QueryWrapper<InstockInfo> getInstockInfoQueryWrapper(InstockInfoQuery instockInfoQuery) {
        QueryWrapper<InstockInfo> queryWrapper=new QueryWrapper<>();
        if(instockInfoQuery.getInstockCategory()!=null && instockInfoQuery.getInstockCategory()>0){

            queryWrapper.eq("INSTOCK_CATEGORY", instockInfoQuery.getInstockCategory());
        }
        if(instockInfoQuery.getInstockTimeStart()!=null){

            queryWrapper.ge("INSTOCK_TIME", instockInfoQuery.getInstockTimeStart());
        }
        if(instockInfoQuery.getInstockTimeEnd()!=null){

            queryWrapper.le("INSTOCK_TIME", instockInfoQuery.getInstockTimeEnd());
        }

        if(StringUtil.isNotEmpty(instockInfoQuery.getInstockNo())){

            queryWrapper.like("INSTOCK_NO", instockInfoQuery.getInstockNo());
        }

        if(StringUtil.isNotEmpty(instockInfoQuery.getInvoiceNo())){

            queryWrapper.like("INVOICE_NO", instockInfoQuery.getInvoiceNo());
        }
        if(StringUtil.isNotEmpty(instockInfoQuery.getOrderNo())){

            queryWrapper.like("ORDER_NO", instockInfoQuery.getOrderNo());
        }

        if(StringUtil.isNotEmpty(instockInfoQuery.getSupplier())){

            queryWrapper.like("SUPPLIER", instockInfoQuery.getSupplier());
        }

        if(instockInfoQuery.getBuinessType()!=null && instockInfoQuery.getBuinessType()>0){

            queryWrapper.eq("BUINESS_TYPE", instockInfoQuery.getBuinessType());
        }
        if(instockInfoQuery.getStoreId()!=null && instockInfoQuery.getStoreId()>0){

            queryWrapper.eq("STORE_ID", instockInfoQuery.getStoreId());
        }

        if(instockInfoQuery.getWaterworksId()!=null && instockInfoQuery.getWaterworksId()>0){

            queryWrapper.eq("WATERWORKS_ID", instockInfoQuery.getWaterworksId());
        }

        if(instockInfoQuery.getInstockType()!=null && instockInfoQuery.getInstockType()>0){

            queryWrapper.eq("INSTOCK_TYPE", instockInfoQuery.getInstockType());
        }

        if(instockInfoQuery.getInstockStatus()!=null && instockInfoQuery.getInstockStatus()>0){

            queryWrapper.eq("INSTOCK_STATUS", instockInfoQuery.getInstockStatus());
        }
        if(instockInfoQuery.getPurchaseType()!=null && instockInfoQuery.getPurchaseType()>0){

            queryWrapper.eq("PURCHASE_TYPE", instockInfoQuery.getPurchaseType());
        }


        queryWrapper.orderByDesc("CREATE_TIME");
        return queryWrapper;
    }

}
