/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.nh.pojo.entity.AlarmInfoEntity;
import org.springblade.modules.nh.pojo.entity.DeviceEntity;
import org.springblade.modules.nh.service.impl.AlarmInfoServiceImpl;
import org.springblade.modules.operation.mapper.OperationSiteEmployeeMapper;
import org.springblade.modules.operation.pojo.entity.OperationSiteEntity;
import org.springblade.modules.operation.pojo.vo.EmpAuthVo;
import org.springblade.modules.operation.service.impl.OperationSiteServiceImpl;
import org.springblade.modules.order.constant.OrderConstants;
import org.springblade.modules.order.mapper.OperationOrderLetterMapper;
import org.springblade.modules.order.pojo.dto.OperationOrderSettleDTO;
import org.springblade.modules.order.pojo.dto.OrderLetterDTO;
import org.springblade.modules.order.pojo.entity.OperationOrderEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderOperationInfoEntity;
import org.springblade.modules.order.pojo.entity.OperationOrderSettleEntity;
import org.springblade.modules.order.pojo.form.OperationOrderConditionForm;
import org.springblade.modules.order.pojo.vo.OperationOrderSettleVO;
import org.springblade.modules.order.excel.OperationOrderSettleExcel;
import org.springblade.modules.order.mapper.OperationOrderSettleMapper;
import org.springblade.modules.order.service.IOperationOrderSettleService;
import org.springblade.modules.order.utils.Target;
import org.springblade.modules.order.utils.WebPageFunUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 工单结算表 服务实现类
 *
 * @author BladeX
 * @since 2024-06-26
 */
@Service
public class OperationOrderSettleServiceImpl extends ServiceImpl<OperationOrderSettleMapper, OperationOrderSettleEntity> implements IOperationOrderSettleService {

	@Autowired
	OperationOrderServiceImpl orderService;

	@Autowired
	OperationOrderOperationInfoServiceImpl infoService;

	@Autowired
	OperationSiteServiceImpl siteService;
	@Autowired
	OperationSiteEmployeeMapper employeeMapper;
	@Autowired
	AlarmInfoServiceImpl alarmInfoService;

	@Autowired
	private OperationOrderLetterMapper orderLetterMapper;


    @Override
	public IPage<OperationOrderSettleVO> selectOperationOrderSettlePage(IPage<OperationOrderSettleVO> page, OperationOrderConditionForm conditionVo) {
		BladeUser user = AuthUtil.getUser();
		//3.服务商 4.平台员工 5.服务商人员
		if ("3".equals(user.getDeptId())) {  //服务商
			OperationSiteEntity site = siteService.findSiteByUserId(user.getUserId());
			conditionVo.setSiteId(site.getId());
		} else if ("5".equals(user.getDeptId())) {  //服务商人员
			EmpAuthVo authVo=employeeMapper.findEmpAuthByUserId(user.getUserId());
			if(authVo!=null){
				conditionVo.setSiteId(authVo.getSiteId());
				conditionVo.setProvinces(authVo.getProvinces());
				conditionVo.setCity(authVo.getCity());
				conditionVo.setArea(authVo.getArea());
			}
		}else if("4".equals(user.getDeptId())){ //平台员工
			EmpAuthVo authVoP=orderService.getBaseMapper().findPlatEmpAuthByUserId(user.getUserId());
			if(authVoP!= null){
				conditionVo.setSiteIds(authVoP.getSiteId());
				conditionVo.setProvinces(authVoP.getProvinces());
				conditionVo.setCity(authVoP.getCity());
				conditionVo.setArea(authVoP.getArea());
				conditionVo.setEntryIds(authVoP.getEntryId());
			}
		}
		return page.setRecords(baseMapper.selectOperationOrderSettlePage(page, conditionVo));
	}


