package com.gxwebsoft.open.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayOpenAppQrcodeCreateModel;
import com.alipay.api.request.AlipayOpenAppQrcodeCreateRequest;
import com.alipay.api.response.AlipayOpenAppQrcodeCreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.apps.entity.Equipment;
import com.gxwebsoft.apps.entity.EquipmentRecord;
import com.gxwebsoft.apps.param.EquipmentParam;
import com.gxwebsoft.apps.service.EquipmentRecordService;
import com.gxwebsoft.apps.service.EquipmentService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.utils.AlipayConfigUtil;
import com.gxwebsoft.common.core.web.*;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderRefund;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.OrderRefundService;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
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.apps.constants.EquipmentConstants.*;
import static com.gxwebsoft.common.core.constants.OrderConstants.*;

/**
 * 设备管理控制器
 *
 * @author 科技小王子
 * @since 2022-11-30 02:11:16
 */
@Api(tags = "设备管理管理")
@RestController
@RequestMapping("/api/open/equipment")
public class OpenEquipmentController extends BaseController {
    @Resource
    private EquipmentService equipmentService;
    @Resource
    private OrderService orderService;
    @Resource
    private AlipayConfigUtil alipayConfig;
    @Resource
    private EquipmentRecordService equipmentRecordService;
    @Resource
    private OrderRefundService orderRefundService;

