package com.cyl.h5.controller;

import com.alibaba.fastjson.JSONObject;
import com.cyl.h5.pojo.vo.form.BondSubmitForm;
import com.cyl.h5.service.H5OrderService;
import com.cyl.manager.staff.domain.BondTransaction;
import com.cyl.manager.staff.domain.Staff;
import com.cyl.manager.staff.service.IBondTransactionService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.LocalDataUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/no-auth/bond")
@Slf4j
public class H5BondController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private H5OrderService orderService;

    @Autowired
    private IBondTransactionService bondTransactionService;

//    @ApiOperation("发起保证金缴纳支付")
    @PostMapping("/orderPay")
    public AjaxResult orderPay(@RequestBody @Valid BondSubmitForm form) {
        log.info("保证金缴纳,提交的数据：{}", JSONObject.toJSONString(form));
        Staff staff = (Staff) LocalDataUtil.getVar(Constants.STAFF_INFO);
        Long staffId = staff.getId();

        //防止用户重复提交
        String redisKey = "h5_oms_bond_order_pay_" + staffId;
        String redisValue = staffId + "_" + System.currentTimeMillis();
        try {
            redisService.lock(redisKey, redisValue, 60);
            BigDecimal amount = new BigDecimal(200);
            if (StringUtils.isNotEmpty(form.getTotalPrice())) {
                amount = BigDecimal.valueOf(Integer.valueOf(form.getTotalPrice()));
            }
            return AjaxResult.success(orderService.bondPay(staff, form.getOpenId(), amount));
        } catch (Exception e) {
            log.error("保证金缴纳支付方法异常", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                redisService.unLock(redisKey, redisValue);
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }


    /**
     * 获取员工保证金明细列表
     */
//    @ApiOperation("获取员工保证金明细")
    @GetMapping("/getBondPageList")
    public ResponseEntity<Page<BondTransaction>> getBondPageList(Pageable page) {
        Staff staff = (Staff) LocalDataUtil.getVar(Constants.STAFF_INFO);
        Long staffId = staff.getId();
        List<BondTransaction> list = bondTransactionService.getStaffBondList(staffId, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page) list).getTotal()));
    }
}
