package com.qmth.sop.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBDelayWarn;
import com.qmth.sop.business.entity.TBDelayWarnDetail;
import com.qmth.sop.business.mapper.TBDelayWarnDetailMapper;
import com.qmth.sop.business.service.TBDelayWarnDetailService;
import com.qmth.sop.business.service.TBDelayWarnService;
import com.qmth.sop.common.enums.DelayWarnStatusEnum;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.FieldUniqueEnum;
import com.qmth.sop.common.util.ResultUtil;
import com.qmth.sop.common.util.ServletUtil;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 延期预警明细表 服务实现.
 *
 * @author: shudonghui
 * @date: 2023-08-08 16:02:22
 * @version: 1.0
 * @email: shudonghui@qmth.com.cn
 * @Company: www.qmth.com.cn
 */
@Service
public class TBDelayWarnDetailServiceImpl extends ServiceImpl<TBDelayWarnDetailMapper, TBDelayWarnDetail> implements TBDelayWarnDetailService{

		@Resource
		TBDelayWarnService tBDelayWarnService;
		/**
		* 新增修改延期预警明细表
		*
		* @param tBDelayWarnDetail
		*/
		@Override
		@Transactional
		public Boolean saveTBDelayWarnDetail(TBDelayWarnDetail tBDelayWarnDetail) {
			try {
				SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
				if (Objects.isNull(tBDelayWarnDetail.getId())) {// 新增
					tBDelayWarnDetail.setCreateId(sysUser.getId());
					tBDelayWarnDetail.setCreateTime(System.currentTimeMillis());
					TBDelayWarn tbDelayWarn = tBDelayWarnService.getById(tBDelayWarnDetail.getDelayWarnId());
					if(tbDelayWarn.getStatus()!=DelayWarnStatusEnum.FOLLOW) {
						tbDelayWarn.setStatus(DelayWarnStatusEnum.FOLLOW);
						tBDelayWarnService.saveTBDelayWarn(tbDelayWarn);
					}
				} else { // 修改
					//tBDelayWarnDetail.updateInfo(sysUser.getId());
				}
				return saveOrUpdate(tBDelayWarnDetail);
			} catch (Exception e) {
				if (e instanceof DuplicateKeyException) {
				String errorColumn = e.getCause().toString();
				String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
				throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
				} else if (e instanceof ApiException) {
                    ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
				} else {
				ResultUtil.error(e.getMessage());
				}
			}
			return null;

		}

	@Override
	public List<TBDelayWarnDetail> list(long id) {
		return this.baseMapper.list(id);
	}


}