package cn.iocoder.foodnexus.module.order.service.customeraddress;

import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.module.order.controller.app.customeraddress.vo.CustomerAddressPageReqVO;
import cn.iocoder.foodnexus.module.order.controller.app.customeraddress.vo.CustomerAddressSaveReqVO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import cn.iocoder.foodnexus.module.order.dal.dataobject.customeraddress.CustomerAddressDO;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;

import cn.iocoder.foodnexus.module.order.dal.mysql.customeraddress.CustomerAddressMapper;

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.foodnexus.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.foodnexus.module.order.enums.ErrorCodeConstants.*;

/**
 * 客户 - 我的地址 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class CustomerAddressServiceImpl implements CustomerAddressService {

    @Resource
    private CustomerAddressMapper customerAddressMapper;

    @Override
    public Long createCustomerAddress(CustomerAddressSaveReqVO createReqVO) {
        Long loginUserId = getLoginUserId();
        if (createReqVO.getIsDefault()) {
            customerAddressMapper.update(Wrappers.<CustomerAddressDO>lambdaUpdate()
                    .set(CustomerAddressDO::getIsDefault, Boolean.FALSE)
                    .eq(CustomerAddressDO::getIsDefault, Boolean.TRUE)
                    .eq(CustomerAddressDO::getCreator, loginUserId));
        }
        if (!customerAddressMapper.exists(Wrappers.<CustomerAddressDO>lambdaQuery()
                .eq(CustomerAddressDO::getCreator, loginUserId))) {
            createReqVO.setIsDefault(Boolean.TRUE);
        }
        // 插入
        CustomerAddressDO customerAddress = BeanUtils.toBean(createReqVO, CustomerAddressDO.class);
        customerAddressMapper.insert(customerAddress);
        // 返回
        return customerAddress.getId();
    }

    @Override
    public void updateCustomerAddress(CustomerAddressSaveReqVO updateReqVO) {
        // 校验存在
        CustomerAddressDO customerAddressDO = validateCustomerAddressExists(updateReqVO.getId());
        if (!customerAddressDO.getIsDefault() && updateReqVO.getIsDefault()) {
            customerAddressMapper.update(Wrappers.<CustomerAddressDO>lambdaUpdate()
                    .set(CustomerAddressDO::getIsDefault, Boolean.FALSE)
                    .eq(CustomerAddressDO::getIsDefault, Boolean.TRUE)
                    .eq(CustomerAddressDO::getCreator, getLoginUserId()));
        }
        // 更新
        CustomerAddressDO updateObj = BeanUtils.toBean(updateReqVO, CustomerAddressDO.class);
        customerAddressMapper.updateById(updateObj);
    }

    @Override
    public void updateAddressDefault(Long id, Long loginUserId) {
        CustomerAddressDO customerAddressDO = validateCustomerAddressExists(id);
        if (!customerAddressDO.getIsDefault()) {
            customerAddressMapper.update(Wrappers.<CustomerAddressDO>lambdaUpdate()
                    .set(CustomerAddressDO::getIsDefault, Boolean.FALSE)
                    .eq(CustomerAddressDO::getIsDefault, Boolean.TRUE)
                    .eq(CustomerAddressDO::getCreator, loginUserId));
        }
        // 更新
        CustomerAddressDO updateObj = new CustomerAddressDO();
        updateObj.setId(id);
        updateObj.setIsDefault(Boolean.TRUE);
        customerAddressMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCustomerAddress(Long id) {
        // 校验存在
        CustomerAddressDO customerAddressDO = validateCustomerAddressExists(id);
        Boolean isDefault = customerAddressDO.getIsDefault();
        // 删除
        customerAddressMapper.deleteById(id);
        deleteSetDefault(isDefault, CommonUtil.asList(id));
    }

    @Override
    public void deleteCustomerAddressListByIds(List<Long> ids) {
        List<CustomerAddressDO> customerAddressDOS = customerAddressMapper.selectByIds(ids);
        boolean isDefault = customerAddressDOS.stream().anyMatch(CustomerAddressDO::getIsDefault);
        // 删除
        customerAddressMapper.deleteByIds(ids);
        deleteSetDefault(isDefault, ids);
    }

    private void deleteSetDefault(boolean isDefault, List<Long> ids) {
        if (isDefault) {
            Long loginUserId = getLoginUserId();
            CustomerAddressDO newAddress = customerAddressMapper.selectOne(Wrappers.<CustomerAddressDO>lambdaQuery()
                    .eq(CustomerAddressDO::getCreator, loginUserId)
                    .notIn(CustomerAddressDO::getId, ids)
                    .orderByDesc(CustomerAddressDO::getId)
                    .last("LIMIT 1"));
            if (CommonUtil.isNotEmpty(newAddress)) {
                this.updateAddressDefault(newAddress.getId(), loginUserId);
            }
        }
    }


    private CustomerAddressDO validateCustomerAddressExists(Long id) {
        CustomerAddressDO customerAddressDO = customerAddressMapper.selectById(id);
        if (customerAddressDO == null) {
            throw exception(CUSTOMER_ADDRESS_NOT_EXISTS);
        }
        return customerAddressDO;
    }

    @Override
    public CustomerAddressDO getCustomerAddress(Long id) {
        return customerAddressMapper.selectById(id);
    }

    @Override
    public PageResult<CustomerAddressDO> getCustomerAddressPage(CustomerAddressPageReqVO pageReqVO) {
        return customerAddressMapper.selectPage(pageReqVO);
    }

    @Override
    public boolean existsById(Long addressId) {
        return customerAddressMapper.exists(Wrappers.<CustomerAddressDO>lambdaQuery()
                .eq(CustomerAddressDO::getId, addressId));
    }

}