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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.musicalListDetailDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
import com.ym.mec.biz.service.MusicGroupService;
import com.ym.mec.util.collection.MapUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.service.GoodsService;
import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
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 StudentPaymentOrderDetailServiceImpl extends BaseServiceImpl<Long, StudentPaymentOrderDetail> implements StudentPaymentOrderDetailService {

    @Autowired
    private StudentPaymentOrderDetailDao studentPaymentOrderDetailDao;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private MusicGroupDao musicGroupDao;
    @Autowired
    private OrganizationDao organizationDao;
    @Autowired
    private MusicGroupPurchaseListDao musicGroupPurchaseListDao;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private StudentRegistrationDao studentRegistrationDao;

    @Override
    public BaseDAO<Long, StudentPaymentOrderDetail> getDAO() {
        return studentPaymentOrderDetailDao;
    }

    @Override
    public int batchAdd(List<StudentPaymentOrderDetail> studentPaymentOrderDetailList) {
        return studentPaymentOrderDetailDao.batchAdd(studentPaymentOrderDetailList);
    }

    @Override
    public List<StudentPaymentOrderDetail> findApplyOrderSuccess(String musicGroupId, DealStatusEnum status) {
        return studentPaymentOrderDetailDao.findApplyOrderSuccess(musicGroupId, status);
    }

    @Override
	public List<Goods> getMusicalList(String musicGroupId) {
		List<StudentPaymentOrderDetail> applyOrder = findApplyOrderSuccess(musicGroupId, DealStatusEnum.SUCCESS);
		if (applyOrder == null || applyOrder.size() == 0) {
			return null;
		}
		String goodsIdsStr = "";
		for (StudentPaymentOrderDetail studentPaymentOrderDetail : applyOrder) {
			if (studentPaymentOrderDetail.getGoodsIdList() != null && !studentPaymentOrderDetail.getGoodsIdList().isEmpty()) {
				goodsIdsStr += studentPaymentOrderDetail.getGoodsIdList() + ",";
			}
		}
		if (StringUtils.isNotBlank(goodsIdsStr)) {
			goodsIdsStr = goodsIdsStr.substring(0, goodsIdsStr.length() - 1);

			String[] goodSIdArr = goodsIdsStr.split(",");

			List<Goods> goodies = goodsService.findGoodsByIds(goodsIdsStr);
            MusicGroup musicGroup = musicGroupDao.get(musicGroupId);
            Organization organization = organizationDao.get(musicGroup.getOrganId());
            goodies.forEach(e->{
                e.setSellCount(0);
                //当作乐团名称字段处理
                e.setMemo(musicGroup.getName());
                //当作分部名称字段处理
                e.setBrief(organization.getName());
                for (String goodsIdStr : goodSIdArr) {
                    if (e.getId().equals(Integer.parseInt(goodsIdStr))) {
                        e.setSellCount(e.getSellCount() + 1);
                    }
                }
            });
			return goodies;
		}
		return null;
	}

    @Override
    public Boolean verifyMusicalList(String musicGroupId) throws BizException {
        //乐器采购清单是否确认
        Map<String, Object> param = new HashMap<>();
        param.put("musicGroupId", musicGroupId);
        int count = musicGroupPurchaseListDao.queryCount(param);
        if (count > 0) {
            throw new BizException("采购清单已经确认");
        }

        List<Goods> musicalList = getMusicalList(musicGroupId);
        Date date = new Date();
        List<MusicGroupPurchaseList> musicGroupPurchaseLists = new ArrayList<>();
        //发放清单没有时确认特殊处理
        if (musicalList == null || musicalList.size() == 0) {
            musicalList = new ArrayList<>();
            Goods goods = new Goods();
            goods.setId(0);
            goods.setSellCount(0);
            musicalList.add(goods);
        }

        for (Goods goods : musicalList) {
            MusicGroupPurchaseList musicGroupPurchaseList = new MusicGroupPurchaseList();
            musicGroupPurchaseList.setGoodsId(goods.getId());
            musicGroupPurchaseList.setMusicGroupId(musicGroupId);
            musicGroupPurchaseList.setPurchaseNum(goods.getSellCount());
            musicGroupPurchaseList.setCreateTime(date);
            musicGroupPurchaseList.setUpdateTime(date);
            musicGroupPurchaseLists.add(musicGroupPurchaseList);
        }
        musicGroupPurchaseListDao.batchInsert(musicGroupPurchaseLists);
        return true;
    }

    @Override
    public List<Goods> findApplyOrderGoods(Long orderId) {
        List<StudentPaymentOrderDetail> applyOrderGoods = studentPaymentOrderDetailDao.findApplyOrderGoods(orderId);

        if (applyOrderGoods == null || applyOrderGoods.size() == 0) {
            return null;
        }
        String goodsIdsStr = "";
        for (StudentPaymentOrderDetail studentPaymentOrderDetail : applyOrderGoods) {
            if (studentPaymentOrderDetail.getGoodsIdList() != null && !studentPaymentOrderDetail.getGoodsIdList().isEmpty()) {
                goodsIdsStr += studentPaymentOrderDetail.getGoodsIdList() + ",";
            }
        }
        if(goodsIdsStr.isEmpty()){
            return null;
        }
        goodsIdsStr = goodsIdsStr.substring(0, goodsIdsStr.length() - 1);

        String[] goodSIdArr = goodsIdsStr.split(",");

        List<Goods> goodies = goodsService.findGoodsByIds(goodsIdsStr);

        for (Goods goods : goodies) {
            goods.setSellCount(0);
            for (String goodsIdStr : goodSIdArr) {
                if (goods.getId().equals(Integer.parseInt(goodsIdStr))) {
                    goods.setSellCount(goods.getSellCount() + 1);
                }
            }
        }
        return goodies;
    }

    @Override
    public List<StudentPaymentOrderDetail> findUserApplyOrder(Integer userId, DealStatusEnum status) {
        return studentPaymentOrderDetailDao.findUserApplyOrder(userId, status);
    }

    @Override
    public List<musicalListDetailDto> getMusicalListDetail(String musicGroupId) {
        List<musicalListDetailDto> musicalListDetailDtos = studentPaymentOrderDetailDao.getMusicalListDetail(musicGroupId);
        if(musicalListDetailDtos != null && musicalListDetailDtos.size() > 0){
            List<Long> paymentOrderNo = musicalListDetailDtos.stream().map(e -> e.getPaymentOrderId()).collect(Collectors.toList());
            List<Integer> userIds = musicalListDetailDtos.stream().map(e -> e.getUserId()).collect(Collectors.toList());
            //商品名称
            MusicGroup musicGroup = musicGroupDao.get(musicGroupId);
            Organization organization = organizationDao.get(musicGroup.getOrganId());
            Map<Long,String> goodsNameMap = MapUtil.convertIntegerMap(studentPaymentOrderDetailDao.queryGoodsNames(paymentOrderNo));
            Map<Integer,String> usernameMap = MapUtil.convertIntegerMap(teacherDao.queryUsernameByIds(userIds));
            Map<Long, BigDecimal> actualAmountMap = MapUtil.convertIntegerMap(studentPaymentOrderDao.queryActualAmount(paymentOrderNo));
            Map<Long, BigDecimal> musicalAmountMap = MapUtil.convertIntegerMap(studentPaymentOrderDetailDao.queryGoodsPrice(paymentOrderNo,"MUSICAL"));
            Map<Long, BigDecimal> accessoriesAmountMap = MapUtil.convertIntegerMap(studentPaymentOrderDetailDao.queryGoodsPrice(paymentOrderNo,"ACCESSORIES"));
            Map<Long, BigDecimal> courseAmountMap = MapUtil.convertIntegerMap(studentPaymentOrderDetailDao.queryGoodsPrice(paymentOrderNo,"COURSE"));
            Map<Long, String> purchaseTypeMap = MapUtil.convertIntegerMap(studentRegistrationDao.queryPurchaseTypeMap(musicGroupId));
            musicalListDetailDtos.forEach(e->{
                e.setGoodsNames(goodsNameMap.get(e.getPaymentOrderId()));
                e.setMusicGroupName(musicGroup.getName());
                e.setUsername(usernameMap.get(e.getUserId()));
                e.setOrganName(organization.getName());
                e.setMusicalAmount(musicalAmountMap.get(e.getPaymentOrderId()));
                e.setAccessoriesAmount(accessoriesAmountMap.get(e.getPaymentOrderId()));
                e.setOrderAmount(actualAmountMap.get(e.getPaymentOrderId()));
                e.setCourseAmount(courseAmountMap.get(e.getPaymentOrderId()));
                e.setKitGroupPurchaseTypeEnum(KitGroupPurchaseTypeEnum.valueOf(purchaseTypeMap.get(e.getUserId())));
            });
        }
        return musicalListDetailDtos;
    }

    @Override
    public StudentPaymentOrderDetail findApplyOrderMusical(Long orderId) {
        return studentPaymentOrderDetailDao.findApplyOrderMusical(orderId);
    }
}