package com.upyuns.platform.rs.website.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.upyuns.platform.rs.datacenter.fegin.DatacenterFeign;
import com.upyuns.platform.rs.datacenter.pojo.ImageDataVO;
import com.upyuns.platform.rs.gtdata.GtDataRestClient;
import com.upyuns.platform.rs.website.biz.*;
import com.upyuns.platform.rs.website.dto.order.OldeliveryJson;
import com.upyuns.platform.rs.website.entity.ImageInfoRelation;
import com.upyuns.platform.rs.website.entity.IndustryApplicationInfo;
import com.upyuns.platform.rs.website.entity.OrderInfo;
import com.upyuns.platform.rs.website.entity.OrderItem;
import com.upyuns.platform.rs.website.type.ItemTypeEnum;
import com.upyuns.platform.rs.website.type.NoticeTypeEnum;
import com.upyuns.platform.rs.website.type.OrderStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

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

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
import static com.upyuns.platform.rs.website.entity.OrderInfo.SENDTYPE_OL;
import static com.upyuns.platform.rs.website.type.OrderStatusEnum.ORDER_PAID;
import static com.upyuns.platform.rs.website.type.OrderStatusEnum.ORDER_SEND;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Slf4j
public class WebsiteScheduleTask {

    @Autowired
    OrderInfoBiz orderInfoBiz;

    @Autowired
    OrderItemBiz orderItemBiz;

    @Autowired
    ImageInfoRelationBiz imageInfoRelationBiz;

    @Autowired
    IndustryApplicationInfoBiz industryApplicationInfoBiz;

    @Autowired
    NoticeInfoBiz noticeInfoBiz;

    @Autowired
    DatacenterFeign datacenterFeign;

    @Autowired
    GtDataRestClient gtDataRestClient;

    public static final int ITEM_STANDARD_DATA = ItemTypeEnum.STANDARD_DATA.getType();
    public static final int ITEM_INDUSTRY_INFO = ItemTypeEnum.INDUSTRY_INFO.getType();
    public static final int ITEM_IMAGE_STORAGE = ItemTypeEnum.IMAGE_STORAGE.getType();


    //3.添加定时任务
//    @Scheduled(cron = "0/30 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    //@Scheduled(fixedRate=5000)
    public void configureTasks() {
        //查询是否有线上并且代发货的订单
        //log.info("执行静态定时任务时间: " + LocalDateTime.now());
        List<OrderInfo> list = orderInfoBiz.selectByWeekend(w -> {
            w.andEqualTo(OrderInfo::getStatus, ORDER_SEND.getType());
            w.andEqualTo(OrderInfo::getSendType, SENDTYPE_OL);
            w.andEqualTo(OrderInfo::getDataPrepare, SYS_TRUE);
//            w.andEqualTo(OrderInfo::getUserId, 656);
            return w;
        });

        list.forEach(orderInfo -> {
            String innerOrderPath =  "/order/"+orderInfo.getOrderNo()+ "/";
            String orderPath = "/"+ orderInfo.getUserId()+ innerOrderPath;
            //创建订单文件夹
            gtDataRestClient.mkdirs("/"+ orderInfo.getUserId()+ "/order/"+orderInfo.getOrderNo());

            List<OldeliveryJson> jsons = CollUtil.newArrayList();
            List<OrderItem> items = orderItemBiz.selectList(new OrderItem(){{
                setOrderId(orderInfo.getOrderId());
            }});
            items.forEach(it -> {
                if(ITEM_STANDARD_DATA == it.getType()) {
                    List<ImageDataVO> imageDataVOS = datacenterFeign.queryByIds(it.getDetailId()+ "").getData();
                    imageDataVOS.forEach(vo -> {
                        //拷贝文件
                        Integer fileFlag = vo.getImageFilePath().lastIndexOf("/")+ 1;
                        String fileName = vo.getImageFilePath().substring(fileFlag);
                        gtDataRestClient.copy(vo.getImageFilePath(), orderPath+ fileName);
                        jsons.add(new OldeliveryJson(){{
                            setName(vo.getName());
                            setPath(innerOrderPath+ fileName);
                        }});
                    });
                }else if(ITEM_INDUSTRY_INFO == it.getType()) {
                    IndustryApplicationInfo iai = industryApplicationInfoBiz.selectById(it.getDetailId().intValue());
                    //拷贝文件
                    Integer fileFlag = iai.getSourceFile().lastIndexOf("/")+ 1;
                    String fileName = iai.getSourceFile().substring(fileFlag);
                    gtDataRestClient.copy(iai.getSourceFile(), orderPath+ fileName);

                    jsons.add(new OldeliveryJson(){{
                        setName(it.getName());
                        setPath(innerOrderPath+ fileName);
                    }});
                }else if(ITEM_IMAGE_STORAGE == it.getType()) {
                    ImageInfoRelation iir = imageInfoRelationBiz.selectById(it.getDetailId().intValue());
                    //拷贝文件
                    Integer fileFlag = iir.getUrl().lastIndexOf("/")+ 1;
                    String fileName = iir.getUrl().substring(fileFlag);
                    gtDataRestClient.copy(iir.getUrl(), orderPath+ fileName);

                    jsons.add(new OldeliveryJson(){{
                        setName(it.getName());
                        setPath(innerOrderPath+ fileName);
                    }});
                }
            });
            orderInfoBiz.updateSelectiveById(new OrderInfo(){{
                setOrderId(orderInfo.getOrderId());
                setStatus(OrderStatusEnum.ORDER_RECEIVED.getType());
                setOldeliveryJson(JSONUtil.toJsonStr(jsons));
            }});

            //添加通知信息
            noticeInfoBiz.addObj("订单" + orderInfo.getOrderNo() + "已交付，请查看下载", NoticeTypeEnum.ORDER_INFO.getType(), orderInfo.getUserId(), String.valueOf(orderInfo.getOrderId()));
        });
    }
}