package com.red.circle.other.infra.database.mongo.service.bd;

import com.red.circle.other.infra.database.mongo.entity.bd.BdLeaderSalarySettlementRecord;
import com.red.circle.other.infra.enums.BdSettlementStatus;
import com.red.circle.tool.core.date.TimestampUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * BD Leader 结算记录服务实现.
 *
 * @author AI Assistant
 * @since 2025-10-29
 */
@Service
@RequiredArgsConstructor
public class BdLeaderSalarySettlementRecordServiceImpl implements BdLeaderSalarySettlementRecordService {

    private final MongoTemplate mongoTemplate;

    @Override
    public void create(BdLeaderSalarySettlementRecord record) {
        record.setCreateTime(TimestampUtils.now());
        record.setUpdateTime(TimestampUtils.now());
        mongoTemplate.save(record);
    }

    @Override
    public void update(BdLeaderSalarySettlementRecord record) {
        record.setUpdateTime(TimestampUtils.now());
        mongoTemplate.save(record);
    }

    @Override
    public BdLeaderSalarySettlementRecord getById(String id) {
        return mongoTemplate.findById(id, BdLeaderSalarySettlementRecord.class);
    }

    @Override
    public BdLeaderSalarySettlementRecord getByBizNo(String bizNo) {
        Query query = new Query(Criteria.where("bizNo").is(bizNo));
        return mongoTemplate.findOne(query, BdLeaderSalarySettlementRecord.class);
    }

    @Override
    public boolean existsByBizNo(String bizNo) {
        Query query = new Query(Criteria.where("bizNo").is(bizNo));
        return mongoTemplate.exists(query, BdLeaderSalarySettlementRecord.class);
    }

    @Override
    public BdLeaderSalarySettlementRecord getByUserIdAndBillBelong(Long bdLeaderUserId, Integer billBelong) {
        Query query = new Query(Criteria.where("bdLeaderUserId").is(bdLeaderUserId)
                .and("billBelong").is(billBelong));
        return mongoTemplate.findOne(query, BdLeaderSalarySettlementRecord.class);
    }

    @Override
    public List<BdLeaderSalarySettlementRecord> listByBillBelong(Integer billBelong) {
        Query query = new Query(Criteria.where("billBelong").is(billBelong));
        return mongoTemplate.find(query, BdLeaderSalarySettlementRecord.class);
    }

    @Override
    public void updateStatus(String id, BdSettlementStatus status, String failureReason) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update()
                .set("status", status)
                .set("failureReason", failureReason)
                .set("updateTime", TimestampUtils.now());
        mongoTemplate.updateFirst(query, update, BdLeaderSalarySettlementRecord.class);
    }
}
