package com.jisco.dynamicweight.dynamicworkauditdata.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Snowflake;
import com.jisco.dynamicweight.dynamicworkauditdata.mapper.DynamicWorkAuditdataMapper;
import com.jisco.dynamicweight.dynamicworkauditdata.model.DynamicWorkAuditdata;
import com.jisco.dynamicweight.dynamicworkauditdata.service.IDynamicWorkAuditdataService;
import com.jisco.dynamicweight.dynamicworkupdata.mapper.DynamicWorkUpdataMapper;
import com.jisco.dynamicweight.dynamicworkupdata.vo.AuditDataVO;
import com.jisco.dynamicweight.pika.service.ICenternetService;
import com.jisco.dynamicweight.util.UserUtil;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.utils.misc.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

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

    @Autowired
    private DynamicWorkAuditdataMapper dynamicWorkAuditdataMapper;

    @Autowired
    private DynamicWorkUpdataMapper dynamicWorkUpdataMapper;

    @Autowired
    private ICenternetService centernetService;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);

    @Override
    protected IBaseMapper<DynamicWorkAuditdata, String> getMapper() {
        return dynamicWorkAuditdataMapper;
    }

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Transactional
    @Override
    public synchronized void audit(String date, List<AuditDataVO> list) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = sdf.parse(date + " 00:00:00");
            endTime = sdf.parse(date + " 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式化错误");
        }
        for (AuditDataVO auditDataVO : list) {
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getMaterialCode()), "物料编码不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getMaterialName()), "物料名称不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getStationCode()), "站点编码不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getStationName()), "站点名称不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getRecieverCode()), "收货库房编码不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getRecieverName()), "收货库房名称不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getRecieverType()), "收货点类型不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getSenderCode()), "发货库房编码不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getSenderName()), "发货库房名称不能为空:" + auditDataVO);
            Assert.isTrue(StringUtils.isNotBlank(auditDataVO.getSenderType()), "发货点类型不能为空:" + auditDataVO);
            Assert.isTrue(Objects.nonNull(auditDataVO.getRzl()), "重量不能为空:" + auditDataVO);
            Assert.isTrue(auditDataVO.getAuditingFlag() !=null && auditDataVO.getAuditingFlag().equals("0"), "数据已审核，不能重复审核！:" + auditDataVO);
            DynamicWorkAuditdata auditdata = new DynamicWorkAuditdata();
            auditdata.setStationCode(auditDataVO.getStationCode());
            auditdata.setStationName(auditDataVO.getStationName());
            auditdata.setMaterialCode(auditDataVO.getMaterialCode());
            auditdata.setMaterialName(auditDataVO.getMaterialName());
            auditdata.setRecieverCode(auditDataVO.getRecieverCode());
            auditdata.setRecieverName(auditDataVO.getRecieverName());
            auditdata.setRecieverType(auditDataVO.getRecieverType());
            auditdata.setSenderCode(auditDataVO.getSenderCode());
            auditdata.setSenderName(auditDataVO.getSenderName());
            auditdata.setSenderType(auditDataVO.getSenderType());
            auditdata.setWeight(auditDataVO.getRzl());
            auditdata.setAuditingManNo(UserUtil.getCurrentUserId());
            auditdata.setAuditingManName(UserUtil.getCurrentUserName());
            auditdata.setAuditingTime(new Date());
            auditdata.setStartTime(startTime);
            auditdata.setEndTime(endTime);
            auditdata.setUploaded("0");
            auditdata.setValidFlag("1");
            auditdata.setAuditingFlag("0");
            auditdata.setCreateManNo(UserUtil.getCurrentUserId());
            auditdata.setCreateManName(UserUtil.getCurrentUserName());
            auditdata.setCreateTime(new Date());
//            BigDecimal weight = dynamicWorkUpdataMapper.getWeightForAuditOrUnaudit(auditdata);
            dynamicWorkUpdataMapper.setAudit(auditdata);
//            Assert.isTrue(weight.compareTo(auditdata.getWeight()) == 0, "数据不一致，请刷新页面并检查数据！");
            auditdata.setAuditingFlag("1");
            dynamicWorkAuditdataMapper.save(auditdata);
        }
    }

    /**
     * 查询上传数据
     *
     * @param auditingTime1
     * @param auditingTime2
     * @return
     */
    @Override
    public List<DynamicWorkAuditdata> getUploadData(String auditingTime1, String auditingTime2) {
        List<DynamicWorkAuditdata> list = dynamicWorkAuditdataMapper.getUploadData(auditingTime1, auditingTime2);
        return list;
    }

    @Transactional
    @Override
    public synchronized void cancelAudit(List<DynamicWorkAuditdata> list) {
        for (DynamicWorkAuditdata dynamicWorkAuditdata : list) {
            Assert.isTrue(dynamicWorkAuditdata.getUploaded().equals("0"), "数据已上传，请先撤销上传:" + dynamicWorkAuditdata);
//            Assert.isTrue(dynamicWorkAuditdata.getAuditingFlag()!=null && dynamicWorkAuditdata.getAuditingFlag().equals("1"), "数据未审核，不能撤销审核:" + dynamicWorkAuditdata);
            dynamicWorkAuditdataMapper.deleteByPrimaryKey(dynamicWorkAuditdata.getId());
//            BigDecimal weight = dynamicWorkUpdataMapper.getWeightForAuditOrUnaudit(dynamicWorkAuditdata);
            dynamicWorkUpdataMapper.setUnAudit(dynamicWorkAuditdata);
//            Assert.isTrue(weight.compareTo(dynamicWorkAuditdata.getWeight()) == 0, "数据不一致，请刷新页面并检查数据！");
        }
    }

//    @Transactional
    @Override
    public synchronized void cancelUpload(List<DynamicWorkAuditdata> list) {
        Assert.isTrue(!CollectionUtils.isEmpty(list), "请选择需要撤销上传的数据!");
//        List<String> ids = new ArrayList<>();
        for (DynamicWorkAuditdata auditdata : list) {
            TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
            try {
                DynamicWorkAuditdata auditdataDb = this.getById(auditdata.getAuditdataNo());
                Assert.isTrue(auditdataDb.getUploaded().equals("1"), "数据未上传，不能撤销上传:" + auditdataDb);
//            ids.add(auditdataDb.getPikaDataId());
                auditdataDb.setUploaded("0");
//            auditdata.setPikaDataId("");
                this.batchUpdate(Arrays.asList(auditdataDb));
                centernetService.cancelUpload(Arrays.asList(auditdataDb.getPikaDataId()));
                platformTransactionManager.commit(transactionStatus);
            } catch (Exception e) {
                platformTransactionManager.rollback(transactionStatus);
//                throw e;
            }
        }
//        this.batchUpdate(list);
//        centernetService.cancelUpload(ids);
    }

//    @Transactional
    @Override
    public synchronized void upload(List<DynamicWorkAuditdata> list) {
        Assert.isTrue(!CollectionUtils.isEmpty(list), "请选择需要上传的数据!");
//        List<DynamicWorkAuditdata> listDB = new ArrayList<>();
        for (DynamicWorkAuditdata auditdata : list) {
            TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
            try {
                DynamicWorkAuditdata auditdataDb = this.getById(auditdata.getAuditdataNo());
                Assert.isTrue(auditdataDb.getUploaded().equals("0"), "数据已上传，不能重复上传:" + auditdata);
                auditdataDb.setUploaded("1");
                auditdataDb.setPikaDataId("DTC" + snowflakeIdWorker.nextId());
//            listDB.add(auditdataDb);
                this.batchUpdate(Arrays.asList(auditdataDb));
                centernetService.upload(Arrays.asList(auditdataDb));
                platformTransactionManager.commit(transactionStatus);
            } catch (Exception e) {
                platformTransactionManager.rollback(transactionStatus);
//                throw e;
            }
        }
//        this.batchUpdate(listDB);
//        centernetService.upload(listDB);
//        int a = 1/0;
    }

    /**
     * 动态秤报表
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<DynamicWorkAuditdata> getCollectData(String startTime, String endTime) {
        List<DynamicWorkAuditdata> list = dynamicWorkAuditdataMapper.getCollectData(startTime, endTime);
        return list;
    }
}
