/*
 * 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.oauth.util.SecurityUtils;
import com.tofly.common.service.IFileInfoService;
import com.tofly.stocks.dto.DeviceTransInfoDto;
import com.tofly.stocks.dto.DeviceTransInfoQuery;
import com.tofly.stocks.entity.*;
import com.tofly.stocks.service.DeviceTransDetailService;
import com.tofly.stocks.service.DeviceTransInfoService;
import com.tofly.stocks.service.StockInfoService;
import com.tofly.stocks.vo.DeviceTransDetailVo;
import com.tofly.stocks.vo.DeviceTransInfoVo;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.tofly.stocks.mapper.DeviceTransInfoMapper;

/**
 * 设备转移信息表
 *
 * @author admin
 * @date Fri Nov 25 00:00:00 CST 2022
 */
@Service("deviceTransInfoService")
public class DeviceTransInfoServiceImpl extends ServiceImpl<DeviceTransInfoMapper, DeviceTransInfo> implements DeviceTransInfoService {

	
	@Autowired
    private IFileInfoService fileInfoService;
    
    @Autowired
    private DeviceTransDetailService deviceTransDetailService;
    
    @Value("${flow.ftp.stocks.deviceTrans}")
    private String path;
    
    @Autowired
    private StockInfoService stockInfoService;
	
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveDeviceTransInfo(DeviceTransInfoDto deviceTransInfoDto, List<MultipartFile> files) {
		Boolean flag =false;
        if (CollectionUtils.isEmpty(deviceTransInfoDto.getDeviceTransDetail())) {
            throw new RuntimeException("转移明细单数据不能为空");
        }
        DeviceTransInfo data = new DeviceTransInfo();
        BeanUtils.copyProperties(deviceTransInfoDto, data);

        data.setRecordUserId(SecurityUtils.getUserId()); //默认入库人为当前登录人
        data.setRecordTime(new Date());
        //附件
        data.setAnnex(fileInfoService.uploadFiles(files,data.getAnnex()
                ,data.getAnnex(),path,"TF_STOCKS_DEVICE_TRANS_INFO"));

       if(data.getDeviceType()==null || data.getDeviceType()==0){
           data.setDeviceType(62002L);//固定为设备
       }
        flag = this.save(data);
        //保存入库明细数据

        for (DeviceTransDetail deviceTransDetail : deviceTransInfoDto.getDeviceTransDetail()){
        	deviceTransDetail.setTransferInfoId(data.getId());
        	deviceTransDetailService.save(deviceTransDetail);
        }
        if(data.getTransStatus()==2){  //已确认的
            AddStockInfo(deviceTransInfoDto.getDeviceTransDetail()); //加入库存
        }
        return flag;
	}
	
	
	/**
     * 更改库存
     * @param deviceTransDetails
     */
    private  void  AddStockInfo(List<DeviceTransDetailVo> deviceTransDetails){

    	for (DeviceTransDetail detail: deviceTransDetails) {
        	StockInfo existStockInfo = stockInfoService.getById(detail.getStockInfoId());
        	if(null == existStockInfo) {
        		 throw new RuntimeException("所选设备没有对应的库存，不能转移");
        	}
            if(existStockInfo.getStockNum()<detail.getTransferNum()){
                 throw new RuntimeException("所选设备转移数量:"+detail.getTransferNum()+"，不能大于当前库存总数:"+existStockInfo.getStockNum());

            }
            StockInfo stockInfo=new StockInfo();
            stockInfo.setId(existStockInfo.getId());
            stockInfo.setTransTotalNum(existStockInfo.getTransTotalNum()+detail.getTransferNum());
            stockInfo.setStockNum(existStockInfo.getStockNum()-detail.getTransferNum());
            stockInfoService.updateById(stockInfo);
        }
    }
	
	

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean editDeviceTransInfo(DeviceTransInfoDto deviceTransInfoDto, List<MultipartFile> files) {
		boolean flag;
		DeviceTransInfo deviceTransInfo = this.getById(deviceTransInfoDto.getId());
        if (deviceTransInfo == null) {
            throw new RuntimeException("修改，参数Id错误");
        }
        if (deviceTransInfo.getTransStatus()==2) {
            throw new RuntimeException("设备转移已确认的数据不能修改");
        }
        if (!deviceTransInfo.getRecordUserId().equals(SecurityUtils.getUserId())) {
            throw new RuntimeException("只能修改自己创建的数据");
        }
        
        DeviceTransInfo data = new DeviceTransInfo();
        BeanUtils.copyProperties(deviceTransInfoDto, data);

        data.setAnnex(fileInfoService.uploadFiles(files,data.getAnnex()
                ,deviceTransInfo.getAnnex(),path,"TF_STOCKS_DEVICE_HANDLE_INFO"));

        flag = this.updateById(data);

        deviceTransDetailService.remove(Wrappers.<DeviceTransDetail>lambdaQuery()
                .eq(DeviceTransDetail::getTransferInfoId,data.getId()));

        for (DeviceTransDetail deviceTransDetail : deviceTransInfoDto.getDeviceTransDetail()) {
        	deviceTransDetail.setTransferInfoId(data.getId());
        	deviceTransDetailService.save(deviceTransDetail);
        }
        if(data.getTransStatus()==2){ //已确认的
            AddStockInfo(deviceTransInfoDto.getDeviceTransDetail());
        }
        return flag;
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
	public boolean deleteByIds(String ids) {
        List<String> lstIds = Arrays.asList(ids.split(","));
        Integer count= this.count(Wrappers.<DeviceTransInfo>lambdaQuery()
                .in(DeviceTransInfo::getId,lstIds)
                        .and(a->a.eq(DeviceTransInfo::getTransStatus,2)
                                .or().ne(DeviceTransInfo::getRecordUserId,SecurityUtils.getUserId()))

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

        //删除明细
        deviceTransDetailService.remove(Wrappers.<DeviceTransDetail>lambdaQuery()
                .in(DeviceTransDetail::getTransferInfoId,lstIds));

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

	@Override
	public Page<DeviceTransInfoVo> getDataPage(Page page, DeviceTransInfoQuery deviceTransInfoQuery) {

        QueryWrapper<DeviceTransInfo> queryWrapper = getDeviceTransInfoQueryWrapper(deviceTransInfoQuery);

        return super.page(page,queryWrapper);
      
	}

    private  QueryWrapper<DeviceTransInfo> getDeviceTransInfoQueryWrapper(DeviceTransInfoQuery deviceTransInfoQuery) {
        QueryWrapper<DeviceTransInfo> queryWrapper=new QueryWrapper<>();
        if(deviceTransInfoQuery.getTransTimeStart()!=null){

            queryWrapper.ge("TRANSFER_TIME", deviceTransInfoQuery.getTransTimeStart());
        }
        if(deviceTransInfoQuery.getTransTimeEnd()!=null){

            queryWrapper.le("TRANSFER_TIME", deviceTransInfoQuery.getTransTimeEnd());
        }

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

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


        if(deviceTransInfoQuery.getTransStatus()!=null && deviceTransInfoQuery.getTransStatus()>0){

            queryWrapper.eq("TRANS_STATUS", deviceTransInfoQuery.getTransStatus());
        }

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

    @Override
	public List<DeviceTransDetail> getDeviceTransDetailByInfoId(Long deviceTransInfoId) {
		return 	deviceTransDetailService.list(Wrappers.<DeviceTransDetail>lambdaQuery()
    			.eq(DeviceTransDetail::getTransferInfoId, deviceTransInfoId));
	}

	


}
