package com.limap.core.basic.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.limap.common.utils.DateUtils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.limap.common.core.domain.AjaxResult;
import com.limap.core.basic.domain.AquPayDevice;
import com.limap.core.basic.domain.AquPayOrder;
import com.limap.core.basic.domain.BasicUserBindInfo;
import com.limap.core.basic.service.IBasicUserWithdrawService;
import com.limap.core.basic.vo.BasicUserWithdrawVo;
import com.limap.core.basic.vo.SharingRecordSearchVo;
import com.limap.core.basic.vo.SharingUserTaskVo;
import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.limap.common.utils.StringUtils;
import com.limap.core.basic.mapper.BasicProfitSharingRecordMapper;
import com.limap.core.basic.domain.BasicProfitSharingRecord;
import com.limap.core.basic.service.IBasicProfitSharingRecordService;

import java.util.Collection;

/**
 * 分润记录Service业务层处理
 *
 * @author jjb
 * @date 2025-04-11
 */
@Service
@Slf4j
@DS("master")
public class BasicProfitSharingRecordServiceImpl extends ServiceImpl<BasicProfitSharingRecordMapper, BasicProfitSharingRecord> implements IBasicProfitSharingRecordService {
    @Autowired
    private BasicProfitSharingRecordMapper basicProfitSharingRecordMapper;
	@Autowired
	private IBasicUserWithdrawService basicUserWithdrawService;

