package com.sckw.system.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.result.PageDataResult;
import com.sckw.system.model.SysDictType;
import com.sckw.system.model.vo.req.SysDictTypeReqVo;
import com.sckw.system.model.vo.res.SysDictTypeResp;
import com.sckw.system.repository.SysDictTypeRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典类型业务服务层(中间层) - MyBatis-Plus 版本
 * @author system
 * @date 2024
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysDictTypeService {

    private final SysDictTypeRepository sysDictTypeService;

    /**
     * 新增字典类型
     */
    public int insert(SysDictTypeReqVo.SysDictTypeInfo entity) {
        log.info("新增字典类型,请求参数：{}", JSON.toJSONString(entity));
        SysDictType existType = sysDictTypeService.selectByType(entity.getType(),entity.getName());
        if (existType != null) {
            log.error("字典类型已存在，请勿重复添加");
            return 0;
        }
        Long userId = LoginUserHolder.getUserId();

        long id = new IdWorker(1L).nextId();
        SysDictType sysDictType = getSysDictType(entity, id, userId);
        return sysDictTypeService.save(sysDictType) ? 1 : 0;
    }

    @NotNull
    private static SysDictType getSysDictType(SysDictTypeReqVo.SysDictTypeInfo entity, long id, Long userId) {
        SysDictType sysDictType = new SysDictType();
        sysDictType.setId(id);
        sysDictType.setName(entity.getName());
        sysDictType.setType(entity.getType());
        sysDictType.setRemark(entity.getRemark());
        sysDictType.setStatus(0);
        sysDictType.setCreateBy(userId);
        sysDictType.setUpdateBy(userId);
        sysDictType.setCreateTime(new Date());
        sysDictType.setUpdateTime(new Date());
        return sysDictType;
    }


    /**
     * 逻辑删除
     */
    public int logicDeleteById(Long id) {
        return sysDictTypeService.logicDeleteById(id);
    }

    /**
     * 更新字典类型
     */
    public int update(SysDictTypeReqVo.SysDictTypeInfo entity) {
        SysDictType sysDictType = new SysDictType();
        sysDictType.setId(entity.getId());
        sysDictType.setName(entity.getName());
        sysDictType.setType(entity.getType());
        sysDictType.setRemark(entity.getRemark());
        sysDictType.setUpdateBy(LoginUserHolder.getUserId());
        sysDictType.setUpdateTime(new Date());
        return sysDictTypeService.update(sysDictType);
    }



    /**
     * 分页查询字典类型
     */
    public PageDataResult<SysDictTypeResp> selectPage(SysDictTypeReqVo reqVo) {
        log.info("分页查询字典类型,请求参数：{}", JSON.toJSONString(reqVo));
        int pageNum = reqVo.getPageNum();
        int pageSize = reqVo.getPageSize();
        IPage<SysDictType> page = sysDictTypeService.selectPage(pageNum, pageSize, reqVo.getName(), reqVo.getType(), reqVo.getStatus(),reqVo.getKeyword());
        List<SysDictType> records = page.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return PageDataResult.empty(reqVo.getPageNum(), reqVo.getPageSize());
        }
        List<SysDictTypeResp> sysDictTypes = records.stream()
                .map(SysDictTypeService::getSysDictTypeResp)
                .collect(Collectors.toList());
        return PageDataResult.of(page, sysDictTypes);
    }

    @NotNull
    private static SysDictTypeResp getSysDictTypeResp(SysDictType s) {
        SysDictTypeResp sysDictTypeResp = new SysDictTypeResp();
        sysDictTypeResp.setId(s.getId());
        sysDictTypeResp.setName(s.getName());
        sysDictTypeResp.setType(s.getType());
        sysDictTypeResp.setRemark(s.getRemark());
        sysDictTypeResp.setStatus(s.getStatus());
        sysDictTypeResp.setCreateTime(s.getCreateTime());
        sysDictTypeResp.setUpdateTime(s.getUpdateTime());
        sysDictTypeResp.setDelFlag(s.getDelFlag());
        return sysDictTypeResp;
    }

    /**
     * 搜索字典类型（支持下拉选择）
     */
    public List<SysDictTypeResp> searchForSelect(String keyword) {
        List<SysDictType> sysDictTypes = sysDictTypeService.searchForSelect(keyword);
        if (CollectionUtils.isEmpty(sysDictTypes)) {
            return List.of();
        }

        return sysDictTypes.stream()
                .map(SysDictTypeService::getSysDictTypeResp)
                .collect(Collectors.toList());
    }


}
