package com.ym.mec.student.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

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

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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.MusicGroupSubjectGoodsAndInfoDto;
import com.ym.mec.biz.dal.dto.RegisterPayDto;
import com.ym.mec.biz.dal.entity.Goods;
import com.ym.mec.biz.dal.entity.MusicGroup;
import com.ym.mec.biz.dal.entity.MusicGroupStudentFee;
import com.ym.mec.biz.dal.entity.MusicGroupStudentFee.PaymentStatus;
import com.ym.mec.biz.dal.entity.MusicGroupSubjectGoodsGroup;
import com.ym.mec.biz.dal.entity.MusicGroupSubjectPlan;
import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
import com.ym.mec.biz.dal.entity.StudentRegistration;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.dal.enums.GoodsType;
import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
import com.ym.mec.biz.dal.enums.MusicGroupStatusEnum;
import com.ym.mec.biz.dal.enums.YesOrNoEnum;
import com.ym.mec.biz.service.GoodsService;
import com.ym.mec.biz.service.MusicGroupService;
import com.ym.mec.biz.service.MusicGroupSubjectGoodsGroupService;
import com.ym.mec.biz.service.MusicGroupSubjectPlanService;
import com.ym.mec.biz.service.PayService;
import com.ym.mec.biz.service.StudentPaymentOrderService;
import com.ym.mec.biz.service.StudentRegistrationService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.util.string.IdWorker;

