package com.ssj.service.weixin.order.service.impl;


import com.ssj.bean.kmt.kmt.domain.KmtCourse;
import com.ssj.bean.sys.cardinfo.domain.TbCardInfo;
import com.ssj.bean.sys.lesson.domain.LessonService;
import com.ssj.bean.weixin.order.domain.LessonServiceSales;
import com.ssj.bean.weixin.order.domain.PayB2C;
import com.ssj.dao.weixin.order.dao.LessonServiceSalesDao;
import com.ssj.dao.weixin.order.dao.OrderQueryDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.weixin.util.DateUtil;
import com.ssj.service.kmt.service.KmtCourseService;
import com.ssj.service.sys.cardinfo.service.ICardInfoService;
import com.ssj.service.sys.lesson.service.LessonServiceService;
import com.ssj.service.weixin.order.service.LessonServiceSalesService;
import com.ssj.service.weixin.order.service.PayB2CService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class LessonServiceSalesServiceImpl extends BaseServiceImpl<LessonServiceSales, String> implements LessonServiceSalesService{
	
	private   Logger logger = LoggerFactory.getLogger(this.getClass());
	   
	@Autowired
	private LessonServiceSalesDao  lessonServiceSalesDao;
	
	@Autowired
	private OrderQueryDao  orderQueryDao;


	@Autowired
	private KmtCourseService kmtCourseService;

	@Autowired
	private LessonServiceService lessonServiceService;
	
	@Autowired
	private PayB2CService  payB2CService;
	
	@Autowired
	private ICardInfoService cardInfoService;
	
	@Override
	public PagingAndSortingRepository<LessonServiceSales, String> getDao() {
		return lessonServiceSalesDao;
	}

	@Override
	public synchronized boolean saveLessonServiceSalesByCourse(String courseId) {
		
		KmtCourse kmtCourse=kmtCourseService.getById(courseId);
		List<LessonServiceSales> salesList=lessonServiceSalesDao.findLessonServiceSalesByCourse(courseId);
				
		//kmtCourse不为空，同时已结课is_finish=1，同时是1:正式课course_type=1，同时lesson_service_id不为空
		//kmt_course_id 整表唯一,不可重复
		if(kmtCourse!=null && 1==kmtCourse.getIsFinish() 
				&& 1==kmtCourse.getCourseType() && StringUtils.isNotEmpty(kmtCourse.getLessonServiceId())
				&& CollectionUtils.isEmpty(salesList)){
			
			//查询流水订单数据
			LessonService lessonService=lessonServiceService.getById(kmtCourse.getLessonServiceId());
			
			if(lessonService!=null){
				
					LessonServiceSales sales=new LessonServiceSales();
					sales.setLibId(lessonService.getLibId());
					sales.setMasterId(lessonService.getMasterId());
					sales.setTeacherId(kmtCourse.getTeacherId());
					sales.setTeacherType(kmtCourse.getTeacherType());
					sales.setTeacherLever(kmtCourse.getTeacherLever());
					sales.setKmtCourseId(courseId);
					sales.setLessonServiceId(lessonService.getId());
					sales.setPrice(lessonService.getPrice());
					sales.setFinishTime(new Date());
					sales.setState(1);//正常
					try {
						String teacherLever=kmtCourse.getTeacherLever();//注册/明星/学霸
						String teacherType=kmtCourse.getTeacherType();//全职/兼职
						BigDecimal t_price  = new BigDecimal(0);//老师分成
						BigDecimal s_price  = new BigDecimal(0);//公司分成
						BigDecimal l_price  = new BigDecimal(0);//图书馆分成
						BigDecimal sd_price  = new BigDecimal(0);//sd分成
						String libId = lessonService.getLibId();
						BigDecimal price= lessonService.getPrice();
						if("全职".equals(teacherType)){
							
							if("资深老师".equals(teacherLever)){//计算资深老师分成...
							
								 if("7a59a20c-7335-42f6-ac5d-9d4aab3e0ee9".equals(libId)){ //校长大本营
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.24").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
								 }else if("b0d5df83-9899-451d-95e0-b26a6d9bc9a2".equals(libId)){   //旗舰馆
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.32").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.08").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
								 }else{  //独立馆
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.08").setScale(2,BigDecimal.ROUND_CEILING));
								 }
								 
							}else{//计算普通老师分成...
								
								 if("7a59a20c-7335-42f6-ac5d-9d4aab3e0ee9".equals(libId)){ //校长大本营
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.4").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  new BigDecimal(0);
								 }else if("b0d5df83-9899-451d-95e0-b26a6d9bc9a2".equals(libId)){   //旗舰馆
									 t_price  =  price.multiply(new BigDecimal("0.4").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  new BigDecimal(0);
								 }else{  //独立馆
									 t_price  =  price.multiply(new BigDecimal("0.4").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.4").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  price.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  new BigDecimal(0);
								 }
								
							}
							
						}else if("兼职".equals(teacherType)){
							if("注册老师".equals(teacherLever)){
								if("7a59a20c-7335-42f6-ac5d-9d4aab3e0ee9".equals(libId)){ //校长大本营
									 t_price  =  price.multiply(new BigDecimal("0.5").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  price.multiply(new BigDecimal("0.3").setScale(2,BigDecimal.ROUND_CEILING));
								 }else if("b0d5df83-9899-451d-95e0-b26a6d9bc9a2".equals(libId)){   //旗舰馆
									 t_price  =  price.multiply(new BigDecimal("0.5").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.4").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  price.multiply(new BigDecimal("0.1").setScale(2,BigDecimal.ROUND_CEILING));
								 }else{  //独立馆
									 t_price  =  price.multiply(new BigDecimal("0.5").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  price.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.1").setScale(2,BigDecimal.ROUND_CEILING));
								 }
							}else if("明星老师".equals(teacherLever)){
								if("7a59a20c-7335-42f6-ac5d-9d4aab3e0ee9".equals(libId)){ //校长大本营
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  price.multiply(new BigDecimal("0.24").setScale(2,BigDecimal.ROUND_CEILING));
								 }else if("b0d5df83-9899-451d-95e0-b26a6d9bc9a2".equals(libId)){   //旗舰馆
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.32").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  price.multiply(new BigDecimal("0.08").setScale(2,BigDecimal.ROUND_CEILING));
								 }else{  //独立馆
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.08").setScale(2,BigDecimal.ROUND_CEILING));
								 }
							}else if("学霸老师".equals(teacherLever)){
								if("7a59a20c-7335-42f6-ac5d-9d4aab3e0ee9".equals(libId)){ //校长大本营
									 t_price  =  price.multiply(new BigDecimal("0.5").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  price.multiply(new BigDecimal("0.3").setScale(2,BigDecimal.ROUND_CEILING));
								 }else if("b0d5df83-9899-451d-95e0-b26a6d9bc9a2".equals(libId)){   //旗舰馆
									 t_price  =  price.multiply(new BigDecimal("0.5").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.4").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
									 sd_price =  price.multiply(new BigDecimal("0.1").setScale(2,BigDecimal.ROUND_CEILING));
								 }else{  //独立馆
									 t_price  =  price.multiply(new BigDecimal("0.5").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  price.multiply(new BigDecimal("0.2").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.1").setScale(2,BigDecimal.ROUND_CEILING));
								 }
							}else if("资深老师".equals(teacherLever)){//计算资深老师分成...
								
								 if("7a59a20c-7335-42f6-ac5d-9d4aab3e0ee9".equals(libId)){ //校长大本营
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.24").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
								 }else if("b0d5df83-9899-451d-95e0-b26a6d9bc9a2".equals(libId)){   //旗舰馆
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.32").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.08").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  new BigDecimal(0);
								 }else{  //独立馆
									 t_price  =  price.multiply(new BigDecimal("0.6").setScale(2,BigDecimal.ROUND_CEILING));
									 s_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 l_price  =  price.multiply(new BigDecimal("0.16").setScale(2,BigDecimal.ROUND_CEILING));
									 sd_price =  price.multiply(new BigDecimal("0.08").setScale(2,BigDecimal.ROUND_CEILING));
								 }
								 
							}
						}
						sales.setTeacherSales(t_price);
						sales.setLibSales(l_price);
						sales.setFirmSales(s_price);
						sales.setSdSales(sd_price);
				} catch (Exception e) {
					sales.setState(2);//记录异常，不计算分成。
					sales.setRemark("异常,e:"+e.getMessage());
					logger.info("反馈计算分成异常...courseId:"+courseId);
				}finally{
					lessonServiceSalesDao.save(sales);
				}
			 return true;
			}
		}
		return false;
	}

	@Override
	public void computeSalesOfLibAndFirm(Date startTime, Date endTime) {
        String startTimeStr = DateUtil.format_yyyyMMdd(startTime);
        String endTimeStr = DateUtil.format_yyyyMMdd(endTime);
        //统计各个共享馆上月的在读学生数
        List<Map<String,Object>> studentSumStudyingInSharedLibCountList = orderQueryDao.countStudentSumStudyingInSharedLib(startTimeStr, endTimeStr);
        //查询需要计算的分成记录
        List<LessonServiceSales> lessonServiceSalesList = lessonServiceSalesDao.findListNeedCompute(startTimeStr, endTimeStr);
        lessonServiceSalesList.forEach(lessonServiceSales -> studentSumStudyingInSharedLibCountList.forEach(it -> {
            if (Objects.equals(it.get("lib_id"), lessonServiceSales.getLibId())) {
                BigDecimal firmSales;//本公司分成金额
                BigDecimal libSales;//机构分成金额
                BigDecimal proportion = BigDecimal.ZERO;//机构分成比例
                switch (lessonServiceSales.getTeacherLever()) {
                    case "注册老师" :
                        proportion = proportion.add(new BigDecimal("0.2"));
                        break;
                    case "资深老师" :
                        proportion = proportion.add(new BigDecimal("0.15"));
                        break;
                    case "明星老师" :
                        proportion = proportion.add(new BigDecimal("0.1"));
                        break;
                }
                if (Integer.valueOf(it.get("student_sum").toString()) >= 10) {
                    proportion = proportion.add(new BigDecimal("0.05"));
                }
                BigDecimal lessonPrice = lessonServiceSales.getPrice();
                libSales = lessonPrice.multiply(proportion).setScale(2, BigDecimal.ROUND_CEILING);
                firmSales = lessonPrice.subtract(libSales).subtract(lessonServiceSales.getTeacherSales());
                lessonServiceSales.setLibSales(libSales);
                lessonServiceSales.setFirmSales(firmSales);
                lessonServiceSales.setUpdateTime(new Date());
                lessonServiceSalesDao.save(lessonServiceSales);
            }
        }));
    }

	@Override
	public boolean countLessonServiceSalesByTime(Date startTime, Date endTime) {
		logger.info("每月第一天早上八点更新上月的结算金额统计"+startTime);
		logger.info("每月第一天早上八点更新上月的结算金额统计"+endTime);
		boolean is=false;

		//统计分成生成打款记录
		List<Map<String,Object>> salesByTime=orderQueryDao.countLessonServiceSalesByGroup(startTime, endTime);
		try {
			for (Map<String, Object> map : salesByTime) {

					String joinid=map.get("joinid").toString();
					//String teacherLever=(String)map.get("teacher_lever");
					String ids=map.get("ids").toString();
					BigDecimal countsales=new BigDecimal(map.get("countsales").toString());
					String type=map.get("type").toString();//type=1 是馆（只统计，不插入打款记录，后期处理再打算），type=2老师，type=3是sd
					PayB2C pay=new PayB2C();
					if("1".equals(type)){ //馆方
						//查询这个馆是否有配置收款账号信息
						TbCardInfo cardInfo = cardInfoService.findByLibId(joinid);
						if(cardInfo !=null){
							pay.setUserId(cardInfo.getUserId());
							pay.setPayStatus(2);
						}else{
							pay.setUserId(joinid);
							pay.setPayStatus(10);
						}

					}else{
						pay.setUserId(joinid);
						pay.setPayStatus(2);
					}

					pay.setCreateTime(new Date());
					pay.setAmount(countsales);

					pay.setType(2);
					payB2CService.save(pay);//保存打款流水

					if(StringUtils.isNotEmpty(pay.getId())){//保证打款保存成功
						if("2".equals(type)){
							lessonServiceSalesDao.updateTeacherPayBusinessIdByIds(pay.getId(), Arrays.asList(ids.split(",")));
						}else if("3".equals(type)){
							lessonServiceSalesDao.updateSdPayBusinessIdIdByIds(pay.getId(), Arrays.asList(ids.split(",")));
						}else if ("1".equals(type)){
							lessonServiceSalesDao.updateLibPayBusinessIdIdByIds(pay.getId(), Arrays.asList(ids.split(",")));
						}
					}
			}
			is=true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存打款流水异常...");
			throw new RuntimeException();
		}
		return is;
	}

	private final Object shareLock = new Object();
	@Override
	public void saveLessonServiceSalesByCourseSharedLib(KmtCourse course) {
		synchronized (shareLock) {
			String courseId = course.getId();
			List<LessonServiceSales> salesList = lessonServiceSalesDao.findLessonServiceSalesByCourse(courseId);

			//已结课is_finish=1，同时是1:正式课course_type=1
			//kmt_course_id 整表唯一,不可重复
			if(1 == course.getIsFinish() && 1 == course.getCourseType() && CollectionUtils.isEmpty(salesList)) {

				//查询流水订单数据
				LessonService lessonService = lessonServiceService.getById(course.getLessonServiceId());

				if (lessonService != null) {
					LessonServiceSales sales = new LessonServiceSales();
					sales.setLibId(lessonService.getLibId());
					sales.setMasterId(lessonService.getMasterId());
					sales.setTeacherId(course.getTeacherId());
					sales.setTeacherType(course.getTeacherType());
					sales.setTeacherLever(course.getTeacherLever());
					sales.setKmtCourseId(courseId);
					sales.setLessonServiceId(lessonService.getId());
					sales.setPrice(lessonService.getPrice());
					sales.setFinishTime(new Date());
					sales.setState(1);//正常

					BigDecimal t_price;//老师分成
					BigDecimal proportion = BigDecimal.ZERO;
					BigDecimal lessonPrice= lessonService.getPrice();//课程服务的价格

					switch (course.getTeacherLever()) {
						case "注册老师":
							proportion = new BigDecimal("0.5");
							break;
						case "资深老师":
							proportion = new BigDecimal("0.6");
							break;
						case "明星老师":
							proportion = new BigDecimal("0.75");
							break;
						default :  break;
					}
					t_price = lessonPrice.multiply(proportion).setScale(2, BigDecimal.ROUND_CEILING);
					sales.setTeacherSales(t_price);
					sales.setSdSales(BigDecimal.ZERO);
					sales.setFirmSales(BigDecimal.ZERO);
					sales.setLibSales(BigDecimal.ZERO);

					lessonServiceSalesDao.save(sales);
				}
			}
		}
	}


}
