package cn.iocoder.yudao.module.system.service.sys;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.controller.admin.sys.vo.ServiceItemPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.sys.vo.ServiceItemSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ServiceItemDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.ServiceItemLevelDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.SysChargeCategoryDO;
import cn.iocoder.yudao.module.system.dal.dataobject.biz.VolunteerDO;
import cn.iocoder.yudao.module.system.dal.dataobject.tenant.TenantDO;
import cn.iocoder.yudao.module.system.dal.mysql.biz.SysChargeCategoryMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.SysServiceIemMapper;
import cn.iocoder.yudao.module.system.dal.mysql.biz.SysServiceItemLevelMapper;
import cn.iocoder.yudao.module.system.dal.mysql.tenant.TenantMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.SERVICE_ITEM_NOT_EXISTS;

/**
 * @Author: jinyd
 * @CreateTime: 2025/4/1  13:44
 * @Description:
 * @Version: 4.0
 */

@Service
@Validated
public class ServiceItemServiceImpl implements ServiceItemService{

    @Resource
    private SysServiceIemMapper serviceItemMapper;

    @Resource
    private TenantMapper tenantMapper;

    @Resource
    private SysChargeCategoryMapper categoryMapper;

    @Resource
    private SysServiceItemLevelMapper levelMapper;

    @Override
    public Long createServiceItem(ServiceItemSaveReqVO createReqVO) {

        // 插入
        ServiceItemDO serviceItem = BeanUtils.toBean(createReqVO, ServiceItemDO.class);
        serviceItemMapper.insert(serviceItem);
        List<ServiceItemLevelDO> levelDOList = createReqVO.getLevelDOList();
        if (null != levelDOList && levelDOList.size() > 0){
            levelDOList.forEach(level -> {
                level.setServiceItemId(serviceItem.getId());
                level.setTenantId(createReqVO.getTenantId());
                levelMapper.insert(level);
            });
        }
        // 返回
        return serviceItem.getId();
    }

    @Override
    public void updateServiceItem(ServiceItemSaveReqVO updateReqVO) {
        // 校验存在
        validateServiceItemExists(updateReqVO.getId());
        levelMapper.update(new LambdaUpdateWrapper<ServiceItemLevelDO>()
                .set(ServiceItemLevelDO::getDeleted, 1)
                .eq(ServiceItemLevelDO::getServiceItemId, updateReqVO.getId())
                .eq(ServiceItemLevelDO::getTenantId, updateReqVO.getTenantId()));
        List<ServiceItemLevelDO> levelDOList = updateReqVO.getLevelDOList();
        if (null != levelDOList && levelDOList.size() > 0){
            levelDOList.forEach(level -> {
                level.setServiceItemId(updateReqVO.getId());
                level.setTenantId(updateReqVO.getTenantId());
                levelMapper.insert(level);
            });
        }
        // 更新
        ServiceItemDO updateObj = BeanUtils.toBean(updateReqVO, ServiceItemDO.class);
        serviceItemMapper.updateById(updateObj);
    }

    @Override
    public void deleteServiceItem(Long id) {
        // 校验存在
        validateServiceItemExists(id);
        // 删除
        serviceItemMapper.deleteById(id);
    }

    private void validateServiceItemExists(Long id) {
        if (serviceItemMapper.selectById(id) == null) {
            throw exception(SERVICE_ITEM_NOT_EXISTS);
        }
    }

    @Override
    public ServiceItemDO getServiceItem(Long id) {
        ServiceItemDO serviceItemDO = serviceItemMapper.selectById(id);
        if (serviceItemDO.getChargeCategoryId() != null) {
            // 找到路径上的所有分类名称
            List<String> categoryNames = new ArrayList<>();
            while (serviceItemDO.getChargeCategoryId() != null) {
                SysChargeCategoryDO sysChargeCategoryDO = categoryMapper.selectById(serviceItemDO.getChargeCategoryId());
                if (null == sysChargeCategoryDO) {
                    break;
                }
                categoryNames.add(sysChargeCategoryDO.getName());
                serviceItemDO.setChargeCategoryId(sysChargeCategoryDO.getParentId());
            }
            serviceItemDO.setCategoryName(String.join("/", categoryNames));
        }
        List<ServiceItemLevelDO> serviceItemLevelDOS = levelMapper.selectList(new LambdaQueryWrapperX<ServiceItemLevelDO>()
                .eq(ServiceItemLevelDO::getServiceItemId, id)
                .eq(ServiceItemLevelDO::getTenantId, serviceItemDO.getTenantId()));
        serviceItemDO.setLevelDOList(serviceItemLevelDOS);
        return serviceItemDO;
    }

    @Override
    public PageResult<ServiceItemDO> getServiceItemPage(ServiceItemPageReqVO pageReqVO) {
        List<TenantDO> tenantDOS = tenantMapper.selectList(new LambdaQueryWrapperX<TenantDO>().in(TenantDO::getId, pageReqVO.getTenantIds()));
        Map<Long, String> tenantMap = tenantDOS.stream().collect(Collectors.toMap(TenantDO::getId, TenantDO::getName));
        PageResult<ServiceItemDO> serviceItemDOPageResult = serviceItemMapper.selectPage(pageReqVO);
        List<ServiceItemDO> serviceItemList = serviceItemDOPageResult.getList();
        serviceItemList.forEach(serviceItem -> {
            if (serviceItem.getTenantId() != null) {
                serviceItem.setTeamName(tenantMap.get(serviceItem.getTenantId()));
            }
            if (serviceItem.getChargeCategoryId() != null) {
                // 找到路径上的所有分类名称
                List<String> categoryNames = new ArrayList<>();
                while (serviceItem.getChargeCategoryId() != null) {
                    SysChargeCategoryDO sysChargeCategoryDO = categoryMapper.selectById(serviceItem.getChargeCategoryId());
                    if (null == sysChargeCategoryDO) {
                        break;
                    }
                    categoryNames.add(sysChargeCategoryDO.getName());
                    serviceItem.setChargeCategoryId(sysChargeCategoryDO.getParentId());
                }
                serviceItem.setCategoryName(String.join("/", categoryNames));
            }
        });
        return serviceItemDOPageResult;
    }

}
