package com.jeesharp.business.modules.mall.service.impl;

import com.jeesharp.business.modules.mall.entity.MallProductQa;
import com.jeesharp.business.modules.mall.mapper.MallProductQaMapper;
import com.jeesharp.business.modules.mall.service.MallProductQaService;
import com.jeesharp.business.modules.mall.vo.MallProductQaQueryVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;

/**
 * 商品问答 Service 实现类
 */
@Service
@Transactional(readOnly = true)
public class MallProductQaServiceImpl extends CrudService<MallProductQaMapper, MallProductQa, MallProductQaQueryVO> implements MallProductQaService {

    private static final String IDS_SEPARATOR = ",";
    private static final int PENDING_REPLY_STATUS = 0;
    private static final int REPLIED_STATUS = 1;

    @Override
    @Transactional(readOnly = false)
    public void createQa(MallProductQa entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateQa(MallProductQa entity) {
        update(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void addQuestion(String memberId, String spuId, String question, Integer isAnonymous) {
        MallProductQa qa = new MallProductQa();
        qa.setMemberId(memberId);
        qa.setSpuId(spuId);
        qa.setQuestion(question);
        qa.setIsAnonymous(isAnonymous);
        qa.setStatus(PENDING_REPLY_STATUS);
        createQa(qa);
    }

    @Override
    @Transactional(readOnly = false)
    public void reply(String qaId, String answer, String replyBy) {
        MallProductQa qa = get(qaId);
        if (qa == null) {
            return;
        }
        qa.setAnswer(answer);
        qa.setReplyBy(replyBy);
        qa.setReplyTime(new Date());
        qa.setStatus(REPLIED_STATUS);
        updateQa(qa);
    }

    @Override
    public PageRespVO<MallProductQa> getProductQaList(String spuId, Page<MallProductQa> page) {
        MallProductQaQueryVO query = new MallProductQaQueryVO();
        query.setSpuId(spuId);
        query.setStatus(REPLIED_STATUS);
        Page<MallProductQa> result = findPage(page, query);
        PageRespVO<MallProductQa> resp = new PageRespVO<>();
        resp.setRecords(result.getRecords());
        resp.setTotal(result.getTotal());
        resp.setPageNo(result.getPageNo());
        resp.setPageSize(result.getPageSize());
        return resp;
    }
}