    @PreAuthorize("hasAuthority('apps:equipment:list')")
    @OperationLog
    @ApiOperation("分页查询设备管理")
    @GetMapping("/page")
    public ApiResult<PageResult<Equipment>> page(EquipmentParam param) {
        // 使用关联查询
        PageParam<Equipment, EquipmentParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        if (getMerchantCode() != null) {
          param.setMerchantCode(getMerchantCode());
        }
        return success(equipmentService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('apps:equipment:list')")
    @OperationLog
    @ApiOperation("查询全部设备管理")
    @GetMapping()
    public ApiResult<List<Equipment>> list(EquipmentParam param) {
        PageParam<Equipment, EquipmentParam> page = new PageParam<>(param);
//        page.setDefaultOrder("create_time desc");
//        return success(equipmentService.list(page.getOrderWrapper()));
        // 使用关联查询
        return success(equipmentService.listRel(param));
    }

    @PreAuthorize("hasAuthority('apps:equipment:list')")
    @OperationLog
    @ApiOperation("根据id查询设备管理")
    @GetMapping("/{id}")
    public ApiResult<Equipment> get(@PathVariable("id") Integer id) {
//        return success(equipmentService.getById(id));
        // 使用关联查询
        return success(equipmentService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('apps:equipment:save')")
    @OperationLog
    @ApiOperation("添加设备管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Equipment equipment) throws AlipayApiException {
        // 记录当前登录用户id、租户id
        User loginUser = getLoginUser();
        if (loginUser != null && getMerchantCode() != null) {
          equipment.setMerchantCode(getMerchantCode());
        }
        if (equipmentService.count(new LambdaQueryWrapper<Equipment>()
          .eq(Equipment::getEquipmentCode, equipment.getEquipmentCode())) > 0) {
          return fail("设备编号已存在");
        }
        if (equipmentService.save(equipment)) {
          // 生成二维码
          String qrcode = createQrcode(equipment);
          equipment.setQrcode(qrcode);
          equipmentService.saveOrUpdate(equipment);
          return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('apps:equipment:update')")
    @OperationLog
    @ApiOperation("修改设备管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Equipment equipment) throws AlipayApiException {
        if (equipmentService.updateById(equipment)) {
          // 生成二维码
          String qrcode = createQrcode(equipment);
          equipment.setQrcode(qrcode);
          equipmentService.saveOrUpdate(equipment);
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('apps:equipment:remove')")
    @OperationLog
    @ApiOperation("删除设备管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (equipmentService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('apps:equipment:save')")
    @OperationLog
    @ApiOperation("批量添加设备管理")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Equipment> list) {
        if (equipmentService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('apps:equipment:update')")
    @OperationLog
    @ApiOperation("批量修改设备管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Equipment> batchParam) {
        if (batchParam.update(equipmentService, "equipment_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('apps:equipment:remove')")
    @OperationLog
    @ApiOperation("批量删除设备管理")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (equipmentService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    // 生成支付宝小程序码
    private String createQrcode(Equipment equipment) throws AlipayApiException{
      // 实例化客户端
      DefaultAlipayClient alipayClient = alipayConfig.alipayClient(getTenantId());

      AlipayOpenAppQrcodeCreateRequest request = new AlipayOpenAppQrcodeCreateRequest();
      AlipayOpenAppQrcodeCreateModel model = new AlipayOpenAppQrcodeCreateModel();
      model.setUrlParam("pages/checkout/checkout");
      model.setQueryParam("equipmentId=".concat(equipment.getEquipmentId().toString()).concat("&equipmentCode=").concat(equipment.getEquipmentCode()));
      model.setDescribe("扫码租赁电池");
      request.setBizModel(model);
      AlipayOpenAppQrcodeCreateResponse response = alipayClient.certificateExecute(request);
      System.out.println(response.getBody());
      if (response.isSuccess()) {
        System.out.println("调用成功");
        final JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        final String alipay_open_app_qrcode_create_response = jsonObject.getString("alipay_open_app_qrcode_create_response");
        final JSONObject jsonObject1 = JSONObject.parseObject(alipay_open_app_qrcode_create_response);
        return jsonObject1.getString("qr_code_url");
      } else {
        System.out.println("调用失败");
        return null;
      }
    }

    @ApiOperation("绑定设备")
    @PostMapping("/bind")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> bindEquipment(@RequestBody Equipment equipment) {
      // 验证签名
      isCheckSign();
      final Integer orderId = equipment.getOrderId();
      final String equipmentCode = equipment.getEquipmentCode();
      final Order order = orderService.getById(orderId);
      Equipment one = equipmentService.getByEquipmentCode(equipmentCode);
      if(one == null){
        return fail("设备不存在");
      }
      if(!one.getUserId().equals(0)){
        return fail("该设备已被绑定");
      }
      // 绑定设备
      Equipment saveData = new Equipment();
      saveData.setEquipmentId(one.getEquipmentId());
      saveData.setUserId(getLoginUserId());
      saveData.setOrderId(orderId);
      if (equipmentService.updateById(saveData)) {
        // 记录明细
        EquipmentRecord record = new EquipmentRecord();
        record.setEquipmentCode(one.getEquipmentCode());
        record.setUserId(getLoginUserId());
        record.setOrderId(orderId);
        record.setEventType(EVENT_TYPE_BIND);
        record.setComments("使用电池：");
        record.setMerchantCode(one.getMerchantCode());
        equipmentRecordService.save(record);
        // 订单发货
        order.setDeliveryStatus(DELIVERY_STATUS_YES);
        order.setOrderStatus(ORDER_STATUS_COMPLETED);
        order.setReceiptStatus(RECEIPT_STATUS_YES);
        order.setExpirationTime(DateUtil.nextMonth());
        order.setEquipmentId(one.getEquipmentId());
        orderService.updateById(order);
        return success("绑定成功");
      }
      return fail("绑定失败");
    }

    @ApiOperation("更换设备")
    @PostMapping("/change")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> changeEquipment(@RequestBody Equipment equipment) {
      // 验证签名
      isCheckSign();
      String equipmentCode = equipment.getEquipmentCode();
      Integer oid = equipment.getEquipmentId();
      Integer orderId = equipment.getOrderId();
      System.out.println("oid = " + oid);
      Integer loginUserId = getLoginUserId();
      // 新电池
      Equipment one = equipmentService.getByEquipmentCode(equipmentCode);
      // 旧电池
      Equipment old = equipmentService.getById(oid);
      // 订单信息
      Order order = orderService.getById(orderId);
      if(one == null){
        return fail("设备不存在");
      }
      if(!one.getUserId().equals(0)){
        return fail("该设备已被绑定");
      }

      // 绑定新电池
      Equipment saveData = new Equipment();
      saveData.setEquipmentId(one.getEquipmentId());
      saveData.setUserId(loginUserId);
      saveData.setOrderId(orderId);
      boolean b = equipmentService.updateById(saveData);
      // 记录新电池明细
      EquipmentRecord record = new EquipmentRecord();
      record.setEquipmentCode(equipmentCode);
      record.setEventType(EVENT_TYPE_BIND);
      record.setUserId(loginUserId);
      record.setOrderId(orderId);
      record.setMerchantCode(one.getMerchantCode());
      equipmentRecordService.save(record);

      if (b) {
        // 解绑旧电池
        old.setUserId(0);
        old.setMerchantCode(one.getMerchantCode());
        equipmentService.updateById(old);
        // 记录明细
        EquipmentRecord record2 = new EquipmentRecord();
        record2.setEquipmentCode(old.getEquipmentCode());
        record2.setUserId(loginUserId);
        record2.setOrderId(orderId);
        record2.setEventType(EVENT_TYPE_UNBIND);
        record2.setMerchantCode(one.getMerchantCode());
        equipmentRecordService.save(record2);
        // 更新订单
        order.setEquipmentId(one.getEquipmentId());
        orderService.updateById(order);
        return success("换电成功");
      }
      return fail("换电失败");
    }

    @ApiOperation("重置")
    @PostMapping("/receipt")
    public ApiResult<?> receipt(@RequestBody Order order){
      // 验证签名
      isCheckSign();
      orderService.updateById(order);
      return success("重置成功");
    }

    @ApiModelProperty("退租")
    @PostMapping("/rentingOut")
    public ApiResult<?> rentingOut(@RequestBody Order order){
      // 验证签名
      isCheckSign();
      final int count = orderRefundService.count(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getOrderId, order.getOrderId()));
      if(count > 0){
        return fail("申请成功，请等待客服人员审核");
      }
      final OrderRefund refund = new OrderRefund();
      refund.setOrderId(order.getOrderId());
      refund.setOrderGoodsId(order.getGoodsId());
      refund.setUserId(getLoginUserId());
      refund.setType(10);
      refund.setApplyDesc("申请退租");
      refund.setRefundMoney(new BigDecimal(0));
      refund.setMerchantCode(order.getMerchantCode());
      if (orderRefundService.save(refund)) {
        return success("申请成功，请等待客服人员审核");
      }
      return fail("退租失败");
    }

//    @ApiModelProperty("退租")
//    @PostMapping("/rentingOut")
//    public ApiResult<?> rentingOut(@RequestBody Order order){
//      // 验证签名
//      isCheckSign();
//      order.setReceiptStatus(RECEIPT_STATUS_RETURN);
//      if(orderService.updateById(order)){
//        final Equipment equipment = equipmentService.getById(order.getEquipmentId());
//        equipment.setUserId(0);
//        equipmentService.updateById(equipment);
//        return success("操作成功，请等待客服人员审核");
//      }
//      return fail("退租失败");
//    }
}
