package com.sunda.spmsoversea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsoversea.dto.SafetyInventorySearchDTO;
import com.sunda.spmsoversea.entity.SafetyInventory;
import com.sunda.spmsoversea.mapper.SafetyInventoryMapper;
import com.sunda.spmsoversea.service.IOverseaOperateLogService;
import com.sunda.spmsoversea.service.ISafetyInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

import static com.sunda.spmsoversea.constant.CommonConstant.SUCCESS;
import static com.sunda.spmsoversea.constant.SafetyInventoryConstant.*;

/**
 * <p>
 * 安全库存表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2022-01-04
 */
@Slf4j
@Service
public class SafetyInventoryServiceImpl extends ServiceImpl<SafetyInventoryMapper, SafetyInventory> implements ISafetyInventoryService {

    @Autowired
    IOverseaOperateLogService iOverseaOperateLogService;

    @Autowired
    SafetyInventoryMapper safetyInventoryMapper;

    @Override
    public IPage getSafetyInventoryPage(SafetyInventorySearchDTO safetyInventorySearchDTO) {
        IPage iPage = safetyInventorySearchDTO.getPage();
        List<Map<String, Object>> mapList = this.baseMapper.getSafetyInventoryPage(iPage, safetyInventorySearchDTO);
        iPage.setRecords(mapList);
        return iPage;
    }

    @Override
    public ResponseResult exportSafetyInventoryDtl(String werks, String materialNo) {
        List<Map<String, Object>> checkResult = this.baseMapper.exportSafetyInventoryDtl(werks, materialNo);        if (checkResult== null){
            return ResponseResult.error("导出数据为空");
        }
        return ResponseResult.success().add("exportSafetyInventoryDtl", checkResult);
    }


    @Override
    public Map<String, Object> getSafetyInventoryInfo(String uuid) {
        return this.baseMapper.getSafetyInventoryInfo(uuid);
    }

