package shop.alien.lawyer.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawFirm;
import shop.alien.entity.store.LawyerUser;
import shop.alien.entity.store.vo.LawFirmListVO;
import shop.alien.entity.store.vo.LawFirmReconciliationVO;
import shop.alien.entity.store.vo.LawyerListVO;
import shop.alien.lawyer.service.LawFirmReconciliationService;
import shop.alien.lawyer.service.LawFirmService;
import shop.alien.lawyer.service.LawyerUserService;
import shop.alien.mapper.LawFirmMapper;
import shop.alien.util.excel.EasyExcelUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 律所对账结算服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class LawFirmReconciliationServiceImpl implements LawFirmReconciliationService {

    private final LawFirmMapper lawFirmMapper;
    private final LawFirmService lawFirmService;
    private final LawyerUserService lawyerUserService;

    @Override
    public R<LawFirmReconciliationVO> getLawFirmReconciliation(
            Integer firmId,
            String firmName,
            Date startDate,
            Date endDate) {
        log.info("LawFirmReconciliationServiceImpl.getLawFirmReconciliation?firmId={},firmName={},startDate={},endDate={}",
                firmId, firmName, startDate, endDate);

        // 查询统计信息
        java.util.Map<String, Object> statistics = lawFirmMapper.getLawFirmReconciliationStatistics(firmId, firmName, startDate, endDate);
        long totalOrderCount = statistics != null && statistics.get("order_count") != null
                ? ((Number) statistics.get("order_count")).longValue() : 0L;
        long totalOrderAmount = statistics != null && statistics.get("total_amount") != null
                ? ((Number) statistics.get("total_amount")).longValue() : 0L;
        long platformServiceFee = statistics != null && statistics.get("total_platform_service_fee") != null
                ? ((Number) statistics.get("total_platform_service_fee")).longValue() : 0L;

        // 获取律所名称
        String resultFirmName = "所有律所";

        // 如果 firmId 有值，查询当前律所信息并验证佣金比例
        if (firmId != null) {
            LawFirm lawFirm = lawFirmService.getById(firmId);
            if (lawFirm == null || (lawFirm.getDeleteFlag() != null && lawFirm.getDeleteFlag() == 1)) {
                return R.fail("律所不存在或已被删除");
            }
            resultFirmName = lawFirm.getFirmName();
//            if (lawFirm.getPlatformCommissionRatio() == null) {
//                return R.fail("律所[" + resultFirmName + "]的平台佣金比例未设置，无法计算对账信息");
//            }
        } else if (firmName != null && !firmName.trim().isEmpty()) {
            // 如果只传了 firmName，使用传入的名称
            resultFirmName = firmName;
        }

        // 构建返回对象
        LawFirmReconciliationVO vo = new LawFirmReconciliationVO();
        vo.setFirmId(firmId);
        vo.setFirmName(resultFirmName);
        vo.setTotalOrderCount(totalOrderCount);
        vo.setTotalOrderAmountYuan(convertFenToYuan(totalOrderAmount));
        vo.setPlatformServiceFeeYuan(convertFenToYuan(platformServiceFee));

        return R.data(vo, "查询成功");
    }



    @Override
    public R<IPage<LawFirmListVO>> getAllLawFirmReconciliationList(
            String firmName,
            Date startDate,
            Date endDate,
            Integer pageNum,
            Integer pageSize) {
        log.info("LawFirmReconciliationServiceImpl.getAllLawFirmReconciliationList?firmName={},startDate={},endDate={},pageNum={},pageSize={}",
                firmName, startDate, endDate, pageNum, pageSize);

        // 查询所有律所的统计信息（SQL中已直接计算为元）
        List<LawFirmListVO> firmList = lawFirmMapper.getAllLawFirmReconciliationStatistics(firmName, startDate, endDate);

        // 手动分页
        Page<LawFirmListVO> page = new Page<>();
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            page.setCurrent(pageNum);
            page.setSize(pageSize);
            page.setTotal(firmList.size());

            int start = (pageNum - 1) * pageSize;
            int end = Math.min(start + pageSize, firmList.size());
            if (start < firmList.size()) {
                page.setRecords(firmList.subList(start, end));
            } else {
                page.setRecords(Collections.emptyList());
            }
        } else {
            page.setCurrent(1);
            page.setSize(firmList.size());
            page.setTotal(firmList.size());
            page.setRecords(firmList);
        }

        return R.data(page, "查询成功");
    }

    @Override
    public R<IPage<LawyerListVO>> getLawyerReconciliationList(
            Integer firmId,
            Date startDate,
            Date endDate,
            Integer pageNum,
            Integer pageSize) {
        log.info("LawFirmReconciliationServiceImpl.getLawyerReconciliationList?firmId={},startDate={},endDate={},pageNum={},pageSize={}",
                firmId, startDate, endDate, pageNum, pageSize);

        // 验证律所是否存在
        if (firmId == null) {
            return R.fail("律所ID不能为空");
        }
        LawFirm lawFirm = lawFirmService.getById(firmId);
        if (lawFirm == null || (lawFirm.getDeleteFlag() != null && lawFirm.getDeleteFlag() == 1)) {
            return R.fail("律所不存在或已被删除");
        }

        // 查询律所下所有律师的统计信息（SQL中已直接计算为元）
        List<LawyerListVO> lawyerList = lawFirmMapper.getLawyerReconciliationStatistics(firmId, startDate, endDate);

        // 手动分页
        Page<LawyerListVO> page = new Page<>();
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            page.setCurrent(pageNum);
            page.setSize(pageSize);
            page.setTotal(lawyerList.size());

            int start = (pageNum - 1) * pageSize;
            int end = Math.min(start + pageSize, lawyerList.size());
            if (start < lawyerList.size()) {
                page.setRecords(lawyerList.subList(start, end));
            } else {
                page.setRecords(Collections.emptyList());
            }
        } else {
            page.setCurrent(1);
            page.setSize(lawyerList.size());
            page.setTotal(lawyerList.size());
            page.setRecords(lawyerList);
        }

        return R.data(page, "查询成功");
    }

    @Override
    public R<IPage<LawyerListVO>> getLawyerReconciliationListWithName(
            Integer firmId,
            String lawyerName,
            Date startDate,
            Date endDate,
            Integer pageNum,
            Integer pageSize) {
        log.info("LawFirmReconciliationServiceImpl.getLawyerReconciliationListWithName?firmId={},lawyerName={},startDate={},endDate={},pageNum={},pageSize={}",
                firmId, lawyerName, startDate, endDate, pageNum, pageSize);

        // 验证律所是否存在
        if (firmId == null) {
            return R.fail("律所ID不能为空");
        }
        LawFirm lawFirm = lawFirmService.getById(firmId);
        if (lawFirm == null || (lawFirm.getDeleteFlag() != null && lawFirm.getDeleteFlag() == 1)) {
            return R.fail("律所不存在或已被删除");
        }

        // 查询律所下所有律师的统计信息（SQL中已直接计算为元，支持律师名称模糊查询）
        List<LawyerListVO> lawyerList = lawFirmMapper.getLawyerReconciliationStatisticsWithName(firmId, lawyerName, startDate, endDate);

        // 手动分页
        Page<LawyerListVO> page = new Page<>();
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            page.setCurrent(pageNum);
            page.setSize(pageSize);
            page.setTotal(lawyerList.size());

            int start = (pageNum - 1) * pageSize;
            int end = Math.min(start + pageSize, lawyerList.size());
            if (start < lawyerList.size()) {
                page.setRecords(lawyerList.subList(start, end));
            } else {
                page.setRecords(Collections.emptyList());
            }
        } else {
            page.setCurrent(1);
            page.setSize(lawyerList.size());
            page.setTotal(lawyerList.size());
            page.setRecords(lawyerList);
        }

        return R.data(page, "查询成功");
    }

    @Override
    public R<IPage<LawFirmReconciliationVO>> getLawyerOrderList(
            Integer lawyerId,
            Integer pageNum,
            Integer pageSize) {
        log.info("LawFirmReconciliationServiceImpl.getLawyerOrderList?lawyerId={},pageNum={},pageSize={}",
                lawyerId, pageNum, pageSize);

        // 验证律师是否存在
        if (lawyerId == null) {
            return R.fail("律师ID不能为空");
        }
//        LawyerUser lawyerUser = lawyerUserService.getById(lawyerId);
//        if (lawyerUser == null || (lawyerUser.getDeleteFlag() != null && lawyerUser.getDeleteFlag() == 1)) {
//            return R.fail("律师不存在或已被删除");
//        }

        // 创建分页对象
//        int pageNumValue = pageNum != null && pageNum > 0 ? pageNum : 1;
//        int pageSizeValue = pageSize != null && pageSize > 0 ? pageSize : 10;
        Page<LawFirmReconciliationVO> page = new Page<>(pageNum, pageSize);

        // 查询律师的已完成订单列表
        IPage<LawFirmReconciliationVO> orderPage = lawFirmMapper.getLawyerOrderList(page, lawyerId);

        return R.data(orderPage, "查询成功");
    }

    @Override
    public void exportAllLawFirmList(
            HttpServletResponse response,
            String firmName,
            Date startDate,
            Date endDate,
            Integer pageNum,
            Integer pageSize) throws Exception {
        log.info("LawFirmReconciliationServiceImpl.exportAllLawFirmList?firmName={},startDate={},endDate={},pageNum={},pageSize={}",
                firmName, startDate, endDate, pageNum, pageSize);

        // 调用查询接口获取数据
        R<IPage<LawFirmListVO>> result = getAllLawFirmReconciliationList(firmName, startDate, endDate, pageNum, pageSize);

        if (result == null || !result.isSuccess()) {
            log.warn("获取律所对账列表失败：{}", result != null ? result.getMsg() : "返回结果为空");
            throw new RuntimeException(result != null ? result.getMsg() : "获取数据失败，请稍后重试");
        }

        IPage<LawFirmListVO> page = result.getData();
        if (page == null || page.getRecords() == null || page.getRecords().isEmpty()) {
            log.warn("律所对账列表导出：无数据可导出");
            throw new IllegalArgumentException("暂无数据可导出");
        }

        List<LawFirmListVO> exportList = page.getRecords();
        log.info("律所对账列表导出：查询到{}条数据，导出{}条数据", page.getTotal(), exportList.size());

        // 使用EasyExcelUtil导出
        EasyExcelUtil.exportExcel(response, exportList, LawFirmListVO.class, "律所对账列表", "律所对账列表");
    }

    @Override
    public void exportLawyerListWithName(
            HttpServletResponse response,
            Integer firmId,
            String lawyerName,
            Date startDate,
            Date endDate,
            Integer pageNum,
            Integer pageSize) throws Exception {
        log.info("LawFirmReconciliationServiceImpl.exportLawyerListWithName?firmId={},lawyerName={},startDate={},endDate={},pageNum={},pageSize={}",
                firmId, lawyerName, startDate, endDate, pageNum, pageSize);

        // 调用查询接口获取数据
        R<IPage<LawyerListVO>> result = getLawyerReconciliationListWithName(firmId, lawyerName, startDate, endDate, pageNum, pageSize);

        if (result == null || !result.isSuccess()) {
            log.warn("获取律师对账列表失败：{}", result != null ? result.getMsg() : "返回结果为空");
            throw new RuntimeException(result != null ? result.getMsg() : "获取数据失败，请稍后重试");
        }

        IPage<LawyerListVO> page = result.getData();
        if (page == null || page.getRecords() == null || page.getRecords().isEmpty()) {
            log.warn("律师对账列表导出：无数据可导出，firmId={}", firmId);
            throw new IllegalArgumentException("暂无数据可导出");
        }

        List<LawyerListVO> exportList = page.getRecords();
        log.info("律师对账列表导出：查询到{}条数据，导出{}条数据，firmId={}", page.getTotal(), exportList.size(), firmId);

        // 使用EasyExcelUtil导出
        EasyExcelUtil.exportExcel(response, exportList, LawyerListVO.class, "律师对账列表", "律师对账列表");
    }

    /**
     * 将分转换为元（字符串格式）
     *
     * @param fen 分
     * @return 元（字符串格式，保留2位小数）
     */
    private String convertFenToYuan(Long fen) {
        if (fen == null || fen == 0) {
            return "0.00";
        }
        BigDecimal yuan = BigDecimal.valueOf(fen).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        return yuan.toString();
    }
}

