package com.ruoyi.frequency.malladdress.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.enums.CoreExceptionEnum;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.controller.req.AddressInsertReq;
import com.ruoyi.controller.req.AddressUpdateReq;
import com.ruoyi.frequency.malladdress.entity.MallAddress;
import com.ruoyi.frequency.malladdress.mapper.MallAddressMapper;
import com.ruoyi.frequency.malladdress.service.MallAddressService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.JudgeLogicUtil;
import com.ruoyi.vo.PageBasic;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 地址Service业务层处理
 *
 * @author liwenlong
 * @date 2024-01-25
 */
@Service
public class MallAddressServiceImpl extends ServiceImpl<MallAddressMapper, MallAddress>  implements MallAddressService
{
    @Autowired
    private MallAddressMapper mallAddressMapper;

    /**
     * 查询地址
     *
     * @param id 地址主键
     * @return 地址
     */
    @Override
    public MallAddress selectMallAddressById(Long id)
    {
        return mallAddressMapper.selectMallAddressById(id);
    }

    /**
     * 查询地址列表
     *
     * @param mallAddress 地址
     * @return 地址
     */
    @Override
    public List<MallAddress> selectMallAddressList(MallAddress mallAddress)
    {
        return mallAddressMapper.selectMallAddressList(mallAddress);
    }

    /**
     * 新增地址
     *
     * @param mallAddress 地址
     * @return 结果
     */
    @Override
    public int insertMallAddress(MallAddress mallAddress)
    {
        mallAddress.setCreateData();
        return mallAddressMapper.insert(mallAddress);
    }

    /**
     * 修改地址
     *
     * @param mallAddress 地址
     * @return 结果
     */
    @Override
    public int updateMallAddress(MallAddress mallAddress)
    {
        mallAddress.setUpdateData();
        return mallAddressMapper.updateMallAddress(mallAddress);
    }

    /**
     * 批量删除地址
     *
     * @param ids 需要删除的地址主键
     * @return 结果
     */
    @Override
    public int deleteMallAddressByIds(Long[] ids,Integer delFlag)
    {
        this.lambdaUpdate().set(MallAddress::getDelFlag,delFlag).in(MallAddress::getId,ids).update();
        return ids.length;
    }

    @Override
    public ResponseData addressPage(UserVo user, PageBasic page) {

        Page<MallAddress> addressPage = baseMapper.selectPage(new Page<>(page.getPageNo(), page.getPageSize()), new QueryWrapper<MallAddress>()
                .lambda()
                .eq(MallAddress::getUserId, user.getUserId())
                .eq(MallAddress::getUserType,user.getUserType())
                .ne(MallAddress::getDelFlag, PublicCommon.删除)
                .orderByDesc(MallAddress::getIsDefault).orderByDesc(MallAddress::getCreateTime));

        return ResponseData.success(new PageResult<>(addressPage));
    }


    @Autowired
    private JudgeLogicUtil judgeLogicUtil;

    @Override
    public ResponseData insertAddress(AddressInsertReq addressInsertReq, UserVo userVo) {
        MallAddress address = new MallAddress();
        BeanUtils.copyProperties(addressInsertReq, address);

        address.setUserId(userVo.getUserId())
                .setUserType(userVo.getUserType());

        //默认地址唯一，用户拥有默认地址，改为非默认
        if (ObjectUtil.equal(PublicCommon.默认,addressInsertReq.getIsDefault())){
            this.lambdaUpdate().set(MallAddress::getIsDefault,PublicCommon.非默认)
                    .eq(MallAddress::getIsDefault,PublicCommon.默认)
                    .eq(MallAddress::getUserId,userVo.getUserId())
                    .eq(MallAddress::getUserType,userVo.getUserType())
                    .update();
        }

        int insertCount = this.baseMapper.insert(address);

        if (insertCount == 0) {
            throw  new CustomException(CoreExceptionEnum.INSERT_DATA);
        }

        return ResponseData.success(address);
    }

    @Override
    public ResponseData updateAddress(AddressUpdateReq addressUpdateReq, UserVo userVo) {

        MallAddress address = this.baseMapper.selectById(addressUpdateReq.getId());

        if (address == null) {
            throw  new CustomException(CoreExceptionEnum.RESOURCES_NOT_EXIST);
        }

        //默认地址唯一，用户拥有默认地址，改为非默认
        if (ObjectUtil.equal(PublicCommon.默认,addressUpdateReq.getIsDefault())){
            this.lambdaUpdate().set(MallAddress::getIsDefault,PublicCommon.非默认)
                    .ne(MallAddress::getId,addressUpdateReq.getId())
                    .eq(MallAddress::getIsDefault,PublicCommon.默认)
                    .eq(MallAddress::getUserId,userVo.getUserId())
                    .eq(MallAddress::getUserType,userVo.getUserType())
                    .update();
        }

        BeanUtils.copyProperties(addressUpdateReq, address);

        this.baseMapper.updateById(address);

        return ResponseData.success(address);
    }

    @Override
    public ResponseData setDefault(Long id) {

        MallAddress address = baseMapper.selectById(id);

        if (address == null) {
            throw  new CustomException(CoreExceptionEnum.RESOURCES_NOT_EXIST);
        }

        //修改后的状态
        Integer isDefault = ObjectUtil.equal(address.getIsDefault(),PublicCommon.默认)?PublicCommon.非默认:PublicCommon.默认;

        //默认地址唯一，用户拥有默认地址，改为非默认
        if (ObjectUtil.equal(PublicCommon.默认,isDefault)){
            this.lambdaUpdate().set(MallAddress::getIsDefault,PublicCommon.非默认)
                    .ne(MallAddress::getId,id)
                    .eq(MallAddress::getIsDefault,PublicCommon.默认)
                    .eq(MallAddress::getUserId,address.getUserId())
                    .eq(MallAddress::getUserType,address.getUserType())
                    .update();
        }

        boolean update = this.update().set("is_default", isDefault).eq("id", id).update();
        if (!update){
            throw  new CustomException(CoreExceptionEnum.UPDATE_DATA);
        }

        return ResponseData.success();
    }

    @Override
    public ResponseData deleteAddressById(List<Long> addressIds,UserVo userVo) {

        this.lambdaUpdate().set(MallAddress::getDelFlag,PublicCommon.删除)
                .in(addressIds != null && addressIds.size() > 0 ,MallAddress::getId,addressIds)
                .eq(MallAddress::getUserType,userVo.getUserType())
                .eq(MallAddress::getUserId,userVo.getUserId())
                .ne(MallAddress::getDelFlag,PublicCommon.删除)
                .update();

        return ResponseData.success();
    }

    @Override
    public ResponseData getDefaultAddress(UserVo userVo) {
        MallAddress address = this.baseMapper.selectOne(Wrappers.<MallAddress>lambdaQuery()
                .eq(MallAddress::getIsDefault, PublicCommon.默认)
                .eq(MallAddress::getUserId, userVo.getUserId())
                .eq(MallAddress::getUserType,userVo.getUserType())
                .eq(MallAddress::getDelFlag, PublicCommon.启用)
                .last("limit 1")
        );
        return ResponseData.success(address);
    }
}
