package com.gxwebsoft.apps.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.exception.BusinessException;
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.Merchant;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.service.MerchantService;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

import static com.gxwebsoft.apps.constants.EquipmentConstants.EVENT_TYPE_BIND;
import static com.gxwebsoft.common.core.constants.OrderConstants.*;

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

    @PreAuthorize("hasAuthority('apps:equipment:list')")
    @OperationLog
    @ApiOperation("分页查询设备管理")
    @GetMapping("/page")
    public ApiResult<PageResult<Equipment>> page(EquipmentParam param) {
        // 使用关联查询
        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 (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:update')")
    @OperationLog
    @ApiOperation("绑定设备")
    @PutMapping("/bind")
    public ApiResult<?> bindEquipment(@RequestBody Equipment equipment) {
      final Integer orderId = equipment.getOrderId();
      final Order order = orderService.getById(orderId);
      Equipment one = equipmentService.getOne(new LambdaQueryWrapper<Equipment>().eq(Equipment::getEquipmentCode, equipment.getEquipmentCode()));
      if(one == null){
        return fail("设备不存在");
      }
      if(!one.getUserId().equals(0)){
        return fail("该设备已被绑定");
      }
      Equipment saveData = new Equipment();
      saveData.setEquipmentId(one.getEquipmentId());
      saveData.setUserId(equipment.getUserId());
      saveData.setOrderId(orderId);
      if (equipmentService.updateById(saveData)) {
        // 记录明细
        EquipmentRecord record = new EquipmentRecord();
        record.setEquipmentCode(one.getEquipmentCode());
        record.setUserId(getLoginUserId());
        record.setEventType(EVENT_TYPE_BIND);
        record.setComments("订单号：".concat(Long.toString(order.getOrderNo())));
        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("绑定失败");
    }

    @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/equipment/equipment");
      System.out.println("equipment = " + equipment);
      // __id__=2&merchantCode=M311539&merchantId=52
      // pages/equipment/equipment

//      Merchant merchant = merchantService.getMerchantByCode(equipment.getMerchantCode());
//      if(merchant == null){
//        throw new BusinessException("该商户不存在");
//      }
      model.setQueryParam("equipmentId=".concat(equipment.getEquipmentId().toString()));
      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;
      }
    }

    @PreAuthorize("hasAuthority('apps:equipment:update')")
    @ApiOperation("确认收货")
    @PostMapping("/receipt")
    public ApiResult<?> receipt(@RequestBody Order order){
      orderService.updateById(order);
      return success("确认收货");
    }
}