@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 MusicGroupSubjectGoodsGroupService musicGroupSubjectGoodsGroupService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private PayService payService;
    
    @Autowired
    private MusicGroupStudentFeeDao musicGroupStudentFeeDao;

    @ApiOperation("获取学生所在乐团列表")
    @GetMapping(value = "/queryUserMusicGroups")
    public Object queryUserMusicGroups() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        return succeed(musicGroupService.queryUserMusicGroups(sysUser.getId()));
    }

    @ApiOperation("获取学生个人中心乐团信息")
    @GetMapping(value = "/queryPersonalMusicGroups")
    public Object queryPersonalMusicGroups() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        return succeed(musicGroupService.queryPersonalMusicGroups(sysUser.getId()));
    }

    @ApiOperation(value = "根据学员编号，获取有关联的老师列表")
    @GetMapping("/findTeachersByStuId")
    public Object findTeachersByStuId() {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("获取用户信息失败");
        }
        return succeed(musicGroupService.findTeachersByStuId(sysUser.getId()));
    }


    @ApiOperation(value = "获取乐团声部费用信息及乐器和辅件")
    @GetMapping("/getSubjectGoodsAndInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团编号", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "subjectId", value = "声部编号", required = true, dataType = "Integer")})
    public HttpResponseResult getSubjectGoodsAndInfo(String musicGroupId, Integer subjectId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        MusicGroupSubjectGoodsAndInfoDto subjectGoodsAndInfo = musicGroupSubjectPlanService.getSubjectGoodsAndInfo(musicGroupId, subjectId);
        return succeed(subjectGoodsAndInfo);
    }

    @ApiOperation(value = "乐团报名缴费状态查询")
    @GetMapping("/getMusicGroupStatus")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String")})
    public HttpResponseResult getMusicGroupStatus(String musicGroupId) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        Integer userId = sysUser.getId();
        MusicGroup musicGroup = musicGroupService.get(musicGroupId);
        if (musicGroup == null) {
            return failed("乐团不存在");
        }
        StudentRegistration studentRegistration = studentRegistrationService.queryByUserIdAndMusicGroupId(userId, musicGroupId);
        if (studentRegistration == null) {
            return failed("乐团报名信息不存在");
        }
        if (!musicGroup.getStatus().equals(MusicGroupStatusEnum.PAY) && !studentRegistration.getPaymentStatus().equals(YesOrNoEnum.YES)) {
            return failed("乐团还未开启缴费，请等待通知");
        }
        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();
		}
		ModelMap model = new ModelMap();
		model.put("musicGroup", musicGroup);
		model.put("amount", amount);

		return succeed(model);
	}

    @ApiOperation(value = "续费")
    @GetMapping("/renew")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团id", required = true, dataType = "String")})
	public HttpResponseResult renew(String musicGroupId) throws Exception {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		Integer userId = sysUser.getId();
		return succeed(musicGroupService.renew(musicGroupId, userId));
	}

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


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

        SysUser sysUser = sysUserFeignService.queryUserInfo();
        Integer userId = sysUser.getId();
        StudentRegistration studentRegistration = studentRegistrationService.get(registerPayDto.getRegisterId().longValue());
        if (!studentRegistration.getUserId().equals(userId)) {
            return failed("报名信息有误，请核查");
        }

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

        //判断用户是否已存在订单
        ApplyOrder = studentPaymentOrderService.findMusicGroupApplyOrderByStatus(userId, studentRegistration.getMusicGroupId(), DealStatusEnum.ING);
        if (ApplyOrder != null) {
            return failed(HttpStatus.CONTINUE, "您有待支付的订单");
        }

        BigDecimal amount = registerPayDto.getAmount(); //前端获取的价格
        BigDecimal orderAmount = new BigDecimal("0");

        //获取课程价格
        MusicGroupSubjectPlan musicOneSubjectClassPlan = musicGroupSubjectPlanService.getMusicOneSubjectClassPlan(studentRegistration.getMusicGroupId(), studentRegistration.getSubjectId());
        BigDecimal courseFee = musicOneSubjectClassPlan.getFee();
        orderAmount = orderAmount.add(courseFee);


        //乐器及打包辅件
        List<MusicGroupSubjectGoodsGroup> goodsGroups = null;
        if (registerPayDto.getGoodsGroupIds() != null && !registerPayDto.getGoodsGroupIds().equals("")) {
            goodsGroups = musicGroupSubjectGoodsGroupService.findGoodsGroupByIds(registerPayDto.getGoodsGroupIds());
            for (MusicGroupSubjectGoodsGroup goodsGroup : goodsGroups) {
                orderAmount = orderAmount.add(goodsGroup.getPrice());
                //团购乐器减免课程费用
                if (goodsGroup.getType().equals(GoodsType.INSTRUMENT) && goodsGroup.getRemissionCourseFee() != null && musicOneSubjectClassPlan.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.GROUP)) {//团购
                    orderAmount = orderAmount.subtract(goodsGroup.getRemissionCourseFee());
                }
            }
        }

        //单独辅件
        List<Goods> goodsList = null;
        if (registerPayDto.getGoodsIds() != null && !registerPayDto.getGoodsIds().equals("")) {
            goodsList = goodsService.findGoodsByIds(registerPayDto.getGoodsIds());
            for (Goods goods : goodsList) {
                orderAmount = orderAmount.add(goods.getGroupPurchasePrice());
            }
        }

        //单独教谱
        List<Goods> otherGoodsList = null;
        if (registerPayDto.getOtherGoodsIds() != null && !registerPayDto.getOtherGoodsIds().equals("")) {
            otherGoodsList = goodsService.findGoodsByIds(registerPayDto.getOtherGoodsIds());
            for (Goods goods : otherGoodsList) {
                orderAmount = orderAmount.add(goods.getGroupPurchasePrice());
            }
        }
        if (amount.compareTo(orderAmount) != 0) {
            return failed("商品价格不符");
        }


        IdWorker idWorker = new IdWorker(0, 0);
        String orderNo = idWorker.nextId();

        Map payMap = payService.getPayMap(orderAmount, orderNo, "https://pay.dayaedu.com/api/yqpay/notify", "http://dev.dayaedu.com", "测试订单", "测试订单");

        studentRegistrationService.addOrder(userId, amount, orderNo, (String) payMap.get("type"), courseFee, goodsGroups, goodsList, otherGoodsList, studentRegistration.getMusicGroupId());

        return succeed(payMap);
    }

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

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

        //判断用户是否已存在订单
        ApplyOrder = studentPaymentOrderService.findMusicGroupApplyOrderByStatus(userId, studentRegistration.getMusicGroupId().toString(), DealStatusEnum.ING);
        if (ApplyOrder == null) {
            return failed(HttpStatus.CONTINUE, "没有支付中的订单，请勿非法请求");
        }

        BigDecimal amount = registerPayDto.getAmount(); //前端获取的价格
        BigDecimal orderAmount = new BigDecimal("0");

        //获取课程价格
        MusicGroupSubjectPlan musicOneSubjectClassPlan = musicGroupSubjectPlanService.getMusicOneSubjectClassPlan(studentRegistration.getMusicGroupId(), studentRegistration.getSubjectId());
        BigDecimal courseFee = musicOneSubjectClassPlan.getFee();
        orderAmount = orderAmount.add(courseFee);


        //乐器及打包辅件
        List<MusicGroupSubjectGoodsGroup> goodsGroups = null;
        if (registerPayDto.getGoodsGroupIds() != null && !registerPayDto.getGoodsGroupIds().equals("")) {
            goodsGroups = musicGroupSubjectGoodsGroupService.findGoodsGroupByIds(registerPayDto.getGoodsGroupIds());
            for (MusicGroupSubjectGoodsGroup goodsGroup : goodsGroups) {
                orderAmount = orderAmount.add(goodsGroup.getPrice());
                //团购乐器减免课程费用
                if (goodsGroup.getType().equals(GoodsType.INSTRUMENT) && goodsGroup.getRemissionCourseFee() != null && musicOneSubjectClassPlan.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.GROUP)) {//团购
                    orderAmount = orderAmount.subtract(goodsGroup.getRemissionCourseFee());
                }
            }
        }

        //单独辅件
        List<Goods> goodsList = null;
        if (registerPayDto.getGoodsIds() != null && !registerPayDto.getGoodsIds().equals("")) {
            goodsList = goodsService.findGoodsByIds(registerPayDto.getGoodsIds());
            for (Goods goods : goodsList) {
                orderAmount = orderAmount.add(goods.getGroupPurchasePrice());
            }
        }

        //单独教谱
        List<Goods> otherGoodsList = null;
        if (registerPayDto.getOtherGoodsIds() != null && !registerPayDto.getOtherGoodsIds().equals("")) {
            otherGoodsList = goodsService.findGoodsByIds(registerPayDto.getOtherGoodsIds());
            for (Goods goods : otherGoodsList) {
                orderAmount = orderAmount.add(goods.getGroupPurchasePrice());
            }
        }
        if (amount.compareTo(orderAmount) != 0) {
            return failed("商品价格不符");
        }


        IdWorker idWorker = new IdWorker(0, 0);
        String orderNo = idWorker.nextId();

        Map payMap = payService.getPayMap(orderAmount, orderNo, "https://pay.dayaedu.com/api/yqpay/notify", "http://dev.dayaedu.com", "测试订单", "测试订单");

        studentRegistrationService.reAddOrder(userId, amount, orderNo, "双乾", courseFee, goodsGroups, goodsList, otherGoodsList, studentRegistration.getMusicGroupId(),ApplyOrder);

        return succeed(payMap);
    }

    @GetMapping("/test")
    public Object test() throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserByMobile("15829292961");


//        Map query = payService.query("1017201910111756231647562047");
//
//        System.out.println(query);
//
        IdWorker idWorker = new IdWorker(0, 0);
        String orderNo = "1017" + idWorker.nextId();
        BigDecimal amount = new BigDecimal("0.01");
        Map map = payService.getPayMap(amount, orderNo, "http://47.99.212.176:8000/studentOrder/notify", "https://baodiu.com", "测试订单", "测试订单");
       return succeed(map);
    }

    @ApiOperation(value = "订单状态查询")
    @GetMapping("/getOrderStatus")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderNo", value = "订单号", required = true, dataType = "String")})
    public HttpResponseResult getOrderStatus(String orderNo) {
        StudentPaymentOrder order = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        return succeed(order);
    }
}
