package com.cirle.scientific.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cirle.scientific.dao.*;
import com.cirle.scientific.po.*;
import com.cirle.scientific.pojo.BizCodeEnum;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.CommonService;
import com.cirle.scientific.service.OrderService;
import com.cirle.scientific.service.QkjTaskService;
import com.cirle.scientific.utils.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {
    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private QkjPurchasedRecordsDao purchasedRecordsDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private QkjTqcourseDao tqcourseDao;

    @Autowired
    private QkjLiveDao liveDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private QkjMemberTaskInfoDao taskInfoDao;

    @Autowired
    private QkjMemberTaskDetailDao taskDetailDao;

    @Autowired
    private QkjCourseWareDao courseWareDao;

    @Autowired
    private QkjConferenceDao conferenceDao;

    @Autowired
    private QkjConferenceRecordDao conferenceRecordDao;

    @Autowired
    private QkjTaskService taskService;

    @Autowired
    private UserDao userDao;

    @Override
    public QkjPurchasedRecords findPurchasedRecords(String memCard, Integer objType, Integer objId, Integer ispackage) {
        return purchasedRecordsDao.findByMemCardAndObjId(memCard, objType, objId, ispackage);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public QkjPurchasedRecords savePurchasedRecords(QkjPurchasedRecords record) {
        return purchasedRecordsDao.save(record);
    }

    @Override
    public JSONObject inviteRank(String memCard, Integer objType, Integer objId) {
        JSONObject rstData = new JSONObject();
        List<Object[]> datas = orderDao.inviteRank(objType, objId);
        JSONArray rankList = new JSONArray();
        for (Object[] data : datas) {
            JSONObject rank = new JSONObject();
            rank.put("memNickname", data[0]);
            rank.put("memHeadimg", data[1]);
            rank.put("count", data[2]);
            rankList.add(rank);
        }
        rstData.put("rankList", rankList);
        log.info("memCard=======================" + memCard);
        if (memCard != null && !"".equals(memCard) && !memCard.equals("mevosnullmemcard")) {
            Object[] mydata = orderDao.inviteRankByMember(objType, objId, memCard);
            if (mydata != null && mydata.length > 0) {
                Object[] mydatum = (Object[]) mydata[0];
                if (mydatum != null && mydatum.length > 0) {
                    JSONObject rank = new JSONObject();
                    rank.put("memNickname", mydatum[0]);
                    rank.put("memHeadimg", mydatum[1]);
                    rank.put("count", mydatum[2]);
                    rstData.put("myRank", rank);
                    log.info("myRank===========================" + rank.toString());
                }
            } else {
                rstData.put("myRank", 0);
            }

        }
        return rstData;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public Result addFreeBuyApi(String memCard, Integer orderType, Integer objId, Integer paySource,
                                String fromMemCard, String ip, Integer objCount, String orderId) {
        //添加订单
        Result result = addOrder(memCard, orderType, objId, 1, 3, paySource,
                1, fromMemCard, ip, objCount, orderId);
        SalesOrdersMain ordersMain;
        if (result.getCode() == 200) {
            ordersMain = (SalesOrdersMain) result.getData();
        } else {
            return result;
        }
        //添加购买记录
        QkjPurchasedRecords records = savePurchased(ordersMain, 36500);

        //增加任务积分
        addTask(memCard, orderType, objId);
        return Result.success("添加免费订单成功");
    }

    @Override
    public Result getObjInfo(String memCard, Integer objType, Long objId, Integer objCount) {
        Map<String, Object> dataInfo = new HashMap<String, Object>();
        if (objType == 1) {
            //精品课
            QkjTqcourse tqcourse = tqcourseDao.findById(objId).get();
            dataInfo.put("objTitle", tqcourse.getTitle());
            dataInfo.put("objCoverImg", commonService.buildImgUrl(tqcourse.getCoverImg()));
            dataInfo.put("objPrice", tqcourse.getPrice());
            dataInfo.put("objPointFlag", tqcourse.getPointFlag());
            dataInfo.put("objPoint", tqcourse.getPoint());
            dataInfo.put("objCount", objCount);
        } else if (objType == 2) {
            //直播
            QkjLive live = liveDao.findById(objId).get();
            dataInfo.put("objTitle", live.getLiveTitle());
            dataInfo.put("objCoverImg", commonService.buildImgUrl(live.getLiveCoverImg()));
            dataInfo.put("objPrice", live.getPrice());
            dataInfo.put("objPointFlag", live.getPointFlag());
            dataInfo.put("objPoint", live.getPoint());
            dataInfo.put("objCount", objCount);
        } else if (objType == 3) {
            //会议
            QkjConference conference = conferenceDao.findById(objId).get();
            dataInfo.put("objTitle", conference.getTitle());
            dataInfo.put("objCoverImg", commonService.buildImgUrl(conference.getCoverImg()));
            dataInfo.put("objPrice", conference.getPrice());
            dataInfo.put("objPointFlag", conference.getPointFlag());
            dataInfo.put("objPoint", conference.getPoint());
            dataInfo.put("objCount", objCount);

        } else if (objType == 4) {
            //课件
            QkjCourseWare courseWare = courseWareDao.findById(objId).get();
            dataInfo.put("objTitle", courseWare.getTitle());
//            if (courseWare.getFileType() == 1) {
//                dataInfo.put("objCoverImg", "http://files.qkyxzx.com/html5/ppt.png");
//            } else if (courseWare.getFileType() == 2) {
//                dataInfo.put("objCoverImg", "http://files.qkyxzx.com/html5/word.png");
//            } else if (courseWare.getFileType() == 3) {
//                dataInfo.put("objCoverImg", "http://files.qkyxzx.com/html5/pdf.png");
//            } else if (courseWare.getFileType() == 4) {
//                dataInfo.put("objCoverImg", "http://files.qkyxzx.com/html5/excel.png");
//            }
            dataInfo.put("objCoverImg",courseWare.getCoverImg());
            dataInfo.put("objPrice", courseWare.getPrice());
            dataInfo.put("objPointFlag", courseWare.getPointFlag());
            dataInfo.put("objPoint", courseWare.getPoint());
            dataInfo.put("objCount", objCount);
        }
        if (memCard != null && !"".equals(memCard)) {
            QkjMemberTaskInfo taskInfo = taskInfoDao.findByMemCard(memCard);
            if (taskInfo != null) {
                dataInfo.put("memResidualPoints", taskInfo.getMemResidualPoints());
            } else {
                dataInfo.put("memResidualPoints", 0);
            }
        }
        return Result.success(dataInfo);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public Result pointPay(String memCard, Integer objType, Integer objId, Integer paySource, String fromMemCard,
                           String ip, Integer objCount, String orderId) {
        //添加订单
        Result result = addOrder(memCard, objType, objId, 1, 2, paySource, 1, fromMemCard, ip, objCount, orderId);
        SalesOrdersMain ordersMain;
        if (result.getCode() == 200) {
            ordersMain = (SalesOrdersMain) result.getData();
        } else {
            return result;
        }
        //添加购买记录
        QkjPurchasedRecords records = savePurchased(ordersMain, 36500);

        //添加积分兑换记录
        QkjMemberTaskDetail taskDetail = new QkjMemberTaskDetail();
        taskDetail.setMemCard(memCard);
        taskDetail.setPoints(ordersMain.getPoint());
        taskDetail.setType(1);
        taskDetail.setChangeType(0);
        taskDetail.setCompleteTime(Calendar.getInstance());
        taskDetailDao.save(taskDetail);

        //扣除积分
        QkjMemberTaskInfo taskInfo = taskInfoDao.findByMemCard(ordersMain.getMemCard());
        taskInfo.setMemResidualPoints(taskInfo.getMemResidualPoints() - ordersMain.getPoint());
        taskInfoDao.save(taskInfo);

        return Result.success("积分购买商品成功");
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public Result createOrder(String memCard, Integer objType, Integer objId, Integer paySource, String fromMemCard,
                              String ip, Integer objCount, String orderId) {
        //添加订单
        Result result = addOrder(memCard, objType, objId, 1, 1, paySource, 0, fromMemCard, ip, objCount, orderId);
        SalesOrdersMain ordersMain;
        if (result.getCode() == 200) {
            ordersMain = (SalesOrdersMain) result.getData();
            return Result.success(ordersMain.getOrderId());
        } else {
            return result;
        }
    }

    @Override
    public Result addTask(String memCard, Integer orderType, Integer objId) {
        //增加任务积分
        if (orderType == 1) {
            //课程
            taskService.dailyCheckIn(memCard, 28, 0);
        } else if (orderType == 2) {
            //直播
            taskService.dailyCheckIn(memCard, 26, 0);
        } else if (orderType == 3) {
            //会议
            //查询是否是第一次报名此会议
            List<QkjConferenceRecord> records = conferenceRecordDao.findByConferIdAndMemCard(objId.longValue(), memCard, 1);
            if (records == null || records.size() == 1) {
                taskService.dailyCheckIn(memCard, 20, 0);
            }
        } else if (orderType == 4) {
            //课件
            taskService.dailyCheckIn(memCard, 23, 0);
        }

        return Result.success("添加成功");
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public QkjPurchasedRecords savePurchased(SalesOrdersMain ordersMain, Integer endDay) {
        QkjPurchasedRecords mpr = new QkjPurchasedRecords();
        mpr.setMemCard(ordersMain.getMemCard());
        mpr.setObjType(ordersMain.getOrderType());
        mpr.setObjId(Long.parseLong(ordersMain.getObjId()));
        mpr.setOrderId(ordersMain.getOrderId());
        mpr.setOprTime(Calendar.getInstance());
        Calendar nowCal = Calendar.getInstance();
        nowCal.add(Calendar.DAY_OF_YEAR, endDay);
        mpr.setEndTime(nowCal);
        mpr.setStatus(0);
        mpr.setPayType(ordersMain.getPayType().intValue());
        if (ordersMain.getSalesId() != null) {
            mpr.setSalesId(ordersMain.getSalesId().longValue());
        }
        mpr.setIspackage(1);
        mpr.setPaySource(ordersMain.getPaySource());
        mpr = purchasedRecordsDao.save(mpr);

        //增加购买数量
        if (ordersMain.getOrderType() == 1) {
            //精品课
            QkjTqcourse tqcourse = tqcourseDao.findById(Long.parseLong(ordersMain.getObjId())).get();
            if (tqcourse != null) {
                //增加虚拟人数
//                tqcourse.setPurchasedMembers(tqcourse.getPurchasedMembers() == null ? 0 : tqcourse.getPurchasedMembers() + 2);
                //增加虚拟购买人数
                tqcourse.setVpurchasedMembers(tqcourse.getVpurchasedMembers() + 1);
                tqcourseDao.save(tqcourse);
            }
        } else if (ordersMain.getOrderType() == 2) {
            //直播
            QkjLive live = liveDao.findById(Long.parseLong(ordersMain.getObjId())).get();
            if (live != null) {
                //增加虚拟人数
//                live.setPurchasedMembers(live.getPurchasedMembers() + 2);
                //增加虚拟购买人数
                live.setVpurchasedMembers(live.getVpurchasedMembers() + 1);
                liveDao.save(live);
            }
        } else if (ordersMain.getOrderType() == 3) {
            //会议
            QkjConference conference = conferenceDao.findById(Long.parseLong(ordersMain.getObjId())).get();
            if (conference != null) {
                conference.setPeopleCount(conference.getPeopleCount() + 2 * ordersMain.getObjCount());
                conference.setVpeopleCount(conference.getVpeopleCount() + ordersMain.getObjCount());
                conferenceDao.save(conference);

                //更改会议参会记录支付状态
                List<QkjConferenceRecord> conferenceRecords = conferenceRecordDao.findByConferIdAndMemCardAndOrderId(Long.parseLong(ordersMain.getObjId()), ordersMain.getMemCard(), ordersMain.getOrderId());
                for (QkjConferenceRecord record : conferenceRecords) {
                    record.setPayStatus(1);
                    conferenceRecordDao.save(record);
                }
            }
        } else if (ordersMain.getOrderType() == 4) {
            //课件
            QkjCourseWare courseWare = courseWareDao.findById(Long.parseLong(ordersMain.getObjId())).get();
            if (courseWare != null) {
                courseWare.setDownloadMembers(courseWare.getDownloadMembers() + 2);
                courseWare.setVdownloadMembers(courseWare.getVdownloadMembers() + 1);
                courseWareDao.save(courseWare);
            }
        }

        return mpr;
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    protected Result addOrder(String memCard, Integer orderType, Integer objId, Integer ispackage, Integer payType,
                              Integer paySource, Integer status, String fromMemCard, String ip, Integer objCount, String orderId) {
        List<String> order = orderDao.getOrderByMemCardAndObjIdAndOrderType(memCard, objId.toString(), orderType);
        if(order != null && !order.isEmpty()){
            return Result.failed(BizCodeEnum.REPEAT_PURCHASE);
        }
        SalesOrdersMain salesOrders = new SalesOrdersMain();
        salesOrders.setMemCard(memCard);
        salesOrders.setProductId(Calendar.getInstance().getTimeInMillis() + "");
        if (StringUtils.isNotBlank(orderId)) {
            salesOrders.setOrderId(orderId);
        } else {
            salesOrders.setOrderId(OrderUtil.getInstance().GenerateOrder());
        }
        salesOrders.setOrderType(orderType);
        salesOrders.setObjId(objId.toString());
        salesOrders.setObjCount(objCount);
        salesOrders.setIspackage(ispackage);
        salesOrders.setPaySource(paySource);
        salesOrders.setPayType(payType);
        salesOrders.setPayIp(ip);
        Result result = inserOrderInfoByObj(salesOrders);
        if (result.getCode() == 200) {
            salesOrders = (SalesOrdersMain) result.getData();
        } else {
            return result;
        }
        salesOrders.setCreatetime(Calendar.getInstance());
        salesOrders.setStatus(status);
        if (status == 1) {
            salesOrders.setPayTime(Calendar.getInstance());
        }
        salesOrders.setFromMemCard(fromMemCard);
        salesOrders = orderDao.save(salesOrders);
        return Result.success(salesOrders);
    }

    private Result inserOrderInfoByObj(SalesOrdersMain salesOrders) {
        QkjMember user = userDao.findUserByMemCard(salesOrders.getMemCard());

        if (salesOrders.getOrderType() == 1) {
            //精品课
            QkjTqcourse tqcourse = tqcourseDao.findById(Long.parseLong(salesOrders.getObjId())).get();
            salesOrders.setOrderName(tqcourse.getTitle());
            salesOrders.setOrderDesc(tqcourse.getTitle());
            if (salesOrders.getPayType() == 1) {
                salesOrders.setOrderSizes(tqcourse.getPrice() * salesOrders.getObjCount());
                salesOrders.setPoint(0);
            } else if (salesOrders.getPayType() == 2) {
                QkjMemberTaskInfo taskInfo = taskInfoDao.findByMemCard(salesOrders.getMemCard());
                if (tqcourse.getPointFlag() == 0) {
                    return Result.failed("此课程不支持积分购买！");
                } else if (taskInfo.getMemResidualPoints() < tqcourse.getPoint() * salesOrders.getObjCount()) {
                    return Result.failed("积分不足！");
                }
                salesOrders.setOrderSizes(0d);
                salesOrders.setPoint(tqcourse.getPoint() * salesOrders.getObjCount());
            } else if (salesOrders.getPayType() == 3) {
                if (tqcourse.getPrice() > 0 && (tqcourse.getPointFlag() == 1 && tqcourse.getPoint() > 0) && user.getIsVip() != 1) {
                    return Result.failed("收费课程，不能免费领取！");
                } else {
                    salesOrders.setOrderSizes(0d);
                    salesOrders.setPoint(0);
                }
            }
        } else if (salesOrders.getOrderType() == 2) {
            //直播
            QkjLive live = liveDao.findById(Long.parseLong(salesOrders.getObjId())).get();
            salesOrders.setOrderName(live.getLiveTitle());
            salesOrders.setOrderDesc(live.getLiveTitle());
            if (salesOrders.getPayType() == 1) {
                salesOrders.setOrderSizes(live.getPrice() * salesOrders.getObjCount());
                salesOrders.setPoint(0);
            } else if (salesOrders.getPayType() == 2) {
                QkjMemberTaskInfo taskInfo = taskInfoDao.findByMemCard(salesOrders.getMemCard());
                if (live.getPointFlag() == 0) {
                    return Result.failed("此课程不支持积分购买！");
                } else if (taskInfo.getMemResidualPoints() < live.getPoint() * salesOrders.getObjCount()) {
                    return Result.failed("积分不足！");
                }
                salesOrders.setOrderSizes(0d);
                salesOrders.setPoint(live.getPoint() * salesOrders.getObjCount());
            } else if (salesOrders.getPayType() == 3) {
                if (live.getPrice() > 0 && (live.getPointFlag() == 1 && live.getPoint() > 0) && user.getIsVip() != 1) {
                    return Result.failed("收费课程，不能免费领取！");
                } else {
                    salesOrders.setOrderSizes(0d);
                    salesOrders.setPoint(0);
                }
            }
        } else if (salesOrders.getOrderType() == 3) {
            //会议
            QkjConference courseWare = conferenceDao.findById(Long.parseLong(salesOrders.getObjId())).get();
            salesOrders.setOrderName(courseWare.getTitle());
            salesOrders.setOrderDesc(courseWare.getTitle());
            if (salesOrders.getPayType() == 1) {
                salesOrders.setOrderSizes(courseWare.getPrice() * salesOrders.getObjCount());
                salesOrders.setPoint(0);
            } else if (salesOrders.getPayType() == 2) {
                QkjMemberTaskInfo taskInfo = taskInfoDao.findByMemCard(salesOrders.getMemCard());
                if (courseWare.getPointFlag() == 0) {
                    return Result.failed("此会议不支持积分购买！");
                } else if (taskInfo.getMemResidualPoints() < courseWare.getPoint() * salesOrders.getObjCount()) {
                    return Result.failed("积分不足！");
                }
                salesOrders.setOrderSizes(0d);
                salesOrders.setPoint(courseWare.getPoint() * salesOrders.getObjCount());
            } else if (salesOrders.getPayType() == 3) {
                if (courseWare.getPrice() > 0 && (courseWare.getPointFlag() == 1 && courseWare.getPoint() > 0) && user.getIsVip() != 1) {
                    return Result.failed("收费会议，不能免费领取！");
                } else {
                    salesOrders.setOrderSizes(0d);
                    salesOrders.setPoint(0);
                }
            }
        } else if (salesOrders.getOrderType() == 4) {
            //课件
            QkjCourseWare courseWare = courseWareDao.findById(Long.parseLong(salesOrders.getObjId())).get();

            salesOrders.setOrderName(courseWare.getTitle());
            salesOrders.setOrderDesc(courseWare.getTitle());
            if (salesOrders.getPayType() == 1) {
                salesOrders.setOrderSizes(courseWare.getPrice() * salesOrders.getObjCount());
                salesOrders.setPoint(0);
            } else if (salesOrders.getPayType() == 2) {
                QkjMemberTaskInfo taskInfo = taskInfoDao.findByMemCard(salesOrders.getMemCard());
                if (courseWare.getPointFlag() == 0) {
                    return Result.failed("此课件不支持积分购买！");
                } else if (taskInfo.getMemResidualPoints() < courseWare.getPoint() * salesOrders.getObjCount()) {
                    return Result.failed("积分不足！");
                }
                salesOrders.setOrderSizes(0d);
                salesOrders.setPoint(courseWare.getPoint() * salesOrders.getObjCount());
            } else if (salesOrders.getPayType() == 3) {
                if (courseWare.getPrice() > 0 && (courseWare.getPointFlag() == 1 && courseWare.getPoint() > 0) && user.getIsVip() != 1) {
                    return Result.failed("收费课件，不能免费领取！");
                } else {
                    salesOrders.setOrderSizes(0d);
                    salesOrders.setPoint(0);
                }
            }
        }
        return Result.success(salesOrders);
    }

}
