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.MusicGroupStudentFeeDao;
import com.ym.mec.biz.dal.dto.RegisterPayDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus;
import com.ym.mec.biz.dal.enums.*;
import com.ym.mec.biz.service.*;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

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

@RequestMapping("musicGroup")
@Api(tags = "乐团服务")
@RestController
public class MusicGroupController extends BaseController {

    @Resource
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private MusicGroupService musicGroupService;
    @Autowired
    private MusicGroupSubjectPlanService musicGroupSubjectPlanService;
    @Autowired
    private StudentRegistrationService studentRegistrationService;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private MusicGroupStudentFeeDao musicGroupStudentFeeDao;
    @Autowired
    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;

    @ApiOperation("获取学生所在乐团列表")
    @GetMapping(value = "/queryUserMusicGroups")
    public Object queryUserMusicGroups() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(musicGroupService.queryUserMusicGroups(sysUser.getId()));
    }

    @ApiOperation("获取学生个人中心乐团信息")
    @GetMapping(value = "/queryPersonalMusicGroups")
    public Object queryPersonalMusicGroups() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(musicGroupService.queryPersonalMusicGroups(sysUser.getId()));
    }

    @ApiOperation(value = "根据学员编号，获取有关联的老师列表")
    @GetMapping("/findTeachersByStuId")
    public Object findTeachersByStuId(String search) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(musicGroupService.findTeachersByStuId(sysUser.getId(),search));
    }


    @ApiOperation(value = "获取乐团声部费用信息及乐器和辅件")
    @GetMapping("/getSubjectGoodsAndInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "subjectId", value = "声部编号", required = true, dataType = "Integer")})
    public HttpResponseResult getSubjectGoodsAndInfo(String musicGroupId, Integer subjectId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser != null && sysUser.getId() > 0) {
            Integer userId = sysUser.getId();
            StudentRegistration studentRegistration = studentRegistrationService.queryByUserIdAndMusicGroupId(userId, musicGroupId);
            if (studentRegistration != null && studentRegistration.getTemporaryCourseFee() != null) {
                return succeed(musicGroupSubjectPlanService.getStudentGoodsAndInfo(musicGroupId, subjectId, studentRegistration));
            }
        }

        return succeed(musicGroupSubjectPlanService.getSubjectGoodsAndInfo(musicGroupId, subjectId));
    }

    @ApiOperation(value = "乐团报名缴费状态查询")
    @GetMapping("/getMusicGroupStatus")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int")
    })
    public HttpResponseResult getMusicGroupStatus(String musicGroupId, Integer userId) throws Exception {
        MusicGroup musicGroup = musicGroupService.get(musicGroupId);
        if (musicGroup == null) {
            return failed("乐团不存在");
        }

        if (userId == null) {
            SysUser sysUser = sysUserFeignService.queryUserInfo();
            userId = sysUser.getId();
        }

        StudentRegistration studentRegistration = studentRegistrationService.queryByUserIdAndMusicGroupId(userId, musicGroupId);
        if (studentRegistration == null) {
            return failed(HttpStatus.CONTINUE, "乐团报名信息不存在");
        }
        if (studentRegistration.getPaymentStatus() != null && studentRegistration.getPaymentStatus().equals(PaymentStatusEnum.YES)) {
            return failed("您已缴费,请等待乐团开启");
        }

        if (!studentRegistration.getPaymentStatus().equals(PaymentStatusEnum.OPEN)) {
            return failed("乐团还未开启缴费，请等待通知");
        }
        if(studentRegistration.getTemporaryCourseFee() == null &&
                (!musicGroup.getStatus().equals(MusicGroupStatusEnum.APPLY) && !musicGroup.getStatus().equals(MusicGroupStatusEnum.PAY))){
            return failed("乐团在"+musicGroup.getStatus().getMsg()+",不能缴费");
        }
        studentRegistration.setOwnershipType(musicGroup.getOwnershipType());

        return succeed(studentRegistration);
    }

    @ApiOperation(value = "查询续费信息")
    @GetMapping("/queryRenewInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String")})
    public HttpResponseResult queryRenewInfo(String musicGroupId) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        Integer userId = sysUser.getId();
        MusicGroup musicGroup = musicGroupService.get(musicGroupId);
        if (musicGroup == null) {
            return failed("乐团不存在");
        }
        MusicGroupStudentFee musicGroupStudentFee = musicGroupStudentFeeDao.findByUser(userId, musicGroupId);

        if (musicGroupStudentFee == null) {
            throw new BizException("个人信息不存在");
        }
        if (musicGroupStudentFee.getPaymentStatus() != PaymentStatus.NON_PAYMENT) {
            throw new BizException("已缴费");
        }

        BigDecimal amount = musicGroupStudentFee.getTemporaryCourseFee();
        if (amount == null || amount.doubleValue() == 0) {
            amount = musicGroupStudentFee.getCourseFee();
        }

        StudentRegistration studentRegistration = studentRegistrationService.queryByUserIdAndMusicGroupId(userId, musicGroupId);
        if (studentRegistration == null) {
            return failed("乐团报名信息找不到");
        }
        MusicGroupSubjectPlan musicGroupSubjectPlan = musicGroupSubjectPlanService.getMusicOneSubjectClassPlan(musicGroupId,
                studentRegistration.getActualSubjectId());
        ModelMap model = new ModelMap();
        model.put("musicGroup", musicGroup);
        model.put("amount", amount);
        model.put("nextPaymentDate", musicGroupStudentFee.getNextPaymentDate());
        model.put("musicGroupSubjectPlan", musicGroupSubjectPlan);
        model.put("balance",studentRegistration.getBalance());

        return succeed(model);
    }

	@ApiOperation(value = "续费")
	@GetMapping("/renew")
	@ApiImplicitParams({ @ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String"),
			@ApiImplicitParam(name = "isUseBalancePayment", value = "是否使用余额付款", required = true, dataType = "Boolean") })
	public HttpResponseResult renew(String musicGroupId, Boolean isUseBalancePayment, boolean isRepeatPay) throws Exception {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		Integer userId = sysUser.getId();

		if (isUseBalancePayment == null) {
			isUseBalancePayment = false;
		}
		if (isRepeatPay == false) {
            // 判断是否存在支付中的记录
            List<StudentPaymentOrder> list = studentPaymentOrderService.queryByCondition(GroupType.MUSIC, musicGroupId, userId, DealStatusEnum.ING,
                    OrderTypeEnum.RENEW);
			if (list.size() > 0) {
				return failed(HttpStatus.CONTINUE, "您有待支付的订单");
			}
		}
		return succeed(musicGroupService.renew(musicGroupId, userId, isUseBalancePayment));
	}

    @ApiOperation(value = "退团")
    @PostMapping("/quitMusicGroup")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String")})
    public HttpResponseResult quitMusicGroup(String musicGroupId) throws Exception {
        return succeed(musicGroupService.applyQuitMusicGroup(musicGroupId));
    }

    @ApiOperation(value = "乐团报名支付")
    @PostMapping("/pay")
    @ApiImplicitParams({@ApiImplicitParam(name = "registerPayDto", value = "支付信息", required = true, dataType = "Integer")})
    public HttpResponseResult pay(@RequestBody RegisterPayDto registerPayDto) throws Exception {

        StudentRegistration studentRegistration = studentRegistrationService.get(registerPayDto.getRegisterId().longValue());
        if (studentRegistration == null) {
            return failed("报名信息有误，请核查");
        }

        Integer userId = studentRegistration.getUserId();

        StudentPaymentOrder ApplyOrder = studentPaymentOrderService.findMusicGroupApplyOrderByStatus(userId, studentRegistration.getMusicGroupId(), DealStatusEnum.SUCCESS);
        StudentPaymentOrder waitPay = studentPaymentOrderService.findMusicGroupApplyOrderByStatus(userId, studentRegistration.getMusicGroupId(), DealStatusEnum.WAIT_PAY);
        if (ApplyOrder != null && waitPay == null) {
            return failed("您已支付成功，请勿重复支付");
        }

        //判断用户是否已存在订单
        ApplyOrder = studentPaymentOrderService.findMusicGroupApplyOrderByStatus(userId, studentRegistration.getMusicGroupId(), DealStatusEnum.ING);
        if (ApplyOrder != null) {
            return failed(HttpStatus.CONTINUE, "您有待支付的订单");
        }
        Map payMap = musicGroupService.pay(registerPayDto);
        if(payMap.containsKey("tradeState")){
            return failed(HttpStatus.CREATED, "恭喜您,报名成功!");
        }

        return succeed(payMap);
    }

    @ApiOperation(value = "乐团报名重新支付")
    @PostMapping("/rePay")
    @ApiImplicitParams({@ApiImplicitParam(name = "registerPayDto", value = "支付信息", required = true, dataType = "Integer")})
    public HttpResponseResult rePay(@RequestBody RegisterPayDto registerPayDto) throws Exception {
        StudentRegistration studentRegistration = studentRegistrationService.get(registerPayDto.getRegisterId().longValue());
        if (studentRegistration == null) {
            return failed("报名信息有误，请核查");
        }

        Integer userId = studentRegistration.getUserId();

        StudentPaymentOrder ApplyOrder = studentPaymentOrderService.findMusicGroupApplyOrderByStatus(userId, studentRegistration.getMusicGroupId(), DealStatusEnum.SUCCESS);
        StudentPaymentOrder waitPay = studentPaymentOrderService.findMusicGroupApplyOrderByStatus(userId, studentRegistration.getMusicGroupId(), DealStatusEnum.WAIT_PAY);
        if (ApplyOrder != null && waitPay == null) {
            return failed("您已支付成功，请勿重复支付");
        }
        Map payMap = musicGroupService.rePay(registerPayDto);
        if(payMap.containsKey("tradeState")){
            return failed(HttpStatus.CREATED, "恭喜您,报名成功!");
        }

        return succeed(payMap);
    }

    @ApiOperation(value = "订单状态查询")
    @GetMapping("/getOrderStatus")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderNo", value = "订单号", required = true, dataType = "String")})
    public HttpResponseResult getOrderStatus(String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            return failed("请指定订单");
        }
        StudentPaymentOrder orderByOrderNo = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        if (Objects.isNull(orderByOrderNo)) {
            return failed("未找到指定订单");
        }
        MusicGroup musicGroup = musicGroupService.get(orderByOrderNo.getMusicGroupId());
        List<Goods> goodsList = studentPaymentOrderDetailService.findApplyOrderGoods(orderByOrderNo.getId());
        HashMap<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("order", orderByOrderNo);
        orderDetail.put("goods", goodsList);
        orderDetail.put("course", musicGroup.getCourseForm());

        return succeed(orderDetail);
    }
}
