package com.steerinfo.meterwork.meterworkmeasuringinstrumentsecond.service.impl;

import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import com.steerinfo.meterwork.meterworkmeasuringinstrument.model.MeterWorkMeasuringInstrument;
import com.steerinfo.meterwork.meterworkmeasuringinstrumentsecond.mapper.MeterWorkMeasuringInstrumentSecondMapper;
import com.steerinfo.meterwork.meterworkmeasuringinstrumentsecond.model.MeterWorkMeasuringInstrumentSecond;
import com.steerinfo.meterwork.meterworkmeasuringinstrumentsecond.service.IMeterWorkMeasuringInstrumentSecondService;
import com.steerinfo.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * MeterWorkMeasuringInstrumentSecond服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2023-02-24 09:12
 * 类描述
 * 修订历史：
 * 日期：2023-02-24
 * 作者：generator
 * 参考：
 * 描述：MeterWorkMeasuringInstrumentSecond服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "meterWorkMeasuringInstrumentSecondService")
public class MeterWorkMeasuringInstrumentSecondServiceImpl extends BaseServiceImpl<MeterWorkMeasuringInstrumentSecond, String> implements IMeterWorkMeasuringInstrumentSecondService {

    @Resource
    private MeterWorkMeasuringInstrumentSecondMapper meterWorkMeasuringInstrumentSecondMapper;

    @Override
    protected IBaseMapper<MeterWorkMeasuringInstrumentSecond, String> getMapper() {
        return meterWorkMeasuringInstrumentSecondMapper;
    }

    @Override
    public PageList<MeterWorkMeasuringInstrumentSecond> likeDesc(HashMap<String, Object> params, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkMeasuringInstrumentSecond> rows = meterWorkMeasuringInstrumentSecondMapper.likeDesc(params);
        PageList pageInfo = new PageList(rows);
        return pageInfo;
    }

    @Override
    public List<String> getCreateManNo(HashMap<String, Object> params) {
        List<String> rows = meterWorkMeasuringInstrumentSecondMapper.getCreateManNo(params);
        return rows;
    }

