package com.gxwebsoft.open.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.param.MerchantParam;
import com.gxwebsoft.shop.service.MerchantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
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/open/merchant")
public class OpenMerchantController extends BaseController {
    @Resource
    private MerchantService merchantService;
    @Resource
    private CacheClient cacheClient;

    @ApiOperation("分页查询商户管理")
    @GetMapping("/page")
    public ApiResult<PageResult<Merchant>> page(MerchantParam param) {
        // 验证签名
        isCheckSign();
        // 搜索条件
        if (getMerchantCode() != null) {
          param.setMerchantCode(getMerchantCode());
        }
        // 使用关联查询
        return success(merchantService.pageRel(param));
    }

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

    @ApiOperation("根据id查询商户管理")
    @GetMapping("/{id}")
    public ApiResult<Merchant> get(@PathVariable("id") Integer id) {
      // 验证签名
      isCheckSign();
      // 使用关联查询
        return success(merchantService.getByIdRel(id));
    }

    @ApiOperation("添加商户管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Merchant merchant) {
      // 验证签名
      isCheckSign();
        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("添加失败");
    }

    @ApiOperation("修改商户管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Merchant merchant) {
      // 验证签名
      isCheckSign();
        // 超级管理员不能设为店主
        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("修改失败");
    }

    @ApiOperation("删除商户管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
      // 验证签名
      isCheckSign();
        if (merchantService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @ApiOperation("批量添加商户管理")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Merchant> list) {
      // 验证签名
      isCheckSign();
        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("添加失败");
    }

    @ApiOperation("批量修改商户管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Merchant> batchParam) {
      // 验证签名
      isCheckSign();
        if (batchParam.update(merchantService, "merchant_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

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

    @ApiOperation("根据定位查询附近的商户列表")
    @PostMapping("/getListByGeo")
    public ApiResult<List<Merchant>> getListByGeo(@RequestBody MerchantParam param) {
      // 验证签名
      isCheckSign();
      return success(merchantService.listByGeo(param));
    }
}
