package com.gxwebsoft.shop.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.DealerUser;
import com.gxwebsoft.shop.param.DealerUserParam;
import com.gxwebsoft.shop.service.DealerUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
import java.util.List;

import static com.gxwebsoft.common.core.constants.RedisConstants.ACCESS_TOKEN_KEY;

/**
 * 分销商用户记录表控制器
 *
 * @author 科技小王子
 * @since 2024-07-28 19:21:15
 */
@Api(tags = "分销商用户记录表管理")
@RestController
@RequestMapping("/api/shop/dealer-user")
public class DealerUserController extends BaseController {
  @Resource
  private DealerUserService dealerUserService;
  @Resource
  private RedisUtil redisUtil;
  @Resource
  private ConfigProperties config;


  @ApiOperation("生成专属二维码")
  @GetMapping("/getDealerUserQrcode")
  public ApiResult<?> getDealerUserQrcode() {
    final Integer loginUserId = getLoginUserId();
    if(loginUserId == null){
      return fail("请先登录");
    }

    final DealerUser dealerUser = dealerUserService.getOne(new LambdaQueryWrapper<DealerUser>().eq(DealerUser::getUserId, loginUserId).last("limit 1"));

    // 生成小程序码
    String apiUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + getAccessToken();
    final HashMap<String, Object> map = new HashMap<>();
    map.put("path", "package/dealer/invite?id=" + loginUserId);
    map.put("env_version", "trial"); // 正式版为"release"，体验版为"trial"，开发版为"develop"

    // 获取图片 Buffer
    byte[] qrCode = HttpRequest.post(apiUrl)
      .body(JSON.toJSONString(map))
      .execute().bodyBytes();

    // 保存的文件名称
    final String fileName = loginUserId.toString().concat(".png");
    // 保存路径
    String filePath = getUploadDir().concat("user-code/") + fileName;
    File file = FileUtil.writeBytes(qrCode, filePath);

    if (file != null) {
      final String qrcode = config.getFileServer().concat("/user-code/").concat(fileName);
      dealerUser.setQrcode(qrcode);
      dealerUserService.updateById(dealerUser);
      return success("操作成功",qrcode);
    }
    return success(dealerUser);
  }

  @ApiOperation("分页查询分销商用户记录表")
  @GetMapping("/page")
  public ApiResult<PageResult<DealerUser>> page(DealerUserParam param) {
    // 使用关联查询
    return success(dealerUserService.pageRel(param));
  }

  @ApiOperation("查询全部分销商用户记录表")
  @GetMapping()
  public ApiResult<List<DealerUser>> list(DealerUserParam param) {
    // 使用关联查询
    return success(dealerUserService.listRel(param));
  }

  @ApiOperation("根据id查询分销商用户记录表")
  @GetMapping("/{id}")
  public ApiResult<DealerUser> get(@PathVariable("id") Integer id) {
    // 分销商信息
    final DealerUser dealerUser = dealerUserService.getOne(new LambdaQueryWrapper<DealerUser>()
      .eq(DealerUser::getUserId, id)
      .eq(DealerUser::getIsDelete, 0)
      .last("limit 1")
    );
    // 上级分销商
    final DealerUser dealerUser1 = dealerUserService.getOne(new LambdaQueryWrapper<DealerUser>()
      .eq(DealerUser::getUserId, dealerUser.getRefereeId())
      .eq(DealerUser::getIsDelete, 0));
    dealerUser.setDealerName(dealerUser1.getRealName());
    dealerUser.setDealerUser(dealerUser1);
    return success(dealerUser);
  }

  @ApiOperation("添加分销商用户记录表")
  @PostMapping()
  public ApiResult<?> save(@RequestBody DealerUser dealerUser) {
    // 记录当前登录用户id
    User loginUser = getLoginUser();
    if (loginUser != null) {
      dealerUser.setUserId(loginUser.getUserId());
    }
    if (dealerUserService.save(dealerUser)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @ApiOperation("修改分销商用户记录表")
  @PutMapping()
  public ApiResult<?> update(@RequestBody DealerUser dealerUser) {
    if (dealerUserService.updateById(dealerUser)) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @ApiOperation("删除分销商用户记录表")
  @DeleteMapping("/{id}")
  public ApiResult<?> remove(@PathVariable("id") Integer id) {
    if (dealerUserService.removeById(id)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @ApiOperation("批量添加分销商用户记录表")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<DealerUser> list) {
    if (dealerUserService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @ApiOperation("批量修改分销商用户记录表")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<DealerUser> batchParam) {
    if (batchParam.update(dealerUserService, "id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @ApiOperation("批量删除分销商用户记录表")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (dealerUserService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }


  private String getAccessToken() {
    String key = ACCESS_TOKEN_KEY.concat(":").concat(getTenantId().toString());
    // 从缓存获取access_token
    final String value = redisUtil.get(key);
    if (value != null) {
      // 解析access_token
      JSONObject response = JSON.parseObject(value);
      return response.getString("access_token");
    }

    return null;
  }


  private String getUploadDir() {
    return config.getUploadPath() + "file/";
  }
}
