package com.qs.mp.web.controller.api.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qs.mp.user.domain.UserAddr;
import com.qs.mp.channel.domain.param.AddrParam;
import com.qs.mp.user.service.IUserAddrService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api/v1/mp/user")
@Api(tags = "地址接口")
@AllArgsConstructor
public class UserAddrController {


  @Autowired
  private IUserAddrService userAddrService;

  @Autowired
  private MapperFacade mapperFacade;

  /**
   * 选择订单配送地址
   */
  @PostMapping("/addr/list")
  @ApiOperation(value = "渠道地址列表" , notes = "获取渠道的所有地址信息")
  public AjaxResult list(@RequestBody AddrParam addrParam) {
    Long userId = SecurityUtils.getLoginUser().getUserId();
    List<UserAddr> userAddrs = userAddrService.list(
        new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId)
            .orderByDesc(UserAddr::getCommonAddr).orderByDesc(UserAddr::getUpdateTime));
    return AjaxResult.success(userAddrs);
  }

  @PostMapping("/addr/create")
  @ApiOperation(value = "新增用户地址" , notes = "新增用户地址")
  public AjaxResult create(@Valid @RequestBody AddrParam addrParam) {
    Long userId = SecurityUtils.getLoginUser().getUserId();

    if (addrParam.getAddrId() != null && addrParam.getAddrId() != 0) {
      return AjaxResult.error("该地址已存在");
    }
    int addrCount = userAddrService.count(
        new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId));
    UserAddr userAddr = mapperFacade.map(addrParam, UserAddr.class);

    if (addrCount == 0) {
      userAddr.setCommonAddr(1);
    } else {
      userAddr.setCommonAddr(0);
    }
    userAddr.setUserId(userId);
    userAddr.setStatus(1);
    userAddr.setCreateTime(new Date());
    userAddr.setUpdateTime(new Date());
    userAddrService.save(userAddr);

    return AjaxResult.success("添加地址成功");
  }

  /**
   * 修改订单配送地址
   */
  @PostMapping("/addr/update")
  @ApiOperation(value = "修改订单用户地址" , notes = "修改用户地址")
  public AjaxResult update(@Valid @RequestBody AddrParam addrParam) {
    Long userId = SecurityUtils.getLoginUser().getUserId();

    UserAddr dbChannelAddr = userAddrService.getChannelAddrByUserId(addrParam.getAddrId(),
        userId);
    if (dbChannelAddr == null) {
      return AjaxResult.error("该地址已被删除");
    }

    UserAddr userAddr = mapperFacade.map(addrParam, UserAddr.class);
    userAddr.setUserId(userId);
    userAddrService.updateById(userAddr);
    return AjaxResult.success("修改地址成功");
  }

  /**
   * 删除订单配送地址
   */
  @PostMapping("/addr/remove")
  @ApiOperation(value = "删除订单用户地址" , notes = "根据地址id，删除用户地址")
  public AjaxResult remove(@RequestBody AddrParam addrParam) {
    if (addrParam.getAddrId() == null || addrParam.getAddrId() == 0) {
      return AjaxResult.error("参数异常，地址ID缺失");
    }
    Long userId = SecurityUtils.getLoginUser().getUserId();
    UserAddr channelAddr = userAddrService.getChannelAddrByUserId(addrParam.getAddrId(),
        userId);
    if (channelAddr == null) {
      return AjaxResult.error("该地址已被删除");
    }
    if (channelAddr.getCommonAddr() == 1) {
      return AjaxResult.error("默认地址无法删除");
    }
    userAddrService.removeById(addrParam.getAddrId());
    return AjaxResult.success();
  }

  /**
   * 设置默认地址
   */
  @PostMapping("/addr/setDefault")
  @ApiOperation(value = "设置默认地址" , notes = "根据地址id，设置默认地址")
  public AjaxResult defaultAddr(@RequestBody AddrParam addrParam) {
    if (addrParam.getAddrId() == null || addrParam.getAddrId() == 0) {
      return AjaxResult.error("参数异常，地址ID缺失");
    }
    Long userId = SecurityUtils.getLoginUser().getUserId();
    userAddrService.updateDefaultChannelAddr(addrParam.getAddrId(), userId);
    return AjaxResult.success();
  }

  /**
   * 查询默认地址
   */
  @PostMapping("/addr/queryDefault")
  @ApiOperation(value = "查询默认地址" , notes = "查询默认地址")
  public AjaxResult queryDefaultAddr(@RequestBody AddrParam addrParam) {
    Long userId = SecurityUtils.getLoginUser().getUserId();
    UserAddr addr = userAddrService.getDefaultChannelAddr(userId);
    return AjaxResult.success(addr);
  }

  /**
   * 获取配送地址
   */
  @PostMapping("/addr/query")
  @ApiOperation(value = "获取地址信息" , notes = "根据地址id，获取地址信息")
  public AjaxResult info(@RequestBody AddrParam addrParam) {
    if (addrParam.getAddrId() == null || addrParam.getAddrId() == 0) {
      return AjaxResult.error("参数异常，地址ID缺失");
    }
    Long userId = SecurityUtils.getLoginUser().getUserId();
    UserAddr channelAddr = userAddrService.getChannelAddrByUserId(addrParam.getAddrId(),
        userId);
    return AjaxResult.success(channelAddr);
  }

}
