package com.bonus.sharedstation.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.sharedstation.api.DictDataApi;
import com.bonus.sharedstation.api.vo.DictDataInfoDO;
import com.bonus.sharedstation.app.domain.GreenUserInfo;
import com.bonus.sharedstation.app.domain.TherapyAppointments;
import com.bonus.sharedstation.app.dto.GreenInfoDTO;
import com.bonus.sharedstation.app.dto.GreenOrderDTO;
import com.bonus.sharedstation.app.entity.GreenInfo;
import com.bonus.sharedstation.app.entity.GreenOrder;
import com.bonus.sharedstation.app.entity.GreenOrderInfo;
import com.bonus.sharedstation.app.mapper.GreenInfoMapper;
import com.bonus.sharedstation.app.mapper.GreenOrderInfoMapper;
import com.bonus.sharedstation.app.mapper.GreenOrderMapper;
import com.bonus.sharedstation.app.service.GreenOrderService;
import com.bonus.sharedstation.common.utils.OrderNumberGeneratorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 便民服务信息表保洁(CleaningServicesOrder)表服务实现类
 *
 * @author makejava
 * @since 2024-12-10 17:02:11
 */
@Service("greenOrderService")
@Slf4j
public class GreenOrderServiceImpl extends ServiceImpl<GreenOrderMapper, GreenOrder> implements GreenOrderService {

    @Resource
    private GreenOrderMapper greenOrderMapper;
    @Resource
    private GreenOrderInfoMapper greenOrderInfoMapper;
    @Resource
    private GreenInfoMapper dao;

    @Resource
    private BaseService baseService;

