package cn.com.ty.lift.system.faq.service.impl;

import cn.com.ty.lift.common.constants.ApiConstants;
import cn.com.ty.lift.system.faq.dao.entity.Faq;
import cn.com.ty.lift.system.faq.dao.mapper.FaqMapper;
import cn.com.ty.lift.system.faq.service.FaqService;
import cn.com.xwy.boot.web.dto.RestResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 常见问题级常见问题分类表 服务实现类
 * </p>
 *
 * @author wang-hai-cheng
 * @since 2019-12-05
 */
@Service
public class FaqServiceImpl extends ServiceImpl<FaqMapper, Faq> implements FaqService {

    public RestResponse getFaqs(Faq faq) {
        List<Faq> faqs = this.list(new QueryWrapper<Faq>()
                .eq(faq.getType() != null, "type", faq.getType())
                .eq(faq.getParentId() != null, "parent_id", faq.getParentId())
                .orderByAsc("serial"));
        if (faqs.isEmpty()) {
            return RestResponse.success();
        }
        return RestResponse.success(faqs, "成功");
    }

    /**
     * 删除id及id下的所有记录
     *
     * @param id 要删除的顶级id
     * @return 操作结果
     */
    public RestResponse delete(Long id) {
        List<Faq> faqs = this.list(new QueryWrapper<Faq>().select("id", "parent_id", "serial"));
        removeFaqs(id, faqs);
        List<Long> ids = faqs.stream()
                //保留序号为-1的记录
                .filter(faq -> faq.getSerial().equals(-1))
                //只获取Id字段
                .map(Faq::getId)
                //转数组返回
                .collect(Collectors.toList());
        ids.add(id);
        this.removeByIds(ids);
        return RestResponse.success(ids, "成功");
    }

    /**
     * 将faqs中要删除的做上标记，setSerial(-1)
     *
     * @param id   要删除的顶级id
     * @param faqs 常见问题列表
     */
    public void removeFaqs(Long id, List<Faq> faqs) {
        for (Faq faq : faqs) {
            if (id.equals(faq.getParentId())) {
                //要删除的记录，把序号标记为-1
                faq.setSerial(-1);
                this.removeFaqs(faq.getId(), faqs);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean addFaq(Faq faq) {
        this.save(faq);
        if (faq.getType().equals(ApiConstants.Faq.TITLE_TYPE)) {
            Faq answer = new Faq();
            answer.setParentId(faq.getId());
            answer.setType(ApiConstants.Faq.ANSWER_TYPE);
            this.save(answer);
        }
        return true;
    }
}