package org.dromara.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.main.domain.MainOrder;
import org.dromara.main.domain.MainPosition;
import org.dromara.main.domain.MainStudent;
import org.dromara.main.domain.MainBackCandidate;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.dromara.main.mapper.MainOrderMapper;
import org.dromara.main.mapper.MainPositionMapper;
import org.dromara.main.mapper.MainStudentMapper;
import org.dromara.main.mapper.MainBackCandidateMapper;
import org.dromara.main.service.IMainOrderService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

@RequiredArgsConstructor
@Service
public class MainOrderServiceImpl implements IMainOrderService {

    private final MainOrderMapper baseMapper;
    private final MainStudentMapper studentMapper;
    private final MainPositionMapper positionMapper;
    private final MainBackCandidateMapper candidateMapper;
    private final ISysOssService ossService;

    @Override
    public MainOrder queryById(Long id) {
        MainOrder order = baseMapper.selectById(id);
        fillExtendInfo(order);
        return order;
    }

    @Override
    public TableDataInfo<MainOrder> queryPageList(MainOrder order, PageQuery pageQuery) {
        LambdaQueryWrapper<MainOrder> lqw = buildQueryWrapper(order);
        Page<MainOrder> result = baseMapper.selectPage(pageQuery.build(), lqw);
        
        // 填充扩展信息
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            for (MainOrder item : result.getRecords()) {
                fillExtendInfo(item);
            }
        }
        
        return TableDataInfo.build(result);
    }

    @Override
    public List<MainOrder> queryList(MainOrder order) {
        LambdaQueryWrapper<MainOrder> lqw = buildQueryWrapper(order);
        List<MainOrder> list = baseMapper.selectList(lqw);
        
        // 填充扩展信息
        if (list != null && !list.isEmpty()) {
            for (MainOrder item : list) {
                fillExtendInfo(item);
            }
        }
        
        return list;
    }

    /**
     * 填充扩展信息（学员手机号/头像，商品信息等）
     */
    private void fillExtendInfo(MainOrder order) {
        if (order == null) {
            return;
        }
        
        // 1. 如果买家是学员，获取学员信息
        if (order.getBuyerType() != null && order.getBuyerType() == 2 && order.getBuyerId() != null) {
            MainStudent student = studentMapper.selectById(order.getBuyerId());
            if (student != null) {
                order.setPhone(student.getMobile());
                if (student.getAvatar() != null) {
                    SysOssVo oss = ossService.getById(student.getAvatar());
                    if (oss != null) {
                        order.setUserAvatar(oss.getUrl());
                    }
                }
            }
        }
        
        // 2. 根据订单类型获取业务信息
        if (order.getOrderType() != null && order.getBusinessId() != null) {
            if (order.getOrderType() == 1) {
                // 职位发布订单
                MainPosition position = positionMapper.selectById(order.getBusinessId());
                if (position != null) {
                    order.setProductName("发布职位：" + position.getPostName());
                }
            } else if (order.getOrderType() == 2) {
                // 简历投递订单
                MainBackCandidate candidate = candidateMapper.selectById(order.getBusinessId());
                if (candidate != null && candidate.getPostId() != null) {
                    MainPosition position = positionMapper.selectById(candidate.getPostId());
                    if (position != null) {
                        order.setProductName("投递职位：" + position.getPostName());
                    }
                }
            } else if (order.getOrderType() == 3) {
                // 背调订单
                order.setProductName("背景调查服务");
            }
        }
    }

    private LambdaQueryWrapper<MainOrder> buildQueryWrapper(MainOrder order) {
        LambdaQueryWrapper<MainOrder> lqw = Wrappers.lambdaQuery();
        if (order != null) {
            lqw.eq(StringUtils.isNotBlank(order.getOrderNo()), MainOrder::getOrderNo, order.getOrderNo());
            lqw.like(StringUtils.isNotBlank(order.getCustomerSn()), MainOrder::getCustomerSn, order.getCustomerSn());
            lqw.eq(order.getOrderType() != null, MainOrder::getOrderType, order.getOrderType());
            lqw.eq(order.getBuyerType() != null, MainOrder::getBuyerType, order.getBuyerType());
            lqw.eq(order.getBuyerId() != null, MainOrder::getBuyerId, order.getBuyerId());
            lqw.like(StringUtils.isNotBlank(order.getBuyerName()), MainOrder::getBuyerName, order.getBuyerName());
            lqw.eq(order.getSellerId() != null, MainOrder::getSellerId, order.getSellerId());
            lqw.eq(order.getOrderStatus() != null, MainOrder::getOrderStatus, order.getOrderStatus());
            lqw.eq(order.getPayStatus() != null, MainOrder::getPayStatus, order.getPayStatus());
            lqw.eq(order.getBusinessId() != null, MainOrder::getBusinessId, order.getBusinessId());
            lqw.eq(order.getProductId() != null, MainOrder::getProductId, order.getProductId());
            lqw.eq(StringUtils.isNotBlank(order.getTenantId()), MainOrder::getTenantId, order.getTenantId());
        }
        lqw.orderByDesc(MainOrder::getCreateTime);
        return lqw;
    }

    @Override
    public Boolean insert(MainOrder order) {
        return baseMapper.insert(order) > 0;
    }

    @Override
    public Boolean update(MainOrder order) {
        return baseMapper.updateById(order) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }
}