    @Resource
    private DictDataApi dictDataApi;
    /**
     * 分页
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getListPageApp(GreenOrderDTO dto) {
        log.info("查询分页入参: {}", dto);
        LambdaQueryWrapper<GreenOrder> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<GreenOrder> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        // 根据userId是否提供来动态添加条件
        if (dto.getUserId() != null) {
            queryWrapper.eq(GreenOrder::getUserId, dto.getUserId());
        }

        if (StringUtils.isNotEmpty(dto.getName())) {
            queryWrapper.like(GreenOrder::getName, dto.getName());
        }
        queryWrapper
                .eq(GreenOrder::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(GreenOrder::getCreatedTime);     // 降序排序

        Page<GreenOrder> result = greenOrderMapper.selectPage(page, queryWrapper);
        //处理参数问题
        List<GreenOrder> records = result.getRecords();
        if (records == null) {
            return AjaxResult.success(result);
        }
        //查询所有的绿植订单信息
        LambdaQueryWrapper<GreenOrderInfo> greenOrderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        greenOrderInfoLambdaQueryWrapper
                .eq(GreenOrderInfo::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(GreenOrderInfo::getCreatedTime);     // 降序排序
        List<GreenOrderInfo> greenOrderInfos = greenOrderInfoMapper.selectList(greenOrderInfoLambdaQueryWrapper);
        for (GreenOrder record : records) {
            if (record != null) {
                Integer id = record.getId();
                List<GreenOrderInfo> collect = greenOrderInfos.stream().
                        filter(greenOrderInfo -> greenOrderInfo.getOrderId() != null
                                && greenOrderInfo.getOrderId() == id).collect(Collectors.toList());
                if (collect != null) {
                    record.setGreenOrderInfoList(collect);
                }
            }
        }
        return AjaxResult.success(result);
    }


    @Override
    public AjaxResult selectInfoById(GreenOrder dto) {
        GreenOrder greenOrder = greenOrderMapper.selectById(dto.getId());
        LambdaQueryWrapper<GreenOrderInfo> greenOrderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (greenOrder != null) {
            greenOrderInfoLambdaQueryWrapper
                    .eq(GreenOrderInfo::getIsDeleted, dto.getIsDeleted())
                    .eq(GreenOrderInfo::getOrderId, greenOrder.getId())
                    .orderByDesc(GreenOrderInfo::getCreatedTime);
            List<GreenOrderInfo> greenOrderInfos =
                    greenOrderInfoMapper.selectList(greenOrderInfoLambdaQueryWrapper);

            if (greenOrderInfos != null) {
                greenOrder.setGreenOrderInfoList(greenOrderInfos);
            }
            return AjaxResult.success(greenOrder);
        }
        return AjaxResult.success();
    }

    /**
     * 新增
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult add(GreenOrderDTO dto) {
        log.info("新增入参 : " + dto);
        GreenUserInfo userInfo = baseService.getUserInfo(dto.getUserId());
        //得到登录人
        GreenOrder greenOrder = new GreenOrder();
        BeanUtils.copyProperties(dto, greenOrder);
        greenOrder.setCreatedBy(userInfo.getLoginName());
        greenOrder.setCreatedTime(new Date());
        greenOrder.setUserId(userInfo.getUserId());
        greenOrder.setIsDeleted("0");
        greenOrder.setOrderTime(new Date());
        //判断订单金额有没有超过 500 ,不超过 500 则 增加 30 配送费
        //三方扣款
        //流水号
        greenOrder.setOrdno(OrderNumberGeneratorUtils.generateOrderNumber());
        //支付相关接入第三方小牛支付
       return null;

    }

    @Override
    public AjaxResult updateInfoById(GreenOrder dto) {
        return null;
    }


    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult getListPage(GreenInfoDTO dto) {
        log.info("查询 入参: {}", dto);
        LambdaQueryWrapper<GreenInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 创建分页对象
        Page<GreenInfo> page = new Page<>(dto.getCurrentPage(), dto.getLimit());
        if (StringUtils.isNotEmpty(dto.getGreenName())) {
            queryWrapper.like(GreenInfo::getGreenName, dto.getGreenName());
        }
        if (StringUtils.isNotEmpty(dto.getType())) {
            queryWrapper.eq(GreenInfo::getType, dto.getType());
        }
        queryWrapper
                .eq(GreenInfo::getIsDeleted, dto.getIsDeleted())
                .orderByDesc(GreenInfo::getCreatedTime);

        Page<GreenInfo> result = dao.selectPage(page, queryWrapper);
        //处理参数问题
        getTypeNameMethd(result);
        return AjaxResult.success(result);
    }


    /**
     * type类型转换
     *
     * @param result
     */
    private void getTypeNameMethd(Page<GreenInfo> result) {
        //处理参数问题
        DictDataInfoDO dictDataInfoDO = new DictDataInfoDO();
        //字典类型
        dictDataInfoDO.setDataType("equipment_type");
        List<DictDataInfoDO> dictDataInfoDOList = dictDataApi.getDictionaryInfo("green_flower");

        if (dictDataInfoDOList.isEmpty()){
            throw new RuntimeException("请先配置设备数据字典绿植服务相关数据");
        }
        // 将 List<SysDictData> 转换为 Map<Long, String>，假设 id 是 Long 类型，name 是 String 类型
        Map<String, String> map = dictDataInfoDOList.stream()
                .collect(Collectors.toMap(DictDataInfoDO::getDataCode, DictDataInfoDO::getDataValue));
        List<GreenInfo> records = result.getRecords();

        if (StringUtils.isNotEmpty(records)) {
            records.stream().forEach(emergencyEquipment -> {
                if (map.containsKey(emergencyEquipment.getType())) {
                    emergencyEquipment.setTypeName(map.get(emergencyEquipment.getType()));
                }

            });
        }
    }


    @Override
    public AjaxResult selectDirCode(TherapyAppointments dto) {
        List<DictDataInfoDO> dictDataInfoDOList = dictDataApi.getDictionaryInfo("green_flower");

        if (dictDataInfoDOList.isEmpty()){
            throw new RuntimeException("请先配置设备数据字典绿植服务相关数据");
        }
        return AjaxResult.success(dictDataInfoDOList);
    }
}

