package com.fzm.mall.server.admin.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.order.entity.dto.ComplaintDTO;
import com.fzm.mall.server.admin.order.entity.dto.ComplaintSaveDTO;
import com.fzm.mall.server.admin.order.entity.dto.ComplaintUpdateDTO;
import com.fzm.mall.server.admin.order.mapper.ComplaintMapper;
import com.fzm.mall.server.admin.order.model.Complaint;
import com.fzm.mall.server.admin.order.service.IComplaintService;
import com.fzm.mall.server.admin.util.CopyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 订单中心-订单投诉 服务实现类
 * </p>
 *
 * @author wulixian
 * @since 2021-03-16
 */
@Service
@Transactional
public class ComplaintServiceImpl extends ServiceImpl<ComplaintMapper, Complaint> implements IComplaintService {

    @Resource
    private ComplaintMapper complaintMapper;

    @Override
    public void save(ComplaintSaveDTO complaintSaveDTO) {
        Complaint complaint = CopyUtil.to(complaintSaveDTO, Complaint.class);
        complaint.init();

        complaintMapper.insert(complaint);
    }

    @Override
    public void update(ComplaintUpdateDTO complaintUpdateDTO) {
        Complaint complaint = CopyUtil.to(complaintUpdateDTO, Complaint.class);
        complaint.setComplaintStatus(Complaint.COMPLAINT_STATUS_DONE);

        UpdateWrapper<Complaint> wrapper = new UpdateWrapper<>();
        wrapper.eq("complaint_id", complaint.getComplaintId())
                .eq("update_time", complaint.getUpdateTime());
        int update = complaintMapper.update(complaint, wrapper);
        if (update == 0) {
            throw new MyException(MallResponseError.UPDATE_FAIL);
        }
    }

    @Override
    public ComplaintDTO read(String complaintId) {
        Complaint complaint = complaintMapper.read(complaintId);
        ComplaintDTO reuslt;
        if (complaint == null) {
            reuslt = new ComplaintDTO();
        }else{
            reuslt = complaint.toDTO();
        }
        return reuslt;
    }

    @Override
    public IPage<ComplaintDTO> page(Page<ComplaintDTO> page, String uid, String complaintId, Integer complaintStatus) {
        IPage<ComplaintDTO> result = complaintMapper.page(page, uid, complaintId, complaintStatus);
        return result;
    }
}
