package com.ym.mec.biz.service.impl;

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

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.MusicGroupGoodsAndDiscountDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ym.mec.biz.dal.dto.MusicGroupRegRespDto;
import com.ym.mec.biz.dal.dto.MusicGroupSubjectGoodsAndInfoDto;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.dal.enums.GoodsType;
import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
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.StudentRegistrationService;
import com.ym.mec.biz.service.SubjectService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;

@Service
public class MusicGroupSubjectPlanServiceImpl extends BaseServiceImpl<Integer, MusicGroupSubjectPlan> implements MusicGroupSubjectPlanService {

    @Autowired
    private MusicGroupSubjectPlanDao musicGroupSubjectPlanDao;

    @Autowired
    private StudentRegistrationService studentRegistrationService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private MusicGroupSubjectGoodsGroupService musicGroupSubjectGoodsGroupService;

    @Autowired
    private MusicGroupService musicGroupService;

    @Autowired
    private SubjectService subjectService;
    @Autowired
    private StudentPaymentOrderDetailDao studentPaymentOrderDetailDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private ChargeTypeSubjectMapperDao chargeTypeSubjectMapperDao;
    @Autowired
    private MusicGroupPaymentCalenderCourseSettingsDao musicGroupPaymentCalenderCourseSettingsDao;
    @Autowired
    private MusicGroupPaymentCalenderDao musicGroupPaymentCalenderDao;

    @Override
    public BaseDAO<Integer, MusicGroupSubjectPlan> getDAO() {
        return musicGroupSubjectPlanDao;
    }

    @Override
    public List<MusicGroupSubjectPlan> getMusicSubjectClassPlan(String musicGroupId) {
        List<MusicGroupSubjectPlan> musicSubjectClassPlans = musicGroupSubjectPlanDao.getMusicSubjectClassPlan(musicGroupId);
        List<MusicGroupSubjectPlan> noClassStuCounts = studentRegistrationService.getNoClassStuCountByMusicGroupId(musicGroupId);

        for (MusicGroupSubjectPlan musicSubjectClassPlan : musicSubjectClassPlans) {
            for (MusicGroupSubjectPlan noClassStuCount : noClassStuCounts) {
                if (!noClassStuCount.getSubjectId().equals(musicSubjectClassPlan.getSubjectId())) continue;
                musicSubjectClassPlan.setNoClassStudentNum(noClassStuCount.getNoClassStudentNum());
            }
            if (musicSubjectClassPlan.getNoClassStudentNum() == null) {
                musicSubjectClassPlan.setNoClassStudentNum(0);
            }
        }
        return musicSubjectClassPlans;
    }

    @Override
    public MusicGroupSubjectPlan getMusicOneSubjectClassPlan(String musicGroupId, int subjectId) {
        return musicGroupSubjectPlanDao.getMusicOneSubjectClassPlan(musicGroupId, subjectId);
    }

    @Override
    public MusicGroupSubjectGoodsAndInfoDto getSubjectGoodsAndInfo(String musicGroupId, Integer subjectId) {
        MusicGroup musicGroup = musicGroupService.get(musicGroupId);

        //课程形态
        Map<String, Object> courseForm = JSON.parseObject(musicGroup.getCourseForm(), Map.class);

        //新的课程形态10.27
        MusicGroupPaymentCalender musicGroupRegCalender = musicGroupPaymentCalenderDao.getMusicGroupRegCalender(musicGroupId);
        if (musicGroupRegCalender != null) {
            List<MusicGroupPaymentCalenderCourseSettings> courseSettings = musicGroupPaymentCalenderCourseSettingsDao.getMusicGroupRegCalenderCourseSettings(musicGroupId);
            musicGroupRegCalender.setMusicGroupPaymentCalenderCourseSettingsList(courseSettings);
        }

        //乐团计划及收费信息
        MusicGroupSubjectPlan musicOneSubjectClassPlan = this.getMusicOneSubjectClassPlan(musicGroupId, subjectId);

        //乐团乐器及辅件信息
        List<MusicGroupSubjectGoodsGroup> goodsGroups = musicGroupSubjectGoodsGroupService.findGoodsGroup(musicGroupId, subjectId);

        List<Goods> accessoriesList = goodsService.findGoodsBySubId(subjectId, GoodsType.ACCESSORIES.getCode());

        goodsGroups.forEach(goodsGroup -> {
            if (goodsGroup.getType().equals(GoodsType.INSTRUMENT)) {
                goodsGroup.getGoodsList().forEach(goods -> {
                    goods.setGoodsList(accessoriesList);
                });
            }
        });
        //获取声部（科目）下其他商品
        List<Goods> otherGoods = goodsService.findTypeGoods("OTHER");

        MusicGroupSubjectGoodsAndInfoDto musicGroupSubjectGoodsAndInfo = new MusicGroupSubjectGoodsAndInfoDto();
        musicGroupSubjectGoodsAndInfo.setMusicGroupSubjectPlan(musicOneSubjectClassPlan);
        musicGroupSubjectGoodsAndInfo.setCourseScheduleInfo(courseForm);
        musicGroupSubjectGoodsAndInfo.setMusicGroupPaymentCalender(musicGroupRegCalender);
        musicGroupSubjectGoodsAndInfo.setMusicGroupSubjectGoodsGroupList(goodsGroups);
        musicGroupSubjectGoodsAndInfo.setOtherGoods(otherGoods);
        return musicGroupSubjectGoodsAndInfo;
    }

