package com.org.hktshop.service.user.impl;

import com.org.hktshop.base.BaseService;
import com.org.hktshop.entity.user.HktUserAddress;
import com.org.hktshop.service.user.HktUserAddressService;
import com.org.hktshop.utils.ExecSqlLib;
import com.org.hktshop.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HktUserAddressServiceImpl extends BaseService<HktUserAddress> implements HktUserAddressService {

    @Override
    public void updateHktUserAddress(HktUserAddress hktUserAddress) {
        if(hktUserAddress.getIsDefault() != null && hktUserAddress.getIsDefault() == 1){
            String sql = "update hkt_user_address set is_default = 0 where user_id = "+hktUserAddress.getUserId();
            this.baseJdbcDao.execute(sql);
        }
        this.updateJdbc(hktUserAddress);
    }

    @Override
    public List<HktUserAddress> getHktUserAddress(String userId,String distribution) {
        HktUserAddress hktUserAddress = new HktUserAddress();
        hktUserAddress.setUserId(userId);
        if(!StringUtils.isNull(distribution)){
            hktUserAddress.setDistribution(distribution);
        }
        List<HktUserAddress> hktUserAddressList = this.baseJdbcDao.queryList(ExecSqlLib.GetQuerySql(hktUserAddress), hktUserAddress);
        if (hktUserAddressList.size() == 1) {
            hktUserAddress.setId(hktUserAddressList.get(0).getId());
            hktUserAddress.setIsDefault(1);
            updateJdbc(hktUserAddress);
            hktUserAddressList.get(0).setIsDefault(1);
        }
        return hktUserAddressList;
    }

    @Override
    public void deleteHktUserAddress(HktUserAddress hktUserAddress) {
        deleteById(hktUserAddress.getId(), hktUserAddress);
    }

    @Override
    public void setDefaultAddress(String userId, String id) {

        List<String> sqls = new ArrayList<>();
        sqls.add(String.format("update hkt_user_address set is_default = 0 where user_id ='%s'", userId));
        sqls.add(String.format("update hkt_user_address set is_default = 1 where user_id ='%s' and id='%s'", userId, id));

        this.baseJdbcDao.executeTransaction(sqls);
    }

    @Override
    public HktUserAddress getDefaultAddress(String userId) {
        HktUserAddress userAddress=new HktUserAddress();
        userAddress.setUserId(userId);
        userAddress.setIsDefault(1);
        return this.baseJdbcDao.query(ExecSqlLib.GetQuerySql(userAddress),userAddress);
    }
}
