package com.fs.task;

import com.fs.common.annotation.QuartzRunnable;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.service.FsJstAftersalePushService;
import com.fs.erp.service.FsJstCodPushService;
import com.fs.erp.service.IErpGoodsService;
import com.fs.erp.service.IErpOrderService;
import com.fs.erp.utils.ErpContextHolder;
import com.fs.live.domain.LiveAfterSales;
import com.fs.live.domain.LiveOrder;
import com.fs.live.service.*;
import com.fs.store.domain.FsExpress;
import com.fs.store.domain.FsStoreAfterSales;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.enums.OrderLogEnum;
import com.fs.store.mapper.*;
import com.fs.store.param.FsStoreAfterSalesAudit1Param;
import com.fs.store.param.LiveAfterSalesAudit1Param;
import com.fs.store.service.*;
import com.fs.system.service.ISysConfigService;
import com.fs.wx.mapper.FsWxExpressTaskMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.List;

/**
 * 定时任务调度
 * @author fs
 */
@Component("liveTask")
public class LiveTask {
    Logger logger = LoggerFactory.getLogger(LiveTask.class);


    @Autowired
    private ILiveOrderService liveOrderService;

    @Autowired
    private ILiveAfterSalesService afterSalesService;


    @Autowired
    private IErpOrderService erpOrderService;


    @Autowired
    private IFsExpressService expressService;


    @Autowired
    private ILiveOrderLogsService orderLogsService;


    @Autowired
    private FsWarehousesMapper fsWarehousesMapper;

    @Autowired
    public FsJstAftersalePushService fsJstAftersalePushService;

    /**
     * 超时订单自动取消
     */
    @QuartzRunnable(name = "超时订单自动取消")
    public void orderCancel(){
        liveOrderService.orderCancel();
    }


    /**
     * 发货任务
     */
    @QuartzRunnable(name = "发货任务")
    public void deliveryOp() {
        List<LiveOrder> list = liveOrderService.selectDeliverPenddingData();

        for (LiveOrder order : list) {
            String orderCode = order.getOrderCode();
            ErpOrderQueryRequert request = new ErpOrderQueryRequert();
            request.setCode(order.getExtendOrderId());

            try {
                // 根据仓库code找erp
                if (com.fs.common.utils.StringUtils.isNotBlank(order.getStoreHouseCode())) {
                    String erp = fsWarehousesMapper.selectErpByCode(order.getStoreHouseCode());
                    ErpContextHolder.setErpType(erp);
                }
                ErpOrderQueryResponse response = erpOrderService.getOrderLive(request);
                if (CollectionUtils.isNotEmpty(response.getOrders())) {
                    for (ErpOrderQuery orderQuery : response.getOrders()) {
                        if (CollectionUtils.isNotEmpty(orderQuery.getDeliverys())) {
                            // 部分发货或者全部发货
                            if (ObjectUtils.equals(orderQuery.getDelivery_state(), 1) || ObjectUtils.equals(orderQuery.getDelivery_state(), 2)) {

                                orderLogsService.create(order.getOrderId(), OrderLogEnum.DELIVERY_GOODS.getValue(),
                                        OrderLogEnum.DELIVERY_GOODS.getDesc());

                                for (ErpDeliverys delivery : orderQuery.getDeliverys()) {

                                    FsExpress express = expressService.selectFsExpressByOmsCode(delivery.getExpress_code());
                                    if (express == null) {
                                        logger.warn("当前express_code: {} 不存在!", delivery.getExpress_code());
                                        continue;
                                    }

                                    if (delivery.getDelivery()) {
                                        liveOrderService.deliveryOrder(orderCode, delivery.getMail_no(),
                                                delivery.getExpress_code(), delivery.getExpress_name());
                                    }
                                }

                                logger.info("订单 {} 发货信息同步成功", order.getOrderCode());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(String.format("[发货任务]调用erp查询接口失败！原因: %s", e));
            }

        }
    }


        /**
         * 退款自动处理 24小时未审核自动审核通过 每小时执行一次
         */
    @QuartzRunnable(name = "直播售后自动审核")
    public void refundOp() {
        //获取所有退款申请
        List<LiveAfterSales> list = afterSalesService.selectLiveAfterSalesByDoAudit();
        if (list != null) {
            for (LiveAfterSales afterSales : list) {
                //仅退款
//                if (afterSales.getServiceType().equals(0)) {
                LiveAfterSalesAudit1Param audit1Param = new LiveAfterSalesAudit1Param();
                audit1Param.setSalesId(afterSales.getId());
                audit1Param.setOperator("平台");
                afterSalesService.audit1(audit1Param);
//                }
            }
        }
    }

    /**
     * 批量推管易
     * @throws ParseException 解析异常
     */
    @QuartzRunnable(name = "批量推管易")
    public void updateOrderItem() throws ParseException {
        List<Long> ids = liveOrderService.selectOrderIdByNoErp();
        for (Long id : ids) {
            try{
                liveOrderService.createOmsOrder(id);
            }catch (Exception e){
                logger.error("推送管易失败 {}",id,e);
            }
        }
    }


    /**
     * 同步物流状态
     */
    @QuartzRunnable(name = "直播同步物流状态")
    public void syncExpress() {
        List<Long> ids = liveOrderService.selectSyncExpressIds();
        for (Long id : ids) {
            liveOrderService.syncExpress(id);
        }
    }

    /**
     * 更新发货状态
     */
    @QuartzRunnable(name = "直播发货任务")
    public void updateExpress() {
        List<LiveOrder> list = liveOrderService.selectUpdateExpress();

        for (LiveOrder order : list) {
            try{
                liveOrderService.syncDeliveryOrder(order);
            }catch (Exception e) {
                logger.error("获取订单是否发货失败！原因: ",e);
            }
        }

    }
}
