package com.wansenai.service.support.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wansenai.dto.support.BasAddressDto;
import com.wansenai.entities.support.BasAddress;
import com.wansenai.mappers.support.BasAddressMapper;
import com.wansenai.service.support.BasAddressService;
import com.wansenai.service.support.BasAreaService;
import com.wansenai.service.user.ISysUserService;
import com.wansenai.utils.SnowflakeIdUtil;
import com.wansenai.vo.support.BasAddressVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BasAddressServiceImpl extends ServiceImpl<BasAddressMapper, BasAddress> implements BasAddressService {

    private final BasAreaService basAreaService;
    private final ISysUserService sysUserService;

    @Override
    public void addOrUpdate(BasAddressDto basAddressDto) {
        if(basAddressDto.getId() != null){
            BasAddress address = this.getById(basAddressDto.getId());
            BeanUtils.copyProperties(basAddressDto, address);
            address.setUpdateBy(sysUserService.getCurrentUserName());
            address.setUpdateTime(null);
            this.updateById(address);
        }else {
            var address = new BasAddress();
            BeanUtils.copyProperties(basAddressDto, address);
            address.setId(SnowflakeIdUtil.nextId());
            address.setCreateBy(sysUserService.getCurrentUserName());
            this.save(address);
        }
    }

    @Override
    public BasAddressVo getDetail(Long id) {
        var result = new BasAddressVo();
        BasAddress address = this.getById(id);
        if(address == null){
            return null;
        }
        BeanUtils.copyProperties(address, result);
        if(result.getCountryId() != null){
            result.setCountry(basAreaService.getDetail(result.getCountryId()));
        }
        if(result.getProvinceId() != null){
            result.setProvince(basAreaService.getDetail(result.getProvinceId()));
        }
        if(result.getCityId() != null){
            result.setCity(basAreaService.getDetail(result.getCityId()));
        }
        if(result.getRegionId() != null){
            result.setRegion(basAreaService.getDetail(result.getRegionId()));
        }
        return result;
    }
}