    @Override
    public SafetyInventory getSafetyInventory(String uuid) {
        if (StringUtils.isEmpty(uuid)){
            return null;
        }
        return this.baseMapper.selectOne(new QueryWrapper<SafetyInventory>().eq("UUID", uuid));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult createSafetyInventory(SafetyInventory safetyInventory, String userId)throws Exception  {
//        try {
            ResponseResult checkResult = checkCreate(safetyInventory);
            if (checkResult.getCode() != SUCCESS){
                return checkResult;
            }
            String werks = safetyInventory.getWerks();
            String materialNo = safetyInventory.getMaterialNo();
            QueryWrapper<SafetyInventory> queryWrapper = new QueryWrapper<SafetyInventory>().eq("WERKS", werks).eq("MATERIAL_NO", materialNo).eq("SPMS_STATUS", "1");
            SafetyInventory safetyInventory1 = this.baseMapper.selectOne(queryWrapper);
            String uuid = "";
            if (safetyInventory1 == null){
                /** 新建安全库存数据 */
                uuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
                SafetyInventory inventory = new SafetyInventory();
                inventory.setUuid(uuid);
                inventory.setWerks(safetyInventory.getWerks());
                inventory.setWhsLocationCode(safetyInventory.getWhsLocationCode());
                inventory.setMaterialNo(safetyInventory.getMaterialNo());
                inventory.setBasicUnit(safetyInventory.getBasicUnit());
                inventory.setSafetyQtyBasicUnit(safetyInventory.getSafetyQtyBasicUnit() == null ? 0 : safetyInventory.getSafetyQtyBasicUnit());
                inventory.setStandardConsumptionLastYear(safetyInventory.getStandardConsumptionLastYear() == null ? 0 : safetyInventory.getStandardConsumptionLastYear());
                inventory.setSafetyInventoryYear(safetyInventory.getSafetyInventoryYear() == null ? 0.5 : safetyInventory.getSafetyInventoryYear());
                inventory.setEmergencyReserveBasicUnit(safetyInventory.getEmergencyReserveBasicUnit() == null ? 0 : safetyInventory.getEmergencyReserveBasicUnit());
                inventory.setRemarks(safetyInventory.getRemarks());
                inventory.setComments(safetyInventory.getComments());
                inventory.setSpmsStatus("1");
                inventory.setClassify(safetyInventory.getClassify());
                inventory.setCreateUserid(userId);
                inventory.setUpdateUserid(userId);
                this.baseMapper.insert(inventory);
                iOverseaOperateLogService.addOverseaOperateLog(userId, uuid, CREATE_ZH, CREATE_EN, "", CREATE_RU);
                return ResponseResult.success("安全库存数据创建成功").add("safetyInventory", getSafetyInventoryInfo(uuid));
            } else {
                /** 更新安全库存数据 */
                uuid = safetyInventory1.getUuid();
                safetyInventory1.setSafetyQtyBasicUnit(safetyInventory.getSafetyQtyBasicUnit() == null ? 0 : safetyInventory.getSafetyQtyBasicUnit());
                safetyInventory1.setStandardConsumptionLastYear(safetyInventory.getStandardConsumptionLastYear() == null ? 0 : safetyInventory.getStandardConsumptionLastYear());
                safetyInventory1.setSafetyInventoryYear(safetyInventory.getSafetyInventoryYear() == null ? 0.5 : safetyInventory.getSafetyInventoryYear());
                safetyInventory1.setEmergencyReserveBasicUnit(safetyInventory.getEmergencyReserveBasicUnit() == null ? 0 : safetyInventory.getEmergencyReserveBasicUnit());
                safetyInventory1.setRemarks(safetyInventory.getRemarks());
                safetyInventory1.setComments(safetyInventory.getComments());
                safetyInventory1.setSpmsStatus("1");
                safetyInventory1.setClassify(safetyInventory.getClassify());
                safetyInventory1.setUpdateUserid(userId);
                this.baseMapper.update(safetyInventory1, queryWrapper);
                iOverseaOperateLogService.addOverseaOperateLog(userId, uuid, UPDATE_ZH, UPDATE_EN, "", UPDATE_RU);
                return ResponseResult.success("安全库存数据更新成功").add("safetyInventory", getSafetyInventoryInfo(uuid));
            }
//        }catch (Exception e){
//            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return ResponseResult.error("请求更新错误 Exception").add("error", e.getMessage());
//        }
    }

    ResponseResult checkCreate(SafetyInventory safetyInventory){
        if (safetyInventory == null){
            return ResponseResult.error("请求参数不能为空");
        }
        if (StringUtils.isEmpty(safetyInventory.getWerks()) || StringUtils.isEmpty(safetyInventory.getMaterialNo()) ||
                StringUtils.isEmpty(safetyInventory.getBasicUnit()) || safetyInventory.getSafetyQtyBasicUnit() == null){
            return ResponseResult.error("请求参数错误");
        }
        String werks = safetyInventory.getWerks();
        String materialNo = safetyInventory.getMaterialNo();
        QueryWrapper<SafetyInventory> queryWrapper = new QueryWrapper<SafetyInventory>().eq("WERKS", werks).eq("MATERIAL_NO", materialNo).eq("SPMS_STATUS", "1");
        SafetyInventory safetyInventory1 = this.baseMapper.selectOne(queryWrapper);
        if (safetyInventory1 != null){
            if (safetyInventory.getDataVersion() != null && !safetyInventory.getDataVersion().equals(safetyInventory1.getDataVersion())){
                return ResponseResult.error("请求数据已更新，请刷新重试");
            }
        }
        return ResponseResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult deleteSafetyInventory(String uuid, Integer dataVersion, String userId) throws Exception {
//        try {
            if (StringUtils.isEmpty(uuid) || dataVersion == null){
                return ResponseResult.error("请求参数错误");
            }
            QueryWrapper<SafetyInventory> queryWrapper = new QueryWrapper<SafetyInventory>().eq("UUID", uuid);
            SafetyInventory safetyInventory = this.baseMapper.selectOne(queryWrapper);
            if (safetyInventory == null){
                return ResponseResult.error("请求安全库存数据不存在");
            }
            if (!dataVersion.equals(safetyInventory.getDataVersion())){
                return ResponseResult.error("请求数据已更新，请刷新重试");
            }
            /** 存在多个安全库存停用数据时，会影响新增更新功能，此处做真删除； */
            this.baseMapper.delete(queryWrapper);
            //safetyInventory.setSpmsStatus("0");
            //safetyInventory.setUpdateUserid(userId);
            //this.baseMapper.update(safetyInventory, queryWrapper);
            //iOverseaOperateLogService.addOverseaOperateLog(userId, uuid, DELETE_ZH, DELETE_EN, "");
            return ResponseResult.success("安全库存数据删除成功").add("safetyInventory", getSafetyInventoryInfo(uuid));
//        }catch (Exception e){
//            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return ResponseResult.error("请求更新错误 Exception").add("error", e.getMessage());
//        }
    }

    @Override
    public ResponseResult getStandardConsumption(String werks, String materialNo, Integer yearNumber) {
        if (StringUtils.isEmpty(werks) || StringUtils.isEmpty(materialNo) || yearNumber == null){
            return ResponseResult.error("请求参数错误");
        }
        Map<String, Object> standardConsumption = this.baseMapper.getStandardConsumption(werks, materialNo, yearNumber - 1);
        if (standardConsumption == null){
            return ResponseResult.error("查询无耗用记录");
        }
        return ResponseResult.success().add("standardConsumptionLastYear", standardConsumption);
    }

    @Override
    public ResponseResult getBelowSafetyInventory(String werks) {
        if (StringUtils.isEmpty(werks)){
            return ResponseResult.error("请求工厂不允许为空");
        }
        return ResponseResult.success().add("belowSafetyInventoryList", this.baseMapper.getBelowSafetyInventory(werks));
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseResult batchCreateSafety(List<SafetyInventory> safetyList, String userId) {
		for (SafetyInventory saf : safetyList) {
			QueryWrapper<SafetyInventory> queryWrapper = new QueryWrapper<SafetyInventory>().eq("WERKS", saf.getWerks()).eq("MATERIAL_NO", saf.getMaterialNo()).eq("SPMS_STATUS", "1");
			SafetyInventory safetyInventory1 = this.baseMapper.selectOne(queryWrapper);
			// 如果是删除安全库存，直接更新状态
			if ("0".equals(saf.getSpmsStatus())) {
				if (safetyInventory1 != null) {
					saf.setUpdateUserid(userId);
					saf.setUuid(safetyInventory1.getUuid());
					this.baseMapper.updateById(saf);
	                iOverseaOperateLogService.addOverseaOperateLog(userId, safetyInventory1.getUuid(), DELETE_ZH, DELETE_EN, "", DELETE_RU);
				}
			} else {
				if (safetyInventory1 == null) {
					// 新增
					String uuid = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
					saf.setUuid(uuid);
					saf.setCreateUserid(userId);
					saf.setUpdateUserid(userId);
					this.baseMapper.insert(saf);
	                iOverseaOperateLogService.addOverseaOperateLog(userId, uuid, CREATE_ZH, CREATE_EN, "", CREATE_RU);
				} else {
					// 更新
					saf.setUuid(safetyInventory1.getUuid());
					saf.setUpdateUserid(userId);
					this.baseMapper.updateById(saf);
	                iOverseaOperateLogService.addOverseaOperateLog(userId, safetyInventory1.getUuid(), UPDATE_ZH, UPDATE_EN, "", UPDATE_RU);
				}
			}
		}
		return ResponseResult.success();
	}
}


