/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.stocks.service.impl;
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.stocks.dto.CheckPlanQuery;
import com.tofly.stocks.entity.CheckDetail;
import com.tofly.stocks.entity.CheckPlan;
import com.tofly.stocks.entity.CheckTask;
import com.tofly.stocks.mapper.CheckPlanMapper;
import com.tofly.stocks.service.CheckDetailService;
import com.tofly.stocks.service.CheckPlanService;
import com.tofly.stocks.service.CheckTaskService;
import com.tofly.stocks.vo.CheckPlanVo;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 库存盘点计划表
 *
 * @author zhoux
 * @date Fri Nov 25 00:00:00 CST 2022
 */
@Service("checkPlanService")
public class CheckPlanServiceImpl extends ServiceImpl<CheckPlanMapper, CheckPlan> implements CheckPlanService {
	
	
    @Autowired
    private CheckTaskService checkTaskService;

	@Autowired
	private CheckDetailService checkDetailService;

	@Override
	public Page<CheckPlanVo> getDataPage(Page page, CheckPlanQuery checkPlanQuery) {                
        return page.setRecords(baseMapper.getDataPage(page, checkPlanQuery));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveCheckPlan(CheckPlan checkPlan) throws Exception {
		
		StringBuffer sb =new StringBuffer();
    	SimpleDateFormat year =new SimpleDateFormat("yyyy");
    	SimpleDateFormat month =new SimpleDateFormat("MM");
    	
    	sb.append("PDJH-");
    	sb.append(year.format(new Date())+"-");
    	sb.append(month.format(new Date())+"-");
    	   	
    	List<CheckPlan> checkPalnList = baseMapper.selectList(Wrappers.<CheckPlan>lambdaQuery()
    			.like(CheckPlan::getCheckPlanNo, sb.toString()).orderByDesc(CheckPlan::getCreateTime));
    	
    	if(checkPalnList.size()==0) {
    		sb.append("001");
    	}else {
    		String existPlanNo =checkPalnList.get(0).getCheckPlanNo();
    		String existPlanNoNum= existPlanNo.substring(existPlanNo.lastIndexOf("-")+1,existPlanNo.length());    		
    		Integer saveNum = Integer.valueOf(existPlanNoNum)+1;   		
    		sb.append(String.format("%04d", Integer.valueOf(saveNum)));    		
    	}
    	checkPlan.setCheckPlanNo(sb.toString());
    	checkPlan.setCreateTime(new Date());
		if(checkPlan.getCheckMakeTime()==null){
			checkPlan.setCheckMakeTime(new Date());

		}
		if(checkPlan.getCheckMakeUserId()==null || checkPlan.getCheckMakeUserId()==0){
			checkPlan.setCheckMakeUserId(SecurityUtils.getUserId());

		}
    	baseMapper.insert(checkPlan);
    	CheckTask checkTask = new CheckTask();
        checkTask.setCheckStatus(1);
    	checkTask.setCheckPlanId(checkPlan.getId());
    	checkTaskService.save(checkTask);
    	
    	return true;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteByIds(String ids) {
		List<String> lstIds = Arrays.asList(ids.split(","));
		Integer count= this.count(Wrappers.<CheckPlan>lambdaQuery()
					  .in(CheckPlan::getId,lstIds)
					  .ne(CheckPlan::getCheckMakeUserId,SecurityUtils.getUserId())
			  );
		if(count>0){
			throw new RuntimeException("只能删除制定人自己创建的任务计划");
		}

		  count =checkTaskService.count(Wrappers.<CheckTask>lambdaQuery()
				.in(CheckTask::getCheckPlanId,lstIds)
				.eq(CheckTask::getCheckStatus,2)

		);
		 if(count>0){
			 throw new RuntimeException("只能删除未确认的任务计划");
		 }

		List<CheckTask> list=checkTaskService.list(Wrappers.<CheckTask>lambdaQuery()
				.in(CheckTask::getCheckPlanId,lstIds));
		if(list!=null && list.stream().count()>0){ //删除详情数据
			for (CheckTask checkTask: list
				 ) {
				checkDetailService.remove(Wrappers.<CheckDetail>lambdaQuery()
						.eq(CheckDetail::getCheckTaskId,checkTask.getCheckPlanId()
                  ));
			}

		}
       //删除任务数据
		checkTaskService.remove(Wrappers.<CheckTask>lambdaQuery()
				.in(CheckTask::getCheckPlanId,lstIds));

		//删除计划数据
		return this.removeByIds(lstIds);

	}

	@Override
	public Boolean editCheckPlan(CheckPlan checkPlan){
		Integer count =checkTaskService.count(Wrappers.<CheckTask>lambdaQuery()
				.in(CheckTask::getCheckPlanId,checkPlan.getId())
				.eq(CheckTask::getCheckStatus,2));
		if(count>0){
			throw new RuntimeException("该盘点计划对应的盘点任务已经确认，不能修改");
		}
		return this.updateById(checkPlan);
	}


}