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

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.MusicGroupGoodsAndDiscountDto;
import com.ym.mec.biz.dal.dto.MusicGroupRegRespDto;
import com.ym.mec.biz.dal.dto.MusicGroupSubjectGoodsAndInfoDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.dal.enums.GoodsType;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

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

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

    @Autowired
    private MusicGroupSubjectPlanDao musicGroupSubjectPlanDao;

    @Autowired
    private StudentRegistrationService studentRegistrationService;

    @Autowired
    private SysTenantConfigService sysTenantConfigService;

    @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 MusicGroupPaymentCalenderService musicGroupPaymentCalenderService;
    @Autowired
    private OrganizationCloudTeacherFeeDao organizationCloudTeacherFeeDao;

	@Autowired
	private MemberRankPrivilegesService memberRankPrivilegesService;
	
	@Autowired
	private OrganizationCourseUnitPriceSettingsService organizationCourseUnitPriceSettingsService;
	
    @Resource
    private SysUserFeignService sysUserFeignService;

    @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);
        if(musicGroup == null){
        	throw new BizException("乐团信息查询失败");
        }
        if(musicGroup.getTenantId() == null){
        	throw new BizException("乐团机构信息异常，请联系管理员");
        }
        String configValue = sysTenantConfigService.getTenantConfigValue(SysConfigService.MEMBER_GROUP_TERM_GIVE_COURSE_TIME, musicGroup.getTenantId());
        if(StringUtils.isEmpty(configValue)){
            throw new BizException("请配置会员团每学期赠送课程分钟数");
        }
        //乐团计划及收费信息
        MusicGroupSubjectPlan musicOneSubjectClassPlan = this.getMusicOneSubjectClassPlan(musicGroupId, subjectId);
        //乐团乐器及辅件信息
        List<MusicGroupSubjectGoodsGroup> goodsGroups = musicGroupSubjectGoodsGroupService.findGoodsGroup(musicGroupId, subjectId);

        for (MusicGroupSubjectGoodsGroup goodsGroup : goodsGroups) {
            String childGoodIds = "";
            for (Goods goods : goodsGroup.getGoodsList()) {
                if (StringUtils.isNotBlank(goods.getComplementGoodsIdList())) {
                    childGoodIds += StringUtils.isNotBlank(childGoodIds) ? "," : "" + goods.getComplementGoodsIdList();
                }
            }
            if (StringUtils.isNotBlank(childGoodIds)) {
                goodsGroup.setChildGoodsList(goodsDao.findGoodsByIds(childGoodIds));
            }
        }
        //获取声部（科目）下其他商品
        MusicGroupSubjectGoodsAndInfoDto musicGroupSubjectGoodsAndInfo = new MusicGroupSubjectGoodsAndInfoDto();
        musicGroupSubjectGoodsAndInfo.setMusicGroupSubjectPlan(musicOneSubjectClassPlan);
        musicGroupSubjectGoodsAndInfo.setMusicGroupSubjectGoodsGroupList(goodsGroups);
        musicGroupSubjectGoodsAndInfo.setMusicGroup(musicGroup);
        //新的课程形态10.27
        MusicGroupPaymentCalender musicGroupRegCalender = musicGroupPaymentCalenderService.getMusicGroupRegCalender(musicGroupId);
        if (musicGroupRegCalender != null) {
            musicGroupSubjectGoodsAndInfo.setPaymentCalender(musicGroupPaymentCalenderService.getDetail(musicGroupRegCalender.getId()));
        }
		// 查询已购买内容
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser != null){
        	Integer userId = sysUser.getId();
        	musicGroupSubjectGoodsAndInfo.setStudentPaymentOrderDetailList(studentPaymentOrderDetailDao.findUserApplyOrder(userId, musicGroupId, DealStatusEnum.SUCCESS));
        }
        
        return musicGroupSubjectGoodsAndInfo;
    }

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

        //乐团信息
        MusicGroup musicGroup = musicGroupService.get(musicGroupId);
        musicGroupRegResp.setMusicGroupName(musicGroup.getName());
        musicGroupRegResp.setCourseViewType(musicGroup.getCourseViewType());
        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 MusicGroupSubjectPlan findSubjectPlan(String musicGroupId, Integer subjectId) {
        return musicGroupSubjectPlanDao.findSubjectPlan(musicGroupId, subjectId);
    }

    @Override
    public List<MusicGroupGoodsAndDiscountDto> getSubjectGoods(Integer subjectId, String type, Integer chargeTypeId, Integer courseViewType, String musicGroupId) {
        Integer organId = null;
        if (StringUtils.isNotEmpty(musicGroupId)) {
            MusicGroup musicGroup = musicGroupService.get(musicGroupId);
            courseViewType = musicGroup.getCourseViewType().getCode();
            organId = musicGroup.getOrganId();
        }
        List<MusicGroupGoodsAndDiscountDto> goodsList = goodsDao.getMusicGroupGoodsAndDiscount(subjectId, type, courseViewType,organId, TenantContextHolder.getTenantId());
        if (chargeTypeId == null || (type != null && !"INSTRUMENT".equals(type))) {
            return goodsList;
        }

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