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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.distribution.entity.dto.CompanyDTO;
import com.fzm.mall.server.admin.distribution.entity.dto.CompanySaveDTO;
import com.fzm.mall.server.admin.distribution.entity.dto.CompanyUpdateDTO;
import com.fzm.mall.server.admin.distribution.mapper.CompanyMapper;
import com.fzm.mall.server.admin.distribution.model.Company;
import com.fzm.mall.server.admin.distribution.service.ICompanyService;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.util.CopyUtil;
import com.fzm.mall.server.admin.util.UUIDUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 物流中心-快递公司 服务实现类
 * </p>
 *
 * @author wulixian
 * @since 2021-03-03
 */
@Service
@Transactional
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {

    @Resource
    private CompanyMapper companyMapper;

    @Override
    public void save(CompanySaveDTO companySaveDTO) {
        Company company = CopyUtil.to(companySaveDTO, Company.class);
        company.setCompanyId(UUIDUtil.getUUID());
        companyMapper.insert(company);
    }

    @Override
    public void update(CompanyUpdateDTO companyUpdateDTO) {
        Company company = CopyUtil.to(companyUpdateDTO, Company.class);
        UpdateWrapper<Company> wrapper = new UpdateWrapper<>();
        wrapper.eq("company_id", company.getCompanyId())
                .eq("merchant_id", company.getMerchantId())
                .eq("update_time", company.getUpdateTime());
        int update = companyMapper.update(company, wrapper);
        if(update == 0){
            throw new MyException(MallResponseError.UPDATE_FAIL);
        }
    }

    @Override
    public void delete(String companyId, String merchantId) {
        QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", companyId).eq("merchant_id", merchantId);
        companyMapper.delete(queryWrapper);
    }

    @Override
    public CompanyDTO read(String companyId, String merchantId) {
        Company company = companyMapper.read(companyId, merchantId);
        return CopyUtil.to(company, CompanyDTO.class);
    }

    @Override
    public List<CompanyDTO> list(String merchantId) {
        List<Company> list = companyMapper.list(merchantId);
        return CopyUtil.toList(list, CompanyDTO.class);
    }
}
