package com.yuchen.saas.park.service.service.resource.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thinkunion.park.service.common.utils.ReceiptCodeUtil;
import com.yuchen.saas.park.api.dto.resource.ResourceInfoReqDTO;
import com.yuchen.saas.park.api.dto.resource.ResourceInfoSubmitReqDTO;
import com.yuchen.saas.park.api.entity.resource.SaasParkResourceInfo;
import com.yuchen.saas.park.api.vo.resource.ResourceInfoVO;
import com.yuchen.saas.park.service.mapper.resource.SaasParkResourceInfoMapper;
import com.yuchen.saas.park.service.service.resource.ISaasParkResourceInfoService;
import com.yuchen.saas.park.service.service.resource.ISaasParkResourceSubscribeInfoService;
import com.yuchen.saas.park.service.util.PageConverterUtils;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseEntity;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.NestPage;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 资源管理表 服务实现类
 * </p>
 *
 * @author zhouhanwei
 * @since 2024-10-17
 */
@Service
public class SaasParkResourceInfoServiceImpl extends BaseServiceImpl<SaasParkResourceInfoMapper, SaasParkResourceInfo> implements ISaasParkResourceInfoService {

    @Lazy
    @Resource
    private ISaasParkResourceSubscribeInfoService iSaasParkResourceSubscribeInfoService;