	@Override
	public List<OperationOrderSettleExcel> exportOperationOrderSettle(Wrapper<OperationOrderSettleEntity> queryWrapper) {
		List<OperationOrderSettleExcel> operationOrderSettleList = baseMapper.exportOperationOrderSettle(queryWrapper);
		//operationOrderSettleList.forEach(operationOrderSettle -> {
		//	operationOrderSettle.setTypeName(DictCache.getValue(DictEnum.YES_NO, OperationOrderSettle.getType()));
		//});
		return operationOrderSettleList;
	}

	//结算
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveOrderSettle(OperationOrderSettleDTO orderSettleDTO) {
		BladeUser user = AuthUtil.getUser();
		OperationOrderEntity orderEntity=orderService.getById(orderSettleDTO.getOrderId());
		Date date=new Date();
		OperationOrderSettleEntity settleEntity;
		String processStr="";
		if(StringUtil.isBlank(orderSettleDTO.getSettleId())){
			/*orderEntity.setLatestProcess(user.getNickName()+"操作结算");
			orderEntity.setLatestProcessTime(date);
			orderEntity.setUpdateName(user.getNickName());
			orderService.updateById(orderEntity);*/
			settleEntity=new OperationOrderSettleEntity();
			settleEntity.setOrderId(orderEntity.getId());
			settleEntity.setSettleBy(String.valueOf(user.getUserId()));
			settleEntity.setSettleByName(user.getNickName());
			settleEntity.setSettleTime(date);
			settleEntity.setSiteId(orderEntity.getSiteId());
			processStr="操作结算";
		}else{
			settleEntity=getById(orderSettleDTO.getSettleId());
			processStr="修改结算";
		}
		settleEntity.setSettleAmount(orderSettleDTO.getSettleAmount());
		settleEntity.setDeductionAmount(orderSettleDTO.getDeductionAmount());
		//扣款总额：每次上传公函时，填写的扣款费用总额，当电站上传过公函，则扣款总额获取公函中的扣款总额信息，不可修改；当电站没有上传过公函，则可手动填写扣款金额；
		//获取公函中的扣款总额
		BigDecimal totalDedutionAumount=orderLetterMapper.getTotalDeductionAmount(orderEntity.getId());
		if(totalDedutionAumount!=null){
			if(totalDedutionAumount.compareTo(orderSettleDTO.getDeductionAmount())!=0){
				throw new ServiceException("电站上传过公函，扣款总额获取公函中的扣款总额信息，不可修改!扣款总额应该为： "+totalDedutionAumount);
			}
			settleEntity.setDeductionAmount(totalDedutionAumount);
		}

        settleEntity.setActualAmount(settleEntity.getSettleAmount().subtract(settleEntity.getDeductionAmount()));
        settleEntity.setRemarks(orderSettleDTO.getRemarks());

        if(!saveOrUpdate(settleEntity)){
			return false;
		}

		Target ta = new Target();
		ta.setD(DateUtil.formatDateTime(date));
		ta.setP(user.getNickName());
		ta.setC(user.getNickName() + processStr);

		OperationOrderOperationInfoEntity info = infoService.findInfoByOrderId(orderEntity.getId());
		ta.setT(2);
		String str = WebPageFunUtils.appendOrderProcessDetail(ta, info.getProcessDetail());
		info.setProcessDetail(str);
		return infoService.updateById(info);
	}

	@Override
	public boolean ifSettle(String orderIds, String ifSettle) {
    	int i=1;
    	for(String orderId:orderIds.split(",")){
			if("0".equals(ifSettle)){//不需要结算了，那么判断一下，之前有没有结算记录，如果有，那么不能修改
				OperationOrderSettleDTO settleDTO=baseMapper.getByOrderId(orderId);
				if(settleDTO!=null){
					throw new ServiceException("第"+i+"条工单已结算，不支持修改！");
				}
			}
			i++;
		}

		LambdaUpdateWrapper<OperationOrderEntity> updateWrapper=new LambdaUpdateWrapper<>();
		updateWrapper.in(OperationOrderEntity::getId,orderIds.split(","));
		updateWrapper.set(OperationOrderEntity::getIfSettle,ifSettle);
		return orderService.update(updateWrapper);
	}


}