    @Override
    public MusicGroupRegRespDto getMusicGroupRegInfo(String musicGroupId) {
        MusicGroupRegRespDto musicGroupRegResp = new MusicGroupRegRespDto();

        //乐团信息
        MusicGroup musicGroup = musicGroupService.get(musicGroupId);
        musicGroupRegResp.setMusicGroupName(musicGroup.getName());
        musicGroupRegResp.setMusicGroupStatus(musicGroup.getStatus().getCode());
        //声部信息
        List<Subject> subjectList = subjectService.findSubByMusicGroupId(musicGroupId);
        musicGroupRegResp.setSubjectList(subjectList);

        return musicGroupRegResp;
    }

    @Override
    public void addApplyStudentNum(String musicGroupId, Integer subjectId, int num){
        boolean flag = false;
        for (int i = 10; i >= 1; i--) {
            MusicGroupSubjectPlan musicOneSubjectClassPlan = musicGroupSubjectPlanDao.getMusicOneSubjectClassPlan(musicGroupId, subjectId);
            if(musicOneSubjectClassPlan == null){
                MusicGroup musicGroup = musicGroupService.get(musicGroupId);
                Subject subject = subjectService.get(subjectId);
                throw new BizException("操作失败：{}乐团缺少{}声部",musicGroup.getName(),subject.getName());
            }
            int applyNum = musicOneSubjectClassPlan.getApplyStudentNum() == null ? 0 : musicOneSubjectClassPlan.getApplyStudentNum();
            musicOneSubjectClassPlan.setApplyStudentNum(applyNum + num);
            musicOneSubjectClassPlan.setUpdateTime(new Date());
            int updateCount = musicGroupSubjectPlanDao.update(musicOneSubjectClassPlan);
            if (updateCount >= 0) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new BizException("系统繁忙，请重试");
        }
    }

    @Override
    public int batchUpdateFee(List<MusicGroupSubjectPlan> musicGroupSubjectPlans) {
        return musicGroupSubjectPlanDao.batchUpdateFee(musicGroupSubjectPlans);
    }

