package shop.alien.second.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.second.SecondEntrustUser;
import shop.alien.entity.second.SecondTradeRecord;
import shop.alien.entity.second.vo.SecondEntrustUserDTO;
import shop.alien.entity.second.vo.SecondEntrustUserDetailVo;
import shop.alien.entity.second.vo.SecondEntrustUserQueryVo;
import shop.alien.entity.second.vo.SecondEntrustUserResultVo;
import shop.alien.entity.second.vo.SecondTradeRecordVo;
import shop.alien.mapper.second.SecondEntrustUserMapper;
import shop.alien.mapper.second.SecondTradeRecordMapper;
import shop.alien.second.service.PlatformSecondTradeService;
import shop.alien.second.service.SecondEntrustUserService;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 二手委托人信息表 服务实现类
 * </p>
 *
 * @author ssk
 * @since 2025-11-21
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SecondEntrustUserServiceImpl extends ServiceImpl<SecondEntrustUserMapper, SecondEntrustUser> implements SecondEntrustUserService {

    private final SecondEntrustUserMapper secondEntrustUserMapper;
    private final SecondTradeRecordMapper secondTradeRecordMapper;
    private final PlatformSecondTradeService platformSecondTradeService;

    /**
     * 创建委托人信息
     *
     * @param dto 委托人信息DTO
     * @return 是否创建成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createEntrustUser(SecondEntrustUserDTO dto) {
        log.info("SecondEntrustUserServiceImpl.createEntrustUser dto={}", dto);
        try {
            // 检查该交易是否已存在委托人信息
            SecondEntrustUser existUser = getByTradeId(dto.getEntrustTradeId());
            if (existUser != null) {
                log.warn("交易ID:{}已存在委托人信息", dto.getEntrustTradeId());
                throw new RuntimeException("该交易已存在委托人信息");
            }

            // 创建委托人信息
            SecondEntrustUser entrustUser = new SecondEntrustUser();
            BeanUtils.copyProperties(dto, entrustUser);
            
            return this.save(entrustUser);
        } catch (Exception e) {
            log.error("SecondEntrustUserServiceImpl.createEntrustUser error: {}", e.getMessage(), e);
            throw new RuntimeException("创建委托人信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据交易ID获取委托人信息
     *
     * @param entrustTradeId 交易ID
     * @return 委托人信息
     */
    @Override
    public SecondEntrustUser getByTradeId(Integer entrustTradeId) {
        log.info("SecondEntrustUserServiceImpl.getByTradeId entrustTradeId={}", entrustTradeId);
        LambdaQueryWrapper<SecondEntrustUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SecondEntrustUser::getEntrustTradeId, entrustTradeId);
        return this.getOne(wrapper);
    }

    /**
     * 根据交易编号获取委托人信息
     *
     * @param entrustTradeNo 交易编号
     * @return 委托人信息
     */
    @Override
    public SecondEntrustUser getByTradeNo(String entrustTradeNo) {
        log.info("SecondEntrustUserServiceImpl.getByTradeNo entrustTradeNo={}", entrustTradeNo);
        if (StringUtils.isBlank(entrustTradeNo)) {
            return null;
        }
        LambdaQueryWrapper<SecondEntrustUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SecondEntrustUser::getEntrustTradeNo, entrustTradeNo);
        return this.getOne(wrapper);
    }

    /**
     * 更新委托人信息
     *
     * @param id 委托人ID
     * @param dto 委托人信息DTO
     * @return 是否更新成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEntrustUser(Integer id, SecondEntrustUserDTO dto) {
        log.info("SecondEntrustUserServiceImpl.updateEntrustUser id={}, dto={}", id, dto);
        try {
            // 检查委托人信息是否存在
            SecondEntrustUser entrustUser = this.getById(id);
            if (entrustUser == null) {
                log.warn("委托人信息不存在, id={}", id);
                throw new RuntimeException("委托人信息不存在");
            }

            // 更新委托人信息
            BeanUtils.copyProperties(dto, entrustUser);
            entrustUser.setId(id);
            
            return this.updateById(entrustUser);
        } catch (Exception e) {
            log.error("SecondEntrustUserServiceImpl.updateEntrustUser error: {}", e.getMessage(), e);
            throw new RuntimeException("更新委托人信息失败: " + e.getMessage());
        }
    }

    /**
     * 删除委托人信息（逻辑删除）
     *
     * @param id 委托人ID
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEntrustUser(Integer id) {
        log.info("SecondEntrustUserServiceImpl.deleteEntrustUser id={}", id);
        try {
            SecondEntrustUser entrustUser = this.getById(id);
            if (entrustUser == null) {
                log.warn("委托人信息不存在, id={}", id);
                throw new RuntimeException("委托人信息不存在");
            }
            return this.removeById(id);
        } catch (Exception e) {
            log.error("SecondEntrustUserServiceImpl.deleteEntrustUser error: {}", e.getMessage(), e);
            throw new RuntimeException("删除委托人信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户电话查询委托人信息列表
     *
     * @param entrustUserPhone 用户电话
     * @return 委托人信息列表
     */
    @Override
    public List<SecondEntrustUser> getByUserPhone(String entrustUserPhone) {
        log.info("SecondEntrustUserServiceImpl.getByUserPhone entrustUserPhone={}", entrustUserPhone);
        LambdaQueryWrapper<SecondEntrustUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SecondEntrustUser::getEntrustUserPhone, entrustUserPhone);
        wrapper.orderByDesc(SecondEntrustUser::getCreatedTime);
        return this.list(wrapper);
    }

    /**
     * 分页查询委托人信息列表（以姓名+身份证号为维度）
     *
     * @param queryVo 查询条件
     * @return 委托人信息分页列表
     */
    @Override
    public IPage<SecondEntrustUserResultVo> getEntrustUserPage(SecondEntrustUserQueryVo queryVo) {
        log.info("SecondEntrustUserServiceImpl.getEntrustUserPage queryVo={}", queryVo);
        try {
            // 创建分页对象
            Page<SecondEntrustUser> page = new Page<>(queryVo.getPageNum(), queryVo.getPageSize());
            
            // 构建查询条件（用于HAVING子句）
            QueryWrapper<SecondEntrustUser> wrapper = new QueryWrapper<>();
            
            // 委托人姓名模糊查询
            if (StringUtils.isNotBlank(queryVo.getEntrustUserName())) {
                wrapper.apply("entrust.entrust_user_name LIKE CONCAT('%', {0}, '%')", queryVo.getEntrustUserName());
            }
            
            // 身份证号模糊查询
            if (StringUtils.isNotBlank(queryVo.getEntrustIdCard())) {
                wrapper.apply("entrust.entrust_id_card LIKE CONCAT('%', {0}, '%')", queryVo.getEntrustIdCard());
            }
            
            // 委托人电话模糊查询
            if (StringUtils.isNotBlank(queryVo.getEntrustUserPhone())) {
                wrapper.apply("entrust.entrust_user_phone LIKE CONCAT('%', {0}, '%')", queryVo.getEntrustUserPhone());
            }
            
            // 交易编号模糊查询
            if (StringUtils.isNotBlank(queryVo.getEntrustTradeNo())) {
                wrapper.apply("trade.trade_no LIKE CONCAT('%', {0}, '%')", queryVo.getEntrustTradeNo());
            }
            // deleteFlag = 0
            wrapper.eq("entrust.delete_flag", 0);
            
            // 执行分页查询
            return secondEntrustUserMapper.getEntrustUserPage(page, wrapper);
        } catch (Exception e) {
            log.error("SecondEntrustUserServiceImpl.getEntrustUserPage error: {}", e.getMessage(), e);
            throw new RuntimeException("查询委托人信息列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据姓名和身份证号获取委托人详情（包含该人所有委托记录的交易信息）
     *
     * @param entrustUserName 委托人姓名
     * @param entrustIdCard 委托人身份证号
     * @return 委托人详情
     */
    @Override
    public SecondEntrustUserDetailVo getEntrustUserDetail(String entrustUserName, String entrustIdCard) throws Exception {
        log.info("SecondEntrustUserServiceImpl.getEntrustUserDetail entrustUserName={}, entrustIdCard={}", entrustUserName, entrustIdCard);
        try {
            // 1. 根据姓名和身份证号查询该人的所有委托记录
            List<SecondEntrustUser> entrustUsers = secondEntrustUserMapper.getByUserNameAndIdCard(entrustUserName, entrustIdCard);
            
            if (entrustUsers == null || entrustUsers.isEmpty()) {
                log.warn("委托人信息不存在, entrustUserName={}, entrustIdCard={}", entrustUserName, entrustIdCard);
                throw new RuntimeException("委托人信息不存在");
            }
            
            // 2. 创建返回对象，使用第一条记录作为基本信息（同一个人的基本信息相同）
            SecondEntrustUserDetailVo detailVo = new SecondEntrustUserDetailVo();
            SecondEntrustUser firstRecord = entrustUsers.get(0);
            detailVo.setEntrustUserInfo(firstRecord);
            
            // 3. 收集该人所有委托记录关联的交易ID
            List<Integer> tradeIds = new ArrayList<>();
            for (SecondEntrustUser entrustUser : entrustUsers) {
                if (entrustUser.getEntrustTradeId() != null) {
                    tradeIds.add(entrustUser.getEntrustTradeId());
                }
            }
            
            // 4. 查询所有关联的交易记录
            List<SecondTradeRecordVo> tradeRecordVos = new ArrayList<>();
            
            if (!tradeIds.isEmpty()) {
                // 去重
                tradeIds = tradeIds.stream().distinct().collect(java.util.stream.Collectors.toList());
                
                // 批量查询交易记录
                QueryWrapper<SecondTradeRecord> tradeWrapper = new QueryWrapper<>();
                tradeWrapper.in("id", tradeIds)
                        .eq("delete_flag", 0)
                        .orderByDesc("created_time");
                
                List<SecondTradeRecord> tradeRecords = secondTradeRecordMapper.selectList(tradeWrapper);
                
                // 5. 处理每条交易记录，添加操作节点信息和用户信息
                if (tradeRecords != null && !tradeRecords.isEmpty()) {
                    for (SecondTradeRecord tradeRecord : tradeRecords) {
                        // 获取完整的交易记录信息（包含买卖双方信息）
                        SecondTradeRecordVo tradeRecordVo = secondTradeRecordMapper.getTradeRecordById(tradeRecord.getId());
                        
                        if (tradeRecordVo != null) {
                            // 添加交易操作节点信息
                            List<JSONObject> operationJsonList = platformSecondTradeService.getOperationJsonList(tradeRecord.getId());
                            tradeRecordVo.setOperationJsonList(operationJsonList);
                            
                            tradeRecordVos.add(tradeRecordVo);
                        }
                    }
                }
            }
            
            detailVo.setTradeRecords(tradeRecordVos);
            
            return detailVo;
        } catch (Exception e) {
            log.error("SecondEntrustUserServiceImpl.getEntrustUserDetail error: {}", e.getMessage(), e);
            throw new Exception("获取委托人详情失败: " + e.getMessage());
        }
    }

}

