package com.xtd.project.activiti.event.listener;

import com.xtd.common.utils.SpringUtil;
import com.xtd.common.utils.StringUtils;
import com.xtd.project.activiti.service.impl.LeaveNewServiceImpl;
import com.xtd.project.assets.domain.DbAssetsStock;
import com.xtd.project.assets.domain.DbAssetsStockIn;
import com.xtd.project.assets.mapper.DbAssetsStockInMapper;
import com.xtd.project.assets.mapper.DbAssetsStockMapper;
import com.xtd.project.assets.mapper.DbAssetsStockOutMapper;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.TaskListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class InputEndListener implements ExecutionListener {
    protected final Logger logger = LoggerFactory.getLogger(LeaveNewServiceImpl.class);

    @Autowired
    private TaskService taskService;

    @Value("${assets.numberName}")
    private String numberName;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        DbAssetsStockMapper dbAssetsStockMapper = SpringUtil.getBean(DbAssetsStockMapper.class);
        String id = delegateExecution.getId();
        DbAssetsStockIn formData =(DbAssetsStockIn)delegateExecution.getVariable("formData");
        DbAssetsStock dbAssetsStock=new DbAssetsStock();
        BeanUtils.copyProperties(formData,dbAssetsStock);
        dbAssetsStock.setaId(null);
        //设置为在库
        dbAssetsStock.setStorageStatus(0L);
        String newNumber = getString(dbAssetsStockMapper);
        dbAssetsStock.setaNumber(newNumber);
        dbAssetsStockMapper.insertDbAssetsStock(dbAssetsStock);
        //设置入库状态为已审核
        DbAssetsStockInMapper dbAssetsStockInMapper = SpringUtil.getBean(DbAssetsStockInMapper.class);
        formData.setState(2);
        //资产编号
        formData.setaNumber(newNumber);
        dbAssetsStockInMapper.updateDbAssetsStockIn(formData);
        logger.info("新增入库信息");
    }

    private String getString(DbAssetsStockMapper dbAssetsStockMapper) {
        String number = dbAssetsStockMapper.selectNumber();
        if (StringUtils.isNull(number)) {
            number = numberName;
        }
        String[] split = number.split("-");
        String head = split[0];
        Long tailNum = Long.valueOf(split[1]);
        tailNum = tailNum + 1;
        String format = String.format("%08d", tailNum);
        return head +"-"+ format;
    }

}
