package com.gxwebsoft.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.security.JwtUtil;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.utils.RequestUtil;
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.Merchant;
import com.gxwebsoft.shop.entity.MerchantAccount;
import com.gxwebsoft.shop.param.MerchantParam;
import com.gxwebsoft.shop.service.MerchantAccountService;
import com.gxwebsoft.shop.service.MerchantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 商户控制器
 *
 * @author 科技小王子
 * @since 2024-04-05 00:03:54
 */
@Api(tags = "商户管理")
@RestController
@RequestMapping("/api/shop/merchant")
public class MerchantController extends BaseController {
    @Resource
    private MerchantService merchantService;
    @Resource
    private MerchantAccountService merchantAccountService;

    @ApiOperation("分页查询商户")
    @GetMapping("/page")
    public ApiResult<PageResult<Merchant>> page(MerchantParam param) {
        // 使用关联查询
      System.out.println("param = " + param);
        return success(merchantService.pageRel(param));
    }

    @ApiOperation("查询全部商户")
    @GetMapping()
    public ApiResult<List<Merchant>> list(MerchantParam param) {
        // 使用关联查询
        return success(merchantService.listRel(param));
    }

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

    @ApiOperation("查询我的商户")
    @GetMapping("/getByUserId")
    public ApiResult<Merchant> getByUserId() {
      final Merchant one = merchantService.getOne(new LambdaQueryWrapper<Merchant>().eq(Merchant::getUserId, getLoginUserId()));
      if (ObjectUtil.isNotEmpty(one)) {
        return success(one);
      }
      return fail("未注册商户",null);
    }

    @PreAuthorize("hasAuthority('shop:merchant:save')")
    @ApiOperation("添加商户")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Merchant merchant, HttpServletRequest request) {
      if (merchantService.count(new LambdaQueryWrapper<Merchant>().eq(Merchant::getPhone,merchant.getPhone())) > 0) {
        return fail("商户手机号码" + merchant.getPhone() + "已存在");
      }
      if (merchantService.save(merchant)) {
          // 设置商家后台入口
          merchant.setAdminUrl(merchant.getTenantId() + ".m.wsdns.cn");
          merchantService.updateById(merchant);
          // 获取用户信息
          final RequestUtil requestUtil = new RequestUtil();
          String access_token = JwtUtil.getAccessToken(request);
          requestUtil.setAccessToken(access_token);
          requestUtil.setTenantId(getTenantId().toString());
          final MerchantAccount merchantAccount = new MerchantAccount();
          merchantAccount.setMerchantId(merchant.getMerchantId());
          merchantAccount.setPhone(merchant.getPhone());
          merchantAccount.setPassword(merchant.getPhone().substring(merchant.getPhone().length() - 6));
          merchantAccount.setRealName(merchant.getRealName());
          merchantAccount.setRoleId(merchant.getRoleId());
          merchantAccount.setRoleName(merchant.getRoleName());
          requestUtil.saveUserByPhone(merchantAccount);
          merchantAccountService.save(merchantAccount);
          return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:merchant:update')")
    @ApiOperation("修改商户")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Merchant merchant) {
        if (merchantService.updateById(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)) {
            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)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
