package com.ym.mec.student.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
import com.ym.mec.biz.dal.dto.SporadicPayDto;
import com.ym.mec.biz.dal.entity.SporadicChargeInfo;
import com.ym.mec.biz.dal.entity.SysUserCashAccount;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.service.MusicGroupService;
import com.ym.mec.biz.service.SporadicChargeInfoService;
import com.ym.mec.biz.service.StudentPaymentOrderService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("sporadicChargeInfo")
@Api(tags = "零星收费")
@RestController
public class SporadicChargeInfoController extends BaseController {

    @Autowired
    private SporadicChargeInfoService sporadicChargeInfoService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private MusicGroupService musicGroupService;

    @ApiOperation(value = "单查询")
    @GetMapping("/get")
    public Object get(Integer id, Integer userId) {
        return succeed(sporadicChargeInfoService.findDetail(id, userId));
    }


    @ApiOperation(value = "零星支付")
    @PostMapping("/sporadicPay")
    public HttpResponseResult sporadicPay(@RequestBody SporadicPayDto sporadicPayDto) throws Exception {
        if (sporadicPayDto == null ||
                sporadicPayDto.getSporadicId() == null ||
                sporadicPayDto.getAmount() == null) {
            throw new BizException("参数校验失败");
        }
        if (sporadicPayDto.getUserId() == null) {
            SysUser sysUser = sysUserFeignService.queryUserInfo();
            if (sysUser == null || sysUser.getId() == null) {
                return failed("用户不存在");
            }
//            if (!sysUser.getUserType().contains("STUDENT")) {
//                return failed("用户信息异常");
//            }
            sporadicPayDto.setUserId(sysUser.getId());
        }
        if (sporadicPayDto.getIsRepeatPay() == false) {
            Integer ingOrder = studentPaymentOrderService.findOrderByGroupType(sporadicPayDto.getUserId(), sporadicPayDto.getSporadicId(), "SPORADIC", DealStatusEnum.ING);
            if (ingOrder != null && ingOrder > 0) {
                return failed(HttpStatus.CONTINUE, "您有待支付的订单");
            }
        }
        SporadicChargeInfo info = sporadicChargeInfoService.get(sporadicPayDto.getSporadicId());

        if (info.getMaxAmount() != null) {
            String msg = "";
            for (int i = 1; i <= 100; i++) {
                try {
                    Map payMap = musicGroupService.sporadicPay(sporadicPayDto);
                    if (payMap.containsKey("tradeState")) {
                        return failed(HttpStatus.CREATED, "恭喜您,支付成功!");
                    }
                    return succeed(payMap);
                } catch (Exception e) {
                    msg = e.getMessage();
                    if (e instanceof BizException) {
                        int max = 100, min = 1;
                        int times = (int) (Math.random() * (max - min) + min);
                        Thread.sleep(times);
                        continue;
                    }
                    break;
                }
            }
            return failed(msg);
        }

        Map payMap = musicGroupService.sporadicPay(sporadicPayDto);
        if (payMap.containsKey("tradeState")) {
            return failed(HttpStatus.CREATED, "恭喜您,支付成功!");
        }
        return succeed(payMap);
    }


    @ApiOperation(value = "福袋活动信息")
    @GetMapping("/activityInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "type", value = "类型（福袋活动6）", required = true, dataType = "String")})
    public HttpResponseResult activityInfo(Integer type) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null || sysUser.getId() == null) {
            return failed("请先登录");
        }
        if (sysUser.getOrganId() == null) {
            return failed("用户信息有误，没有分部信息");
        }
        Integer organId = sysUser.getOrganId();

        if (type == null || type <= 0) {
            return failed("参数不合法");
        }
        SporadicChargeInfo chargeInfo = sporadicChargeInfoService.findByOrganIdAndType(organId, type);
        if (chargeInfo == null) {
            return failed("分部活动不存在");
        }
        return succeed(chargeInfo);
    }
}