    @Override
    public NestPage<ResourceInfoVO> findResourceInfoPage(ResourceInfoReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        Page<ResourceInfoVO> resultPage = new Page<>();
        // 分页数据
        Query query = new Query();
        query.setCurrent(reqDTO.getCurrent());
        query.setSize(reqDTO.getSize());
        // 赋值数据
        LambdaQueryWrapper<SaasParkResourceInfo> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkResourceInfo::getCustomerId, contextUser.getCustomerManageId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getProjectId()), SaasParkResourceInfo::getProjectId, reqDTO.getProjectId());
        lambdaWrapper.like(Func.isNotEmpty(reqDTO.getResourceName()), SaasParkResourceInfo::getResourceName, reqDTO.getResourceName());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getResourceTypeId()), SaasParkResourceInfo::getResourceTypeId, reqDTO.getResourceTypeId());
        lambdaWrapper.le(Func.isNotEmpty(reqDTO.getResourceStartTime()), SaasParkResourceInfo::getResourceStartTime, reqDTO.getResourceStartTime());
        lambdaWrapper.le(Func.isNotEmpty(reqDTO.getResourceEndTime()), SaasParkResourceInfo::getResourceEndTime, reqDTO.getResourceEndTime());
        lambdaWrapper.like(Func.isNotEmpty(reqDTO.getResourceTags()), SaasParkResourceInfo::getResourceTags, reqDTO.getResourceTags());
        lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        IPage<SaasParkResourceInfo> page = page(Condition.getPage(query),lambdaWrapper);
        // 数据列表
        List<ResourceInfoVO> resultList = new ArrayList<>();
        for (SaasParkResourceInfo saasParkResourceInfo : page.getRecords()) {
            ResourceInfoVO vo = new ResourceInfoVO();
            BeanUtil.copyProperties(saasParkResourceInfo, vo);
            resultList.add(vo);
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultList);
        return PageConverterUtils.convert(resultPage);
    }

    @Override
    public ResourceInfoVO getResourceInfoById(Long resourceId) {
        ResourceInfoVO vo = new ResourceInfoVO();
        SaasParkResourceInfo saasParkResourceInfo = getById(resourceId);
        if (Objects.isNull(saasParkResourceInfo)) {
            throw new ServiceException("资源管理数据不存在");
        }
        BeanUtil.copyProperties(saasParkResourceInfo, vo);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addResourceInfo(ResourceInfoSubmitReqDTO reqDTO) {
        SaasParkResourceInfo saasParkResourceInfo = new SaasParkResourceInfo();
        BeanUtil.copyProperties(reqDTO, saasParkResourceInfo);
        saasParkResourceInfo.setCustomerId(AuthUtil.getUser().getCustomerManageId());
        // 判断预约方式
        if (StrUtil.equals(saasParkResourceInfo.getSubscribeMode(), "1")) {
            if (Func.isEmpty(saasParkResourceInfo.getResourceSubscribeLeadDay())) {
                throw new ServiceException("资源可提前预约时间(天)不能为空");
            }
            if (Func.isEmpty(saasParkResourceInfo.getUserSubscribeLeadHour())) {
                throw new ServiceException("用户需提前预定时间(小时)");
            }
            if (Func.isEmpty(saasParkResourceInfo.getUserSubscribeScope())) {
                throw new ServiceException("请选择可预定对象范围");
            }
        }
        // 判断收费方式
        if (StrUtil.equals(saasParkResourceInfo.getChargeMode(), "1")) {
            if (Func.isEmpty(saasParkResourceInfo.getSubscribeType())) {
                throw new ServiceException("请选择收费方式");
            }
            if (Func.isEmpty(saasParkResourceInfo.getPriceType())) {
                throw new ServiceException("请选择价格类型");
            }
            if (Func.isEmpty(saasParkResourceInfo.getCurrentPrice())) {
                throw new ServiceException("现价不能为空");
            }
            if (Func.isEmpty(saasParkResourceInfo.getOriginalPrice())) {
                saasParkResourceInfo.setOriginalPrice(0L);
            }
        }
        // 待发布状态
        saasParkResourceInfo.setResourceState("2");
        // 资源编号
        saasParkResourceInfo.setResourceCode(ReceiptCodeUtil.setResourceCodeValue("ZY"));
        return save(saasParkResourceInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editResourceInfo(ResourceInfoSubmitReqDTO reqDTO) {
        SaasParkResourceInfo saasParkResourceInfo = getById(reqDTO.getId());
        if (Objects.isNull(saasParkResourceInfo)) {
            throw new ServiceException("资源管理数据不存在");
        }
        saasParkResourceInfo.setResourceStartTime(reqDTO.getResourceStartTime());
        saasParkResourceInfo.setResourceEndTime(reqDTO.getResourceEndTime());
        saasParkResourceInfo.setResourceImages(reqDTO.getResourceImages());
        saasParkResourceInfo.setResourceDesc(reqDTO.getResourceDesc());
        saasParkResourceInfo.setLinkman(reqDTO.getLinkman());
        saasParkResourceInfo.setLinkmanPhone(reqDTO.getLinkmanPhone());
        saasParkResourceInfo.setCustomerServicePhone(reqDTO.getCustomerServicePhone());
        saasParkResourceInfo.setOpenStartTime(reqDTO.getOpenStartTime());
        saasParkResourceInfo.setOpenEndTime(reqDTO.getOpenEndTime());
        saasParkResourceInfo.setSubscribeMode(reqDTO.getSubscribeMode());
        saasParkResourceInfo.setResourceSubscribeLeadDay(reqDTO.getResourceSubscribeLeadDay());
        saasParkResourceInfo.setUserSubscribeLeadHour(reqDTO.getUserSubscribeLeadHour());
        saasParkResourceInfo.setUserSubscribeScope(reqDTO.getUserSubscribeScope());
        saasParkResourceInfo.setSubscribeType(reqDTO.getSubscribeType());
        saasParkResourceInfo.setChargeMode(reqDTO.getChargeMode());
        saasParkResourceInfo.setPriceType(reqDTO.getPriceType());
        saasParkResourceInfo.setCurrentPrice(reqDTO.getCurrentPrice());
        saasParkResourceInfo.setOriginalPrice(reqDTO.getOriginalPrice());
        return updateById(saasParkResourceInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeResourceInfo(Long resourceId) {
        SaasParkResourceInfo saasParkResourceInfo = getById(resourceId);
        if (Objects.isNull(saasParkResourceInfo)) {
            throw new ServiceException("资源管理数据不存在");
        }
        int count = iSaasParkResourceSubscribeInfoService.getResourceSubscribeCount(resourceId);
        if (count > 0) {
            throw new ServiceException("资源已有用户预定，不能撤回");
        }
        return removeById(resourceId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean publishResourceInfo(Long resourceId) {
        SaasParkResourceInfo saasParkResourceInfo = getById(resourceId);
        if (Objects.isNull(saasParkResourceInfo)) {
            throw new ServiceException("资源管理数据不存在");
        }
        Date newDate = new Date();
        if (StrUtil.equals(saasParkResourceInfo.getResourceState(), "2")) {
            throw new ServiceException("待发布状态的资源才可以进行发布");
        }
        if (newDate.getTime() > saasParkResourceInfo.getResourceEndTime().getTime()) {
            throw new ServiceException("资源已过期，无法发布");
        }
        // 已发布状态
        saasParkResourceInfo.setResourceState("1");
        saasParkResourceInfo.setPublishDate(newDate);
        return updateById(saasParkResourceInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean revocationResourceInfo(Long resourceId) {
        SaasParkResourceInfo saasParkResourceInfo = getById(resourceId);
        if (Objects.isNull(saasParkResourceInfo)) {
            throw new ServiceException("资源管理数据不存在");
        }
        int count = iSaasParkResourceSubscribeInfoService.getResourceSubscribeCount(resourceId);
        if (count > 0) {
            throw new ServiceException("资源已有用户预定，不能撤回");
        }
        // 撤回设置成待发布状态
        saasParkResourceInfo.setResourceState("2");
        return updateById(saasParkResourceInfo);
    }

    @Override
    public void everyDayUpdateParkResource() {
        List<SaasParkResourceInfo> list = list(new LambdaQueryWrapper<SaasParkResourceInfo>()
                .le(SaasParkResourceInfo::getResourceEndTime, new Date()));
        if (Func.isNotEmpty(list)) {
            list.forEach(s -> {
                s.setResourceState("3");
            });
            updateBatchById(list);
        }
    }
}