    @Override
    public MusicGroupSubjectGoodsAndInfoDto getStudentGoodsAndInfo(String musicGroupId, Integer subjectId, StudentRegistration studentRegistration) {
        MusicGroup musicGroup = musicGroupService.get(musicGroupId);

        //课程形态
        Map<String, Object> courseForm = JSON.parseObject(musicGroup.getCourseForm(), Map.class);

        //乐团计划及收费信息
        MusicGroupSubjectPlan musicOneSubjectClassPlan = this.getMusicOneSubjectClassPlan(musicGroupId, subjectId);
        musicOneSubjectClassPlan.setFee(studentRegistration.getTemporaryCourseFee());
        musicOneSubjectClassPlan.setDepositFee(studentRegistration.getTemporaryCourseFee());

        //乐团乐器及辅件信息
        List<MusicGroupSubjectGoodsGroup> goodsGroups = new ArrayList<>();

        List<StudentPaymentOrderDetail> orderDetails = studentPaymentOrderDetailDao.findUserApplyOrder(studentRegistration.getUserId(), musicGroupId, DealStatusEnum.WAIT_PAY);
        for (StudentPaymentOrderDetail orderDetail : orderDetails) {
            if (orderDetail == null || orderDetail.getGoodsIdList() == null || orderDetail.getGoodsIdList().isEmpty())
                continue;
            MusicGroupSubjectGoodsGroup musicGroupSubjectGoodsGroup = new MusicGroupSubjectGoodsGroup();
            if (orderDetail.getType().equals(OrderDetailTypeEnum.MUSICAL)) {
                musicGroupSubjectGoodsGroup.setName("乐器");
                musicGroupSubjectGoodsGroup.setType(GoodsType.INSTRUMENT);
            } else {
                musicGroupSubjectGoodsGroup.setName("辅件");
                musicGroupSubjectGoodsGroup.setType(GoodsType.ACCESSORIES);
            }
            if (orderDetail.getKitGroupPurchaseType() != null) {
                if (orderDetail.getKitGroupPurchaseType().equals(KitGroupPurchaseTypeEnum.LEASE)) {
                    musicGroupSubjectGoodsGroup.setDepositFee(orderDetail.getPrice());
                }
                String kitGroupPurchaseTypeJson = "{\"" + orderDetail.getKitGroupPurchaseType().getCode() + "\":0}";
                musicGroupSubjectGoodsGroup.setKitGroupPurchaseTypeJson(kitGroupPurchaseTypeJson);
            }

            musicGroupSubjectGoodsGroup.setId(orderDetail.getId());
            musicGroupSubjectGoodsGroup.setGoodsIdList(orderDetail.getGoodsIdList());
            musicGroupSubjectGoodsGroup.setMusicGroupId(musicGroupId);
            musicGroupSubjectGoodsGroup.setPrice(orderDetail.getPrice());
            List<Goods> goodies = goodsService.findGoodsByIds(orderDetail.getGoodsIdList());
            musicGroupSubjectGoodsGroup.setGoodsList(goodies);
            goodsGroups.add(musicGroupSubjectGoodsGroup);
        }

        //获取声部（科目）下其他商品
        MusicGroupSubjectGoodsAndInfoDto musicGroupSubjectGoodsAndInfo = new MusicGroupSubjectGoodsAndInfoDto();
        musicGroupSubjectGoodsAndInfo.setMusicGroupSubjectPlan(musicOneSubjectClassPlan);
        musicGroupSubjectGoodsAndInfo.setCourseScheduleInfo(courseForm);
        musicGroupSubjectGoodsAndInfo.setMusicGroupSubjectGoodsGroupList(goodsGroups);
        return musicGroupSubjectGoodsAndInfo;
    }

    @Override
    public MusicGroupSubjectPlan findSubjectPlan(String musicGroupId, Integer subjectId) {
        return musicGroupSubjectPlanDao.findSubjectPlan(musicGroupId, subjectId);
    }

    @Override
    public List<MusicGroupGoodsAndDiscountDto> getSubjectGoods(Integer subjectId, String type, Integer chargeTypeId) {
        List<MusicGroupGoodsAndDiscountDto> goodsList = goodsDao.getMusicGroupGoodsAndDiscount(subjectId, type);
        if (chargeTypeId == null || (type != null && !"INSTRUMENT".equals(type))) {
            return goodsList;
        }

        ChargeTypeSubjectMapper subjectDiscount = chargeTypeSubjectMapperDao.getSubjectDiscount(chargeTypeId, subjectId);
        if (subjectDiscount == null || subjectDiscount.getGoodsDiscountRate() == null || subjectDiscount.getGoodsDiscountRate().compareTo(new BigDecimal(100)) == 0) {
            return goodsList;
        }
        for (MusicGroupGoodsAndDiscountDto musicGroupGoodsAndDiscountDto : goodsList) {
            if (musicGroupGoodsAndDiscountDto.getType() != null && musicGroupGoodsAndDiscountDto.getType().equals(GoodsType.INSTRUMENT)) {
                musicGroupGoodsAndDiscountDto.setDiscountRate(subjectDiscount.getGoodsDiscountRate());
                musicGroupGoodsAndDiscountDto.setGroupPurchasePrice(musicGroupGoodsAndDiscountDto.getDiscountPrice().multiply(subjectDiscount.getGoodsDiscountRate()).divide(new BigDecimal(100), 0, BigDecimal.ROUND_HALF_UP));
            }
        }
        return goodsList;
    }
}
