package com.ycwl.basic.service.pc.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycwl.basic.mapper.TemplateMapper;
import com.ycwl.basic.model.pc.template.entity.TemplateConfigEntity;
import com.ycwl.basic.model.pc.template.entity.TemplateEntity;
import com.ycwl.basic.model.pc.template.req.TemplateReqQuery;
import com.ycwl.basic.model.pc.template.resp.TemplateRespVO;
import com.ycwl.basic.service.pc.TemplateService;
import com.ycwl.basic.repository.TemplateRepository;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.SnowFlakeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author：longbinbin
 * @Date：2024/12/3 16:20
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private TemplateRepository templateRepository;

    @Override
    public ApiResponse<PageInfo<TemplateRespVO>> pageQuery(TemplateReqQuery templateReqQuery) {
        PageHelper.startPage(templateReqQuery.getPageNum(), templateReqQuery.getPageSize());
        List<TemplateRespVO> list = templateMapper.list(templateReqQuery);
        PageInfo<TemplateRespVO> pageInfo = new PageInfo<>(list);
        return ApiResponse.success(pageInfo);
    }

    @Override
    public ApiResponse<List<TemplateRespVO>> list(TemplateReqQuery templateReqQuery) {
        return ApiResponse.success(templateMapper.list(templateReqQuery));
    }

    @Override
    public ApiResponse<TemplateRespVO> getById(Long id) {
        return ApiResponse.success(templateRepository.getTemplate(id));
    }

    @Override
    public ApiResponse<Boolean> add(TemplateEntity template) {
        template.setId(SnowFlakeUtil.getLongId());
        int i = templateMapper.add(template);
        if (template.getChildren() != null) {
            template.getChildren().forEach(item -> {
                item.setId(SnowFlakeUtil.getLongId());
                item.setPid(template.getId());
                item.setScenicId(template.getScenicId());
                item.setStatus(1);
                templateMapper.add(item);
            });
        }
        if (i > 0) {
            return ApiResponse.success(true);
        }else {
            return ApiResponse.fail("添加模版失败");
        }
    }

    @Override
    public ApiResponse<Integer> deleteById(Long id) {
        int i = templateMapper.deleteById(id);
        templateRepository.clearTemplateCache(id);
        if (i > 0) {
            templateMapper.deleteByPid(id);
            return ApiResponse.success(i);
        }else {
            return ApiResponse.fail("删除模版失败");
        }
    }

    @Override
    public ApiResponse<Boolean> update(TemplateEntity template) {
        template.setUpdateTime(new Date());
        int i = templateMapper.update(template);
        if (template.getChildren() != null) {
            templateMapper.deleteByPid(template.getId());
            template.getChildren().forEach(item -> {
                item.setId(SnowFlakeUtil.getLongId());
                item.setPid(template.getId());
                item.setScenicId(template.getScenicId());
                item.setStatus(1);
                templateMapper.add(item);
            });
        }
        templateRepository.clearTemplateCache(template.getId());
        if (i > 0) {
            return ApiResponse.success(true);
        }else {
            return ApiResponse.fail("更新模版失败");
        }
    }

    @Override
    public ApiResponse<Boolean> updateStatus(Long id) {
        int i = templateMapper.updateStatus(id);
        templateRepository.clearTemplateCache(id);
        if (i > 0) {
            return ApiResponse.success(true);
        }else {
            return ApiResponse.fail("更新模版状态失败");
        }
    }

    @Override
    public TemplateConfigEntity getConfig(Long templateId) {
        return templateRepository.getTemplateConfig(templateId);
    }

    @Override
    public void saveConfig(Long configId, TemplateConfigEntity config) {
        config.setId(configId);
        templateMapper.updateConfigById(config);
        templateRepository.clearTemplateCache(config.getTemplateId());
    }

    @Override
    public ApiResponse<Boolean> sortTemplate(Long templateId, Long afterTemplateId) {
        TemplateRespVO template = templateRepository.getTemplate(templateId);
        if (template == null) {
            return ApiResponse.fail("模版不存在");
        }
        List<TemplateRespVO> scenicTemplateList = templateRepository.getAllTemplateListByScenicId(template.getScenicId());
        AtomicInteger sortNum = new AtomicInteger(0);
        for (TemplateRespVO item : scenicTemplateList) {
            item.setSort(sortNum.addAndGet(1));
        }
        Optional<TemplateRespVO> templateOptional = scenicTemplateList.stream().filter(item -> item.getId().equals(templateId)).findAny();
        Optional<TemplateRespVO> afterTemplateOptional = scenicTemplateList.stream().filter(item -> item.getId().equals(afterTemplateId)).findAny();
        if (templateOptional.isEmpty()) {
            return ApiResponse.fail("模版不存在");
        }
        if (afterTemplateOptional.isPresent()) {
            TemplateRespVO afterTemplate = afterTemplateOptional.get();
            Integer newSort = afterTemplate.getSort();
            TemplateRespVO oldTemplate = templateOptional.get();
            Integer oldSort = oldTemplate.getSort();
            afterTemplate.setSort(oldSort);
            oldTemplate.setSort(newSort);
        }
        scenicTemplateList.forEach(item -> {
            templateMapper.updateSort(item.getId(), item.getSort());
            templateRepository.clearTemplateCache(item.getId());
        });
        return ApiResponse.success(true);
    }
}