    @Override
    public String checkandadd(MeterWorkMeasuringInstrumentSecond model) {
        if (StringUtils.isEmpty(model.getRailwayNo())) {
            return "车号不能为空";
        }
        if (StringUtils.isEmpty(model.getMatterName())){
            return "物资名称不能为空";
        }
        if(model.getNetWeight() == null){
            return "净重不能为空";
        }
        if(model.getGrossWeight() == null){
            return "毛重不能为空";
        }
        if(model.getTareWeight() == null){
            return "皮重不能为空";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String afl = sdf.format(new Date());
        String actualFirstNo = sdf.format(new Date()) + meterWorkMeasuringInstrumentSecondMapper.getNewID(afl);
        UserPayload payload = UserPayload.getCurrUser();
        String userName = payload.getUserName();
//            String userId = "admin";
//            String userName = "admins";
        model.setGrossWeight(model.getGrossWeight().multiply(new BigDecimal(1000)));
        model.setTareWeight(model.getTareWeight().multiply(new BigDecimal(1000)));
        if(model.getGrossWeight().compareTo(model.getTareWeight()) == -1){
            return "毛重小于皮重";
        }
        model.setNetWeight(model.getGrossWeight().subtract(model.getTareWeight()));
        model.setCreateManName(userName);
        model.setCreateTime(new Date());
        model.setActualNo(actualFirstNo);
        meterWorkMeasuringInstrumentSecondMapper.insertSelective(model);
        return "";
    }

    @Override
    public RESTfulResult batchAddInfo(List<MeterWorkMeasuringInstrumentSecond> models) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        UserPayload payload = UserPayload.getCurrUser();
        String userId = payload.getUserCode();
        String userName = payload.getUserName();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        int count = 0;

        for(MeterWorkMeasuringInstrumentSecond model : models) {
            if (StringUtils.isEmpty(model.getRailwayNo())) {
                rm.setMessage("车号不能为空");
                return rm;
            }else {
                Pattern pattern2 = Pattern.compile("[0-9]*");
                Matcher matcher2 = pattern2.matcher(model.getRailwayNo());
                if (!matcher2.matches()) {
                    rm.setMessage("火车号包含字母或者其他特殊字符");
                    return rm;
                }
            }
            if (StringUtils.isEmpty(model.getMatterName())){
                rm.setMessage("物资名称不能为空");
                return rm;
            }
            if(model.getForwardingUnitName() == null){
                rm.setMessage("发货单位名称不能为空");
                return rm;
            }
            if(model.getReceivingUintName() == null){
                rm.setMessage("收货单位名称不能为空");
                return rm;
            }
            if(model.getCarrierUnitName() == null){
                rm.setMessage("录入单位名称不能为空");
                return rm;
            }
            if(model.getNetWeight() == null){
                rm.setMessage("净重不能为空");
                return rm;
            }
            if(model.getGrossWeight() == null){
                rm.setMessage("毛重不能为空");
                return rm;
            }
            if(model.getTareWeight() == null){
                rm.setMessage("皮重不能为空");
                return rm;
            }
        }
        Random random = new Random();
        for(int i = 0; i <= models.size()-1; i++) {
            String afl = sdf.format(new Date());
            String no = meterWorkMeasuringInstrumentSecondMapper.getNewID(afl);
            models.get(i).setActualNo(afl+ no);
            models.get(i).setGrossWeight(models.get(i).getGrossWeight().multiply(new BigDecimal(1000)));
            models.get(i).setTareWeight(models.get(i).getTareWeight().multiply(new BigDecimal(1000)));
            models.get(i).setNetWeight(models.get(i).getNetWeight().multiply(new BigDecimal(1000)));
            models.get(i).setCarrierUnitName(models.get(0).getCarrierUnitName());
            if(i == 0) {
                if(models.get(i).getGrossTime() == null){
                    rm.setMessage("毛重时间不能为空");
                    return rm;
                }
                if(models.get(i).getTareTime() == null){
                    rm.setMessage("皮重时间不能为空");
                    return rm;
                }
                if(models.get(i).getGrossTime().compareTo(models.get(i).getTareTime()) > 0) {
                    models.get(i).setNetTime(models.get(i).getGrossTime());
                }else {
                    models.get(i).setNetTime(models.get(i).getTareTime());
                }
                models.get(i).setGrossTime(new Date(sdfDate.format(models.get(i).getGrossTime())));
                models.get(i).setTareTime(new Date(sdfDate.format(models.get(i).getTareTime())));
//                models.get(i).setNetTime(new Date(sdfDate.format(models.get(i).getNetTime())));
            }else {
                Calendar grossTime = Calendar.getInstance();
                Calendar tareTime = Calendar.getInstance();
                Calendar netTime = Calendar.getInstance();
                grossTime.setTime(models.get(i-1).getGrossTime());
                grossTime.add(Calendar.MINUTE, 2);
                grossTime.add(Calendar.SECOND, random.nextInt(60));
                tareTime.setTime(models.get(i-1).getTareTime());
                tareTime.add(Calendar.MINUTE, 2);
                tareTime.add(Calendar.SECOND, random.nextInt(60));
                netTime.setTime(models.get(i-1).getNetTime());
                netTime.add(Calendar.MINUTE, 2);
                netTime.add(Calendar.SECOND, random.nextInt(60));
                models.get(i).setGrossTime(new Date(sdfDate.format(grossTime.getTime())));
                models.get(i).setTareTime(new Date(sdfDate.format(tareTime.getTime())));
                if(models.get(i).getGrossTime().compareTo(models.get(i).getTareTime()) > 0) {
                    models.get(i).setNetTime(models.get(i).getGrossTime());
                }else {
                    models.get(i).setNetTime(models.get(i).getTareTime());
                }
            }
            models.get(i).setUpdateManNo(userId);
            models.get(i).setUpdateManName(userName);
            models.get(i).setUpdateTime(new Date());
            models.get(i).setCreateManName(userName);
            models.get(i).setCreateTime(new Date());
            models.get(i).setValueFlag("1");
            meterWorkMeasuringInstrumentSecondMapper.insertSelective(models.get(i));
            count ++;
        }
        rm.setSucceed(true);
        rm.setMessage("操作成功，总共" + count + "条数据批量导入成功");
        return rm;
    }

    @Override
    public RESTfulResult batchDeleteInfo(List<MeterWorkMeasuringInstrumentSecond> models) {
        RESTfulResult rm = new RESTfulResult();
        try{
            int count = 0;
            UserPayload payload = UserPayload.getCurrUser();
            String userId = payload.getUserCode();
            String userName = payload.getUserName();
            for(MeterWorkMeasuringInstrumentSecond model: models) {
                model.setValueFlag("0");
                model.setUpdateManNo(userId);
                model.setUpdateManName(userName);
                model.setUpdateTime(new Date());
                model.setNote("数据作废");
                meterWorkMeasuringInstrumentSecondMapper.updateByPrimaryKeySelective(model);
                count++;
            }
            rm.setSucceed(true);
            rm.setMessage("操作成功，总共" + count + "条数据批量作废成功");
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            rm.setFailed();
            rm.setMessage("操作失败：" + e.getMessage());
        }
        return rm;
    }
}
