package com.gxwebsoft.common.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.*;
import com.gxwebsoft.common.system.service.PaymentService;
import com.gxwebsoft.common.system.param.PaymentParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 支付方式控制器
 *
 * @author 科技小王子
 * @since 2024-05-11 12:39:11
 */
@Tag(name = "支付")
@RestController
@RequestMapping("/api/system/payment")
public class PaymentController extends BaseController {
    @Resource
    private PaymentService paymentService;
    @Resource
    private RedisUtil redisUtil;

    @Operation(summary = "选择支付方式")
    @GetMapping("/select")
    public ApiResult<?> select(PaymentParam param) {
      String key = "SelectPayment:".concat(getTenantId().toString());
      final String string = redisUtil.get(key);
      final List<Payment> paymentList = JSONObject.parseArray(string, Payment.class);
      if (!CollectionUtils.isEmpty(paymentList)) {
        return success(paymentList);
      }
      // 使用关联查询
      final List<Payment> list = paymentService.list(new LambdaUpdateWrapper<Payment>().eq(Payment::getStatus, true));
      if (!CollectionUtils.isEmpty(list)) {
        list.forEach(d -> {
          d.setApiKey(null);
          d.setApiclientCert(null);
          d.setApiclientKey(null);
          d.setMerchantSerialNumber(null);
        });
      }
      redisUtil.set(key,list,1L, TimeUnit.DAYS);
      return success(list);
    }

    @PreAuthorize("hasAuthority('sys:payment:list')")
    @Operation(summary = "分页查询支付方式")
    @GetMapping("/page")
    public ApiResult<PageResult<Payment>> page(PaymentParam param) {
        PageParam<Payment, PaymentParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time asc");
        return success(paymentService.page(page, page.getWrapper()));
        // 使用关联查询
//        return success(paymentService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('sys:payment:list')")
    @Operation(summary = "查询全部支付方式")
    @GetMapping()
    public ApiResult<List<Payment>> list(PaymentParam param) {
        PageParam<Payment, PaymentParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time asc");
        return success(paymentService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(paymentService.listRel(param));
    }

    @PreAuthorize("hasAuthority('sys:payment:list')")
    @Operation(summary = "根据id查询支付方式")
    @GetMapping("/{id}")
    public ApiResult<Payment> get(@PathVariable("id") Integer id) {
        return success(paymentService.getById(id));
        // 使用关联查询
        //return success(paymentService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('sys:payment:save')")
    @OperationLog
    @Operation(summary = "添加支付方式")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Payment payment) {
        if (paymentService.count(new LambdaQueryWrapper<Payment>().eq(Payment::getCode,payment.getCode())) > 0) {
          return fail(payment.getName() + "已存在");
        }
        if (paymentService.save(payment)) {
            String key = "Payment:" + payment.getCode() + ":" + getTenantId();
            redisUtil.set(key,payment);
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('sys:payment:update')")
    @OperationLog
    @Operation(summary = "修改支付方式")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Payment payment) {
        if (paymentService.updateById(payment)) {
            String key = "Payment:" + payment.getCode() + ":" + getTenantId();
            redisUtil.set(key,payment);
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:payment:remove')")
    @OperationLog
    @Operation(summary = "删除支付方式")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        final Payment payment = paymentService.getById(id);
      System.out.println("payment = " + payment);
        String key = "Payment:" + payment.getCode() + ":" + getTenantId();
        redisUtil.delete(key);
        if (paymentService.removeById(id)) {
          return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('sys:payment:save')")
    @OperationLog
    @Operation(summary = "批量添加支付方式")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Payment> list) {
        if (paymentService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('sys:payment:update')")
    @OperationLog
    @Operation(summary = "批量修改支付方式")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Payment> batchParam) {
        if (batchParam.update(paymentService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('sys:payment:remove')")
    @OperationLog
    @Operation(summary = "批量删除支付方式")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (paymentService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