    /**
     * 查询分润记录列表
     *
     * @param basicProfitSharingRecord 分润记录
     * @return 分润记录
     */
    @Override
    public List<BasicProfitSharingRecord> selectBasicProfitSharingRecordList(BasicProfitSharingRecord basicProfitSharingRecord) {
    	LambdaQueryWrapper<BasicProfitSharingRecord> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotNull(basicProfitSharingRecord.getUserId())) {
			queryWrapper.eq(BasicProfitSharingRecord::getUserId, basicProfitSharingRecord.getUserId());
		}
        if (StringUtils.isNotEmpty(basicProfitSharingRecord.getFromWay())) {
			queryWrapper.like(BasicProfitSharingRecord::getFromWay, basicProfitSharingRecord.getFromWay());
		}
        if (StringUtils.isNotNull(basicProfitSharingRecord.getStatus())) {
			queryWrapper.eq(BasicProfitSharingRecord::getStatus, basicProfitSharingRecord.getStatus());
		}
        if (StringUtils.isNotNull(basicProfitSharingRecord.getGenerateTime())) {
			queryWrapper.eq(BasicProfitSharingRecord::getGenerateTime, basicProfitSharingRecord.getGenerateTime());
		}
        if (StringUtils.isNotNull(basicProfitSharingRecord.getWithdrawalStatus())) {
			queryWrapper.eq(BasicProfitSharingRecord::getWithdrawalStatus, basicProfitSharingRecord.getWithdrawalStatus());
		}
        if (StringUtils.isNotNull(basicProfitSharingRecord.getWithdrawalTime())) {
			queryWrapper.eq(BasicProfitSharingRecord::getWithdrawalTime, basicProfitSharingRecord.getWithdrawalTime());
		}
        if (StringUtils.isNotNull(basicProfitSharingRecord.getPaymentStatus())) {
			queryWrapper.eq(BasicProfitSharingRecord::getPaymentStatus, basicProfitSharingRecord.getPaymentStatus());
		}
        if (StringUtils.isNotNull(basicProfitSharingRecord.getPaymentTime())) {
			queryWrapper.eq(BasicProfitSharingRecord::getPaymentTime, basicProfitSharingRecord.getPaymentTime());
		}
        if (StringUtils.isNotNull(basicProfitSharingRecord.getWithdrawId())) {
			queryWrapper.eq(BasicProfitSharingRecord::getWithdrawId, basicProfitSharingRecord.getWithdrawId());
		}
		if (StringUtils.isNotNull(basicProfitSharingRecord.getDeviceName())) {
			queryWrapper.eq(BasicProfitSharingRecord::getDeviceName, basicProfitSharingRecord.getDeviceName());
		}
		// 兼容前端params[beginTime]/params[endTime]传参方式
		Map<String, Object> params = basicProfitSharingRecord.getParams();
		String scopeType = (String) params.get("scopeType");
		Long scopeDeptId = (Long) params.get("scopeDeptId");
		if (StringUtils.isNotNull(scopeDeptId)) {
			if ("deptAndChild".equals(scopeType)) {
				queryWrapper.inSql(BasicProfitSharingRecord::getDeptId,
						"SELECT dept_id FROM sys_dept WHERE dept_id = " + scopeDeptId + " OR find_in_set(" + scopeDeptId + ", ancestors)");
			} else if ("dept".equals(scopeType)) {
				queryWrapper.eq(BasicProfitSharingRecord::getDeptId, scopeDeptId);
			}
		}
		String beginTime = (String) params.get("beginTime");
		String endTime = (String) params.get("endTime");
		if (StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime)) {
			queryWrapper.ge(BasicProfitSharingRecord::getGenerateTime, beginTime + " 00:00:00");
			queryWrapper.le(BasicProfitSharingRecord::getGenerateTime, endTime + " 23:59:59");
		} else if (StringUtils.isNotNull(basicProfitSharingRecord.getStartTime())) {
			queryWrapper.between(BasicProfitSharingRecord::getGenerateTime, basicProfitSharingRecord.getStartTime(), basicProfitSharingRecord.getEndTime());
		}
		if (StringUtils.isNotNull(basicProfitSharingRecord.getTel())) {
			queryWrapper.like(BasicProfitSharingRecord::getTel, basicProfitSharingRecord.getTel());
		}
		if (StringUtils.isNotEmpty(basicProfitSharingRecord.getUserName())) {
			queryWrapper.like(BasicProfitSharingRecord::getUserName, basicProfitSharingRecord.getUserName());
		}
		if (StringUtils.isNotEmpty(basicProfitSharingRecord.getOrderNo())) {
			queryWrapper.like(BasicProfitSharingRecord::getOrderNo, basicProfitSharingRecord.getOrderNo());
		}
        queryWrapper.orderByDesc(BasicProfitSharingRecord::getGenerateTime);
        return basicProfitSharingRecordMapper.selectList(queryWrapper);
    }

	/**
	 * 重写saveBatch，解决dynamic-datasource下批量插入事务不提交的问题
	 * 1. saveBatch内部BATCH模式绕过@DS
	 * 2. @Transactional与@DS冲突导致事务不提交
	 * 去掉@Transactional，依赖连接池autoCommit=true逐条提交
	 */
	@DS("master")
	@Override
	public boolean saveBatch(Collection<BasicProfitSharingRecord> entityList, int batchSize) {
		if (entityList == null || entityList.isEmpty()) {
			return false;
		}
		log.info("saveBatch开始, 待插入{}条记录", entityList.size());
		int count = 0;
		for (BasicProfitSharingRecord record : entityList) {
			try {
				int rows = basicProfitSharingRecordMapper.insert(record);
				if (rows > 0) {
					count++;
				} else {
					log.warn("insert返回0行, record.orderNo={}, record.userId={}", record.getOrderNo(), record.getUserId());
				}
			} catch (Exception e) {
				log.error("insert单条异常, record.orderNo={}, error={}", record.getOrderNo(), e.getMessage());
			}
		}
		log.info("saveBatch完成, 预期插入{}条, 实际影响行数{}条", entityList.size(), count);
		return count > 0;
	}

	/**
	 * 处理分润计算
	 *
	 * @param aquPayOrder
	 * @param sharingUserTaskVo
	 * @return
	 */
	@Override
	public BasicProfitSharingRecord calculateProfit(AquPayDevice aquPayOrder, SharingUserTaskVo sharingUserTaskVo) {
		if(aquPayOrder.getOrderId() == null){
			log.info("异常数据 aquPayOrder ：{}。sharingUserTaskVo：{}", JSONObject.toJSONString(aquPayOrder), JSONObject.toJSONString(sharingUserTaskVo));
		}
		BigDecimal decimal = new BigDecimal(aquPayOrder.getPayAmount()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
		BigDecimal ratio = BigDecimal.ZERO;
		if(aquPayOrder.getDeviceType() == 1){
			ratio = sharingUserTaskVo.getOmRatio();
		}else{
			ratio = sharingUserTaskVo.getControlRatio();
		}
		String serialNum = aquPayOrder.getSerialNum();
		BigDecimal amount = decimal.multiply(ratio).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
		BasicProfitSharingRecord basicProfitSharingRecord = new BasicProfitSharingRecord();
		basicProfitSharingRecord.setUserId(sharingUserTaskVo.getUserId());
		basicProfitSharingRecord.setUserName(sharingUserTaskVo.getNickName());
		basicProfitSharingRecord.setAmount(amount);
		basicProfitSharingRecord.setTitle("设备："+ serialNum + ",微信充值：" + decimal + "元,分润：" + amount + "元");
		basicProfitSharingRecord.setFromWay("微信充值账单分润");
		basicProfitSharingRecord.setStatus(1);
		basicProfitSharingRecord.setGenerateTime(aquPayOrder.getCreatedTime());
		basicProfitSharingRecord.setOrderNo(aquPayOrder.getOrderId() + "");
		basicProfitSharingRecord.setDeviceName(serialNum);
		basicProfitSharingRecord.setWithdrawalStatus(0);
		basicProfitSharingRecord.setPaymentStatus(0);
		basicProfitSharingRecord.setTel(sharingUserTaskVo.getTel());
		basicProfitSharingRecord.setDeptId(sharingUserTaskVo.getDeptId());
		return basicProfitSharingRecord;
	}

	@Override
	public Map<String, Object> getReportData(SharingRecordSearchVo searchVo) {
		return basicProfitSharingRecordMapper.getReportData(searchVo);
	}

	@Override
	public List<BasicProfitSharingRecord> selectRecordByWithdraw(BasicUserWithdrawVo basicUserWithdraw) {
		LambdaQueryWrapper<BasicProfitSharingRecord> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(BasicProfitSharingRecord::getUserId, basicUserWithdraw.getUserId());
		queryWrapper.eq(BasicProfitSharingRecord::getWithdrawalStatus, 0);
		LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
		queryWrapper.lt(BasicProfitSharingRecord::getGenerateTime, thirtyDaysAgo);
//		queryWrapper.between(BasicProfitSharingRecord::getGenerateTime, basicUserWithdraw.getStartTime(), basicUserWithdraw.getEndTime());
		return list(queryWrapper);
	}

	@Override
	public void updateRecordByWithdraw(BasicUserWithdrawVo basicUserWithdraw) {
		LambdaUpdateWrapper<BasicProfitSharingRecord> queryWrapper = Wrappers.lambdaUpdate();
		queryWrapper.eq(BasicProfitSharingRecord::getUserId, basicUserWithdraw.getUserId());
		queryWrapper.eq(BasicProfitSharingRecord::getWithdrawalStatus, 0);
		LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
		queryWrapper.lt(BasicProfitSharingRecord::getGenerateTime, thirtyDaysAgo);
		queryWrapper.set(BasicProfitSharingRecord::getWithdrawalStatus, 1);
		queryWrapper.set(BasicProfitSharingRecord::getStatus, 0);
	}

	@Override
	public AjaxResult dealRefund(BasicProfitSharingRecord basicProfitSharingRecord) {
		List<BasicProfitSharingRecord> orderRecord = this.list(new QueryWrapper<BasicProfitSharingRecord>().eq("order_no", basicProfitSharingRecord.getOrderNo()));
		orderRecord.forEach(record -> {
			if(record.getStatus() != 9 && record.getPaymentStatus() != 9){
				record.setStatus(9);
				record.setPaymentStatus(9);
				record.setPaymentReason(basicProfitSharingRecord.getPaymentReason());
				if(basicProfitSharingRecord.getWithdrawId() != null){
					basicUserWithdrawService.updatePayment(basicProfitSharingRecord.getWithdrawId(),basicProfitSharingRecord.getAmount());
				}
				this.updateById(record);
			}
		});
		return AjaxResult.success("退款成功");
	}
}
