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


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.GoodsSellDto;
import com.ym.mec.biz.dal.dto.StudentGoodsSellDto;
import com.ym.mec.biz.dal.dto.StudentPaymentOrderDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.page.GoodsSellQueryInfo;
import com.ym.mec.biz.service.StudentGoodsSellService;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysTenantConfigService;
import com.ym.mec.biz.service.TenantInfoService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
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 org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class StudentGoodsSellServiceImpl extends BaseServiceImpl<Integer, StudentGoodsSell> implements StudentGoodsSellService {

    @Autowired
    private StudentGoodsSellDao studentGoodsSellDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SysTenantConfigService sysTenantConfigService;
    @Autowired
    private TenantInfoService tenantInfoService;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private StudentInstrumentDao studentInstrumentDao;
    @Autowired
    private SysCouponCodeDao sysCouponCodeDao;

    @Override
    public BaseDAO<Integer, StudentGoodsSell> getDAO() {
        return studentGoodsSellDao;
    }

    @Override
    public PageInfo<StudentGoodsSellDto> queryStudentGoodsOrders(GoodsSellQueryInfo queryInfo) {
        //根据订单状态和教务老师获取订单列表
        PageInfo<StudentGoodsSellDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        List<StudentGoodsSellDto> dataList = null;
        int count = studentGoodsSellDao.countStudentGoodsOrders(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentGoodsSellDao.queryStudentGoodsOrders(params);
            Integer tenantId = TenantContextHolder.getTenantId();
            String autoAffirmReceiveTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.AUTO_AFFIRM_RECEIVE_TIME,tenantId);
            if(StringUtils.isNotEmpty(autoAffirmReceiveTime)){
                dataList.forEach(e -> {
                    e.setAutoAffirmReceiveTime(Integer.parseInt(autoAffirmReceiveTime));
                });
            }
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void affirmReceive(String orderNo) {
        String str = "MANUAL_RECEIVE";
        if (StringUtils.isNotEmpty(orderNo)) {
            studentGoodsSellDao.autoAffirmReceive(orderNo, str);
            return;
        }
        //如果订单编号为空，那么自动确认
        StringBuffer sb = new StringBuffer();
        str = "AUTO_RECEIVE";
        List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
        if(tenantInfos != null && tenantInfos.size() > 0){
            for (int i = 0; i < tenantInfos.size(); i++) {
                TenantInfo tenantInfo = tenantInfos.get(i);
                String autoAffirmReceiveTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.AUTO_AFFIRM_RECEIVE_TIME,tenantInfo.getId());
                //获取到期的订单编号
                String s = studentGoodsSellDao.queryNoAffirmOrderNo(autoAffirmReceiveTime, tenantInfo.getId());
                if(StringUtils.isNotEmpty(s)){
                    sb.append(s).append(",");
                }
            }
            if (sb.length() > 0) {
                studentGoodsSellDao.autoAffirmReceive(sb.substring(0,sb.length() - 1), str);
            }
        }
    }

    @Override
    public PageInfo<StudentPaymentOrderDto> queryStudentPaymentOrders(GoodsSellQueryInfo queryInfo) {
        PageInfo<StudentPaymentOrderDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        List<StudentPaymentOrderDto> dataList = null;
        int count = studentGoodsSellDao.countStudentPaymentOrders(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentGoodsSellDao.queryStudentPaymentOrders(params);
            Integer tenantId = TenantContextHolder.getTenantId();
            String autoAffirmReceiveTime = sysTenantConfigService.getTenantConfigValue(SysConfigService.AUTO_AFFIRM_RECEIVE_TIME,tenantId);
            if(StringUtils.isNotEmpty(autoAffirmReceiveTime)){
                dataList.forEach(e -> {
                    e.setAutoAffirmReceiveTime(Integer.parseInt(autoAffirmReceiveTime));
                });
            }
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public List<StudentInstrument> saveStudentInstrument(StudentPaymentOrder order) {
        StudentGoodsSell studentGoodsSell = studentGoodsSellDao.findByOrderNo(order.getOrderNo());
        List<GoodsSellDto> goodsSellDtos = JSONObject.parseArray(studentGoodsSell.getGoodsJson(), GoodsSellDto.class);
        List<Integer> goodsIds = new ArrayList<>();
        for (GoodsSellDto goodsSellDto : goodsSellDtos) {
            if (!goodsSellDto.getGoodsType().equals("INSTRUMENT")) continue;
            goodsIds.add(goodsSellDto.getGoodsId());
        }
        if (goodsIds.size() <= 0) {
            return null;
        }
        List<Goods> goodies = goodsDao.getGoodiesAndCate(goodsIds);
        List<StudentInstrument> studentInstruments = new ArrayList<>();
        for (Goods goods : goodies) {
            StudentInstrument studentInstrument = new StudentInstrument();
            studentInstrument.setStudentId(studentGoodsSell.getUserId());
            studentInstrument.setOrganId(studentGoodsSell.getOrganId());
            studentInstrument.setGoodsId(goods.getId());
            studentInstrument.setGoodsCategoryId(goods.getGoodsCategoryId());
            studentInstrument.setGoodsCategoryName(goods.getGoodsCategoryName());
            studentInstrument.setGoodsName(goods.getName());
            studentInstrument.setGoodsBrand(goods.getBrand());
            studentInstrument.setSpecification(goods.getSpecification());
            studentInstrument.setGoodsImg(goods.getImage());
            studentInstrument.setOrderId(order.getId());
            studentInstrument.setChangeOrderId(order.getId());
            studentInstrument.setStatus(0);
            studentInstruments.add(studentInstrument);
        }
        studentInstrumentDao.batchAdd(studentInstruments);
        return studentInstruments;
    }

    @Override
    public StudentGoodsSell getStudentGoodsOrder(Integer goodsSellId) {
        StudentGoodsSell studentGoodsSell = studentGoodsSellDao.get(goodsSellId);
        //获取优惠券列表
        String couponIds = studentGoodsSell.getCouponIds();
        if(StringUtils.isNotEmpty(couponIds)){
            List<Integer> couponIdList = Arrays.stream(couponIds.split(",")).map(id -> Integer.valueOf(id)).collect(Collectors.toList());
            studentGoodsSell.setCouponCodeDtoList(sysCouponCodeDao.findByIdList(couponIdList));
        }
        return studentGoodsSell;
    }
}