package com.hwrj.cloud.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.hwrj.cloud.admin.dao.OmsOrderDao;
import com.hwrj.cloud.admin.dao.OmsOrderOperateHistoryDao;
import com.hwrj.cloud.admin.dao.excel.enumbo.*;
import com.hwrj.cloud.admin.dao.excel.model.OmsOrderExcel;
import com.hwrj.cloud.admin.dto.*;
import com.hwrj.cloud.admin.mapper.OmsOrderItemMapper;
import com.hwrj.cloud.admin.mapper.OmsOrderMapper;
import com.hwrj.cloud.admin.mapper.OmsOrderOperateHistoryMapper;
import com.hwrj.cloud.admin.mapper.PmsProductMapper;
import com.hwrj.cloud.admin.model.*;
import com.hwrj.cloud.admin.service.OmsOrderService;
import com.hwrj.cloud.admin.util.CurrUserUtil;
import com.hwrj.cloud.common.exception.GlobalException;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理Service实现类
 * Created by macro on 2018/10/11.
 */
@Service
public class OmsOrderServiceImpl implements OmsOrderService {
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private OmsOrderDao orderDao;
    @Autowired
    private OmsOrderOperateHistoryDao orderOperateHistoryDao;
    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;

    @Override
    public List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        Long compId = CurrUserUtil.getCompIdInfo();
        if(!StringUtils.isEmpty(compId)){
            queryParam.setCompId(compId);
        }
        PageHelper.startPage(pageNum, pageSize);
        return orderDao.getList(queryParam);
    }

    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = orderDao.delivery(deliveryParamList);
        //添加操作记录
        List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream()
                .map(omsOrderDeliveryParam -> {
                    OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                    history.setOrderId(omsOrderDeliveryParam.getOrderId());
                    history.setCreateTime(new Date());
                    history.setOperateMan("后台管理员");
                    history.setOrderStatus(2);
                    history.setNote("完成发货");
                    return history;
                }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(operateHistoryList);
        return count;
    }
    @Autowired
    private PmsProductMapper pmsProductMapper;


    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;


    @Override
    @Transactional
    public int close(List<Long> ids, String note) {
        //释放商品
        releaseProduct(ids);
        int count = closeOrder(ids, note);
        return count;
    }

    private void releaseProduct(List<Long> ids) {
        OmsOrderItemExample example=new OmsOrderItemExample();
        example.createCriteria().andOrderIdIn(ids);
        List<OmsOrderItem> omsOrderItems = omsOrderItemMapper.selectByExample(example);
        List<Long> productId = omsOrderItems.stream().map(OmsOrderItem::getProductId).collect(Collectors.toList());
        PmsProduct record =new PmsProductParam();
        record.setLockDel(0);
        PmsProductExample pmsProductExample = new PmsProductExample();
        pmsProductExample.createCriteria().andIdIn(productId);
        pmsProductMapper.updateByExampleSelective(record,pmsProductExample);
    }

    private int closeOrder(List<Long> ids, String note) {
        OmsOrder record = new OmsOrder();
        record.setStatus(4);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids);
        int count = orderMapper.updateByExampleSelective(record, example);
        List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(new Date());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(4);
            history.setNote("订单关闭:" + note);
            return history;
        }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(historyList);
        return count;
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrder record = new OmsOrder();
        record.setDeleteStatus(1);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids);
        return orderMapper.updateByExampleSelective(record, example);
    }

    @Override
    public OmsOrderDetail detail(Long id) {
        return orderDao.getDetail(id);
    }

    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(receiverInfoParam.getOrderId());
        order.setReceiverName(receiverInfoParam.getReceiverName());
        order.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        order.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        order.setReceiverCity(receiverInfoParam.getReceiverCity());
        order.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(receiverInfoParam.getStatus());
        history.setNote("修改收货人信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(moneyInfoParam.getOrderId());
        order.setFreightAmount(moneyInfoParam.getFreightAmount());
        order.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateNote(Long id, String note, Integer status) {
        OmsOrder order = new OmsOrder();
        order.setId(id);
        order.setNote(note);
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(id);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(status);
        history.setNote("修改备注信息：" + note);
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public List<OmsOrderExcel> listExcel(OmsOrderQueryParam queryParam) {

        Date endTime = queryParam.getEndTime();

        Date startTime = queryParam.getStartTime();
        if (!StringUtils.isEmpty(endTime) && !StringUtils.isEmpty(startTime)) {
            long end = endTime.getTime();
            long start = startTime.getTime();
            if (end - start < 0) {
                throw new GlobalException("开始时间不能大于结束时间!");
            } else if (end - start > 31536000000L) {
                throw new GlobalException("时间区间不能超过一年!");
            }
        } else {
            throw new GlobalException("数据量过大,请输入开始时间和结束时间!");
        }
        List<OmsOrder> list = orderDao.getList(queryParam);
        List<OmsOrderExcel> collect = list.stream().map(x -> {
            OmsOrderExcel omsOrderExcel = new OmsOrderExcel();
            BeanUtils.copyProperties(x, omsOrderExcel);
            //支付方式
            Integer payType = x.getPayType();
            String payTypeName = PayType.getEnumType(payType).getName();
            omsOrderExcel.setPayType(payTypeName);
            //订单来源
            Integer sourceType = x.getSourceType();
            String sourceeName = SourceType.getEnumType(sourceType).getName();
            omsOrderExcel.setSourceType(sourceeName);

            //设置订单状态
            Integer status = x.getStatus();
            String statusName = Status.getEnumType(status).getName();
            omsOrderExcel.setStatus(statusName);

            //订单类型
            Integer orderType = x.getOrderType();
            String orderTypeName = OrderType.getEnumType(orderType).getName();
            omsOrderExcel.setOrderType(orderTypeName);
            //确认收货状态
            Integer confirmStatus = x.getConfirmStatus();
            String confirmStatusName = ConfirmStatus.getEnumType(confirmStatus).getName();
            omsOrderExcel.setConfirmStatus(confirmStatus);
            return omsOrderExcel;
        }).collect(Collectors.toList());
        return collect;
    }
}
