package com.fjhx.victoriatourist.service.after.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.file.utils.ObsFileUtil;
import com.fjhx.victoriatourist.entity.after.dto.AfterSaleHandleDto;
import com.fjhx.victoriatourist.entity.after.dto.AfterSaleHandleSelectDto;
import com.fjhx.victoriatourist.entity.after.po.AfterSaleHandle;
import com.fjhx.victoriatourist.entity.after.po.AfterSaleRecord;
import com.fjhx.victoriatourist.entity.after.vo.AfterSaleHandleVo;
import com.fjhx.victoriatourist.mapper.after.AfterSaleHandleMapper;
import com.fjhx.victoriatourist.service.after.AfterSaleHandleService;
import com.fjhx.victoriatourist.service.after.AfterSaleRecordService;
import com.ruoyi.common.core.domain.BaseIdPo;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 售后管理-跟进记录 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-19
 */
@Service
public class AfterSaleHandleServiceImpl extends ServiceImpl<AfterSaleHandleMapper, AfterSaleHandle> implements AfterSaleHandleService {

    @Autowired
    private AfterSaleRecordService afterSaleRecordService;

    @Override
    public Page<AfterSaleHandleVo> getPage(AfterSaleHandleSelectDto dto) {
        IWrapper<AfterSaleHandle> wrapper = getWrapper();
        wrapper.eq("ash", AfterSaleHandle::getAfterSaleRecordId, dto.getAfterSaleRecordId());
        wrapper.orderByDesc("ash", AfterSaleHandle::getId);
        Page<AfterSaleHandleVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);

        List<AfterSaleHandleVo> records = page.getRecords();
        if (records.size() == 0) {
            return page;
        }

        UserUtil.assignmentNickName(records, AfterSaleHandle::getHandleUserId, AfterSaleHandleVo::setHandleUserName);
        UserUtil.assignmentNickName(records, AfterSaleHandle::getNextUserId, AfterSaleHandleVo::setNextUserName);

        return page;
    }

    @DSTransactional
    @Override
    public void add(AfterSaleHandleDto afterSaleHandleDto) {
        this.save(afterSaleHandleDto);
        ObsFileUtil.saveFile(afterSaleHandleDto.getFileList(), afterSaleHandleDto.getId());
        afterSaleRecordService.update(q -> q
                .eq(BaseIdPo::getId, afterSaleHandleDto.getAfterSaleRecordId())
                .set(AfterSaleRecord::getStatus, afterSaleHandleDto.getStatus())
        );
    }

}
