package com.ym.mec.student.controller;

import com.ym.mec.biz.dal.dao.SubjectChangeDao;
import com.ym.mec.biz.dal.dto.SubjectChangeParamDto;
import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
import com.ym.mec.biz.dal.entity.SubjectChange;
import com.ym.mec.biz.dal.enums.PayStatus;
import com.ym.mec.biz.dal.enums.SubjectChangeStatusEnum;
import com.ym.mec.biz.service.StudentPaymentOrderService;
import com.ym.mec.biz.service.SubjectChangeService;
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.util.Map;

@RequestMapping("subjectChange")
@Api(tags = "声部更换服务")
@RestController
public class SubjectChangeController extends BaseController {

    @Autowired
    private SubjectChangeService subjectChangeService;
    @Autowired
    private SubjectChangeDao subjectChangeDao;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;


    @ApiOperation(value = "获取更换详情")
    @GetMapping("/getChangeInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer")})
    public HttpResponseResult<SubjectChange> getChangeInfo(Integer id) {
        if (id == null) {
            return failed("参数校验异常");
        }
        return succeed(subjectChangeService.getChangeInfo(id));
    }

    @ApiOperation(value = "支付更换声部费用")
    @PostMapping("/payChange")
    public HttpResponseResult<Map> payChange(@RequestBody SubjectChangeParamDto subjectChangeParamDto) throws Exception {
        SubjectChange subjectChange = subjectChangeDao.get(subjectChangeParamDto.getId());
        if (!subjectChangeParamDto.getRepay() && subjectChange.getStatus().equals(SubjectChangeStatusEnum.ING)) {
        	
            StudentPaymentOrder applyOrder = studentPaymentOrderService.get(subjectChange.getOrderId().longValue());
        	// 查询订单状态
            PayStatus payStatus = studentPaymentOrderService.queryPayStatus(applyOrder);
            if(payStatus == PayStatus.SUCCESSED){
        		throw new BizException("订单已支付成功，请勿重复支付");
        	}
            return failed(HttpStatus.CONTINUE, "您有待支付的订单");
        }
        subjectChangeParamDto.setTenantId(subjectChange.getTenantId());
        Map payMap = subjectChangeService.payChange(subjectChangeParamDto);
        if (payMap.containsKey("tradeState")) {
            return failed(HttpStatus.CREATED, payMap, "恭喜您,支付成功!");
        }
        return succeed(payMap);
    }


}
