package com.gxwebsoft.shop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.shop.entity.Merchant;
import com.gxwebsoft.shop.entity.MerchantWithdraw;
import com.gxwebsoft.shop.param.MerchantParam;
import com.gxwebsoft.shop.service.MerchantService;
import com.gxwebsoft.shop.service.MerchantWithdrawService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

import static com.gxwebsoft.common.core.constants.RedisConstants.MERCHANT_GEO_KEY;
import static com.gxwebsoft.common.core.constants.RedisConstants.MERCHANT_KEY;

/**
 * 商户管理控制器
 *
 * @author 科技小王子
 * @since 2022-11-30 15:10:54
 */
@Api(tags = "商户管理管理")
@RestController
@RequestMapping("/api/shop/merchant")
public class MerchantController extends BaseController {
    @Resource
    private MerchantService merchantService;
    @Resource
    private CacheClient cacheClient;
    @Resource
    private MerchantWithdrawService merchantWithdrawService;

    @PreAuthorize("hasAuthority('shop:merchant:list')")
    @ApiOperation("分页查询商户管理")
    @GetMapping("/page")
    public ApiResult<PageResult<Merchant>> page(MerchantParam param) {
        // 使用关联查询
        return success(merchantService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('shop:merchant:list')")
    @ApiOperation("查询全部商户管理")
    @GetMapping()
    public ApiResult<List<Merchant>> list(MerchantParam param) {
        PageParam<Merchant, MerchantParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        // 使用关联查询
        return success(merchantService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:merchant:list')")
    @ApiOperation("根据id查询商户管理")
    @GetMapping("/{id}")
    public ApiResult<Merchant> get(@PathVariable("id") Integer id) {
      // 使用关联查询
        return success(merchantService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('shop:merchant:save')")
    @ApiOperation("添加商户管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Merchant merchant) {
        if (merchantService.count(new LambdaQueryWrapper<Merchant>()
          .eq(Merchant::getMerchantCode, merchant.getMerchantCode())) > 0) {
          return fail("商户编号已存在");
        }
        if (merchantService.save(merchant)) {
            // 添加缓存
            String lngAndLat = merchant.getLngAndLat();
            String[] split = lngAndLat.split(",");
            Double x = Double.parseDouble(split[0]);
            Double y = Double.parseDouble(split[1]);
            String id = merchant.getMerchantId().toString();
            cacheClient.geoAdd(MERCHANT_GEO_KEY,x,y,id);
            cacheClient.set(MERCHANT_KEY.concat(":").concat(merchant.getMerchantId().toString()),merchant);
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:update')")
    @ApiOperation("修改商户管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Merchant merchant) {
        // 超级管理员不能设为店主
        if(getLoginUser().getUserId().equals(merchant.getMerchantOwner())){
          return fail("超级管理员不能绑定为负责人！");
        }
        if (merchantService.updateById(merchant)) {
            // 添加缓存
            String lngAndLat = merchant.getLngAndLat();
            String[] split = lngAndLat.split(",");
            Double x = Double.parseDouble(split[0]);
            Double y = Double.parseDouble(split[1]);
            String id = merchant.getMerchantId().toString();
            cacheClient.geoAdd(MERCHANT_GEO_KEY,x,y,id);
            cacheClient.geoAdd(MERCHANT_GEO_KEY,x,y,id);
            cacheClient.set(MERCHANT_KEY.concat(":").concat(merchant.getMerchantId().toString()),merchant);
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:remove')")
    @ApiOperation("删除商户管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (merchantService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:save')")
    @ApiOperation("批量添加商户管理")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Merchant> list) {
        if (merchantService.saveBatch(list)) {
            list.forEach(d -> {
              // 添加缓存
              String lngAndLat = d.getLngAndLat();
              String[] split = lngAndLat.split(",");
              Double x = Double.parseDouble(split[0]);
              Double y = Double.parseDouble(split[1]);
              String id = d.getMerchantId().toString();
              cacheClient.geoAdd(MERCHANT_GEO_KEY,x,y,id);
              cacheClient.geoAdd(MERCHANT_GEO_KEY,x,y,id);
              cacheClient.set(MERCHANT_KEY.concat(":").concat(d.getMerchantId().toString()),d);
            });
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:update')")
    @ApiOperation("批量修改商户管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Merchant> batchParam) {
        if (batchParam.update(merchantService, "merchant_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:remove')")
    @ApiOperation("批量删除商户管理")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (merchantService.removeByIds(ids)) {
            // 删除缓存
            ids.forEach(id -> {
              cacheClient.geoRemove(MERCHANT_GEO_KEY,id);
            });
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:list')")
    @ApiOperation("根据定位查询附近的商户列表")
    @PostMapping("/getListByGeo")
    public ApiResult<List<Merchant>> getListByGeo(@RequestBody MerchantParam param) {
      return success(merchantService.listByGeo(param));
    }

    @PreAuthorize("hasAuthority('shop:merchant:list')")
    @ApiOperation("提现申请")
    @PostMapping("/addWithdraw")
    public ApiResult<?> addWithdraw(@RequestBody Merchant merchant) {
      // 提现金额是否不足
      if(merchant.getAmount().compareTo(merchant.getMoney()) > 0){
        return fail("可提现金额不足");
      }
      // 提现金额不能等于0
      if(merchant.getAmount().compareTo(BigDecimal.ZERO) == 0){
        return fail("提现金额不正确");
      }

      // 保存提现账号
      final Merchant data = new Merchant();
      data.setMerchantId(merchant.getMerchantId());
      data.setAlipayName(merchant.getAlipayName());
      data.setAlipayAccount(merchant.getAlipayAccount());
      data.setBankName(merchant.getBankName());
      data.setBankAccount(merchant.getBankAccount());
      data.setBankCard(merchant.getBankCard());
      // 扣除提现金额
      data.setMoney(merchant.getMoney().subtract(merchant.getAmount()));
      // 冻结金额
      data.setFreezeMoney(merchant.getFreezeMoney().add(merchant.getAmount()));
      merchantService.updateById(data);
      // 记录明细
      final MerchantWithdraw withdraw = new MerchantWithdraw();
      withdraw.setUserId(merchant.getUserId());
      withdraw.setMoney(merchant.getAmount().subtract(merchant.getAmount().multiply(new BigDecimal("0.04"))));
      withdraw.setPayType(merchant.getPayType());
      withdraw.setAlipayName(merchant.getAlipayName());
      withdraw.setAlipayAccount(merchant.getAlipayAccount());
      withdraw.setBankName(merchant.getBankName());
      withdraw.setBankAccount(merchant.getBankAccount());
      withdraw.setBankCard(merchant.getBankCard());
      merchantWithdrawService.save(withdraw);

      return success("已收到您的提交申请",null);
    }

    @PreAuthorize("hasAuthority('shop:merchant:update')")
    @ApiOperation("冻结收益")
    @PutMapping("/onFreezeMoney")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> onFreezeMoney(@RequestBody Merchant merchant) {
      Merchant merchant1 = merchantService.getById(merchant.getMerchantId());
      merchant1.setMoney(merchant1.getMoney().subtract(merchant.getMoney()));
      merchant1.setFreezeMoney(merchant1.getFreezeMoney().add(merchant.getMoney()));
      if (merchantService.updateById(merchant1)) {
        return success("操作成功");
      }
      return fail("操作失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:update')")
    @ApiOperation("冻结收益")
    @PutMapping("/onUnFreezeMoney")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> onUnFreezeMoney(@RequestBody Merchant merchant) {
      Merchant merchant1 = merchantService.getById(merchant.getMerchantId());
      merchant1.setMoney(merchant1.getMoney().add(merchant.getFreezeMoney()));
      merchant1.setFreezeMoney(merchant1.getFreezeMoney().subtract(merchant.getFreezeMoney()));
      if (merchantService.updateById(merchant1)) {
        return success("操作成功");
      }
      return fail("操作失败");
    }

}
