package cn.com.ctop.kuaishou.modules.material.service.impl;

import cn.com.ctop.common.module.entity.MaterialInfo;
import cn.com.ctop.common.module.service.IMaterialInfoService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CosUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.common.module.vo.ResFileDTO;
import cn.com.ctop.kuaishou.modules.material.entity.ProductMaterial;
import cn.com.ctop.kuaishou.modules.material.mapper.ProductMaterialMapper;
import cn.com.ctop.kuaishou.modules.material.service.IProductMaterialService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.MD5Util;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 选品库——产品与商品信息
 *
 * @author jeecg-boot
 * 2022-04-19
 * @version V1.0
 */
@Service
public class ProductMaterialServiceImpl extends ServiceImpl<ProductMaterialMapper, ProductMaterial> implements IProductMaterialService {

    @Autowired
    private IMaterialInfoService materialInfoService;


    @Value("${zip.local.download-path}")
    private String downloadPath;

    static ExecutorService videoService = Executors.newFixedThreadPool(8);
    @Override
    public Result<Object> queryPageList(ProductMaterial productMaterial, Integer pageNo, Integer pageSize) {
        String startMonth = productMaterial.getStartMonth();
        String endMonth = productMaterial.getEndMonth();
        if (!Check.isNull(startMonth)) {
            productMaterial.setStartDate(startMonth.concat("-01"));
            if (!Check.isNull(endMonth)) {
                String[] sp = endMonth.split("-");
                String lastDayStr = "-" + DateUtils.getDaysOfMonth(Integer.valueOf(sp[0]), Integer.valueOf(sp[1]));
                productMaterial.setEndDate(endMonth.concat(lastDayStr));
            }
        }
        Long total = baseMapper.queryPageListTotal(productMaterial);
        PageHelper.startPage(pageNo, pageSize, false);
        List<JSONObject> list = baseMapper.queryPageList(productMaterial);
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setTotal(total);
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> videoList(ProductMaterial productMaterial, Integer pageNo, Integer pageSize) {
        String startMonth = productMaterial.getStartMonth();
        String endMonth = productMaterial.getEndMonth();
        if (!Check.isNull(startMonth)) {
            productMaterial.setStartDate(startMonth.concat("-01"));
            if (!Check.isNull(endMonth)) {
                String[] sp = endMonth.split("-");
                String lastDayStr = "-" + DateUtils.getDaysOfMonth(Integer.valueOf(sp[0]), Integer.valueOf(sp[1]));
                productMaterial.setEndDate(endMonth.concat(lastDayStr));
            }else{
                productMaterial.setEndDate(DateUtils.date2Str());
            }
        }
        Long total = baseMapper.videoListTotal(productMaterial);
        PageHelper.startPage(pageNo, pageSize, false);
        List<JSONObject> list = baseMapper.videoList(productMaterial);
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setTotal(total);
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> add(JSONObject data) throws IOException {
        String result = "添加完成";
        JSONArray list = data.getJSONArray("list");
        if (Check.isNull(list) || list.size() == 0) {
            return Result.error("缺少参数");
        }
        ProductMaterial entity = JSONObject.parseObject(data.toJSONString(), ProductMaterial.class);

        List<ProductMaterial> lists = new ArrayList<>();
        boolean flag = false;
        String msg = "";
        for (int i = 0; i < list.size(); i++) {
            JSONObject trade = list.getJSONObject(i);
            String tradeName = trade.getString("tradeName");
            String videoUrl = trade.getString("videoUrl");
            String signature = trade.getString("signature");
            String uploaderId = trade.getString("uploaderId");
            QueryWrapper<ProductMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_id", entity.getProductId());
            queryWrapper.eq("trade_name", tradeName).last("limit 1");
            ProductMaterial one1 = this.getOne(queryWrapper);
            if (!Check.isNull(one1)) {
                entity.setStartMonth(one1.getStartMonth());
                entity.setEndMonth(one1.getEndMonth());
                result = "";
            }
            int count = 0;
            queryWrapper.isNull("video_url");
            ProductMaterial one = this.getOne(queryWrapper);
            if (Check.isNull(one)) {
                entity.setTradeName(tradeName);
                lists.add(entity);
            }
            if (!Check.isNull(videoUrl)) {
                if (Check.isNull(signature) && Check.isNull(uploaderId)) {
                    List<String >urls = Arrays.asList(videoUrl.split(","));
                    HashSet<String> set = new HashSet<>(urls);
                    for (String url : set) {
                        count++;
                        //获取MD5
                        String localPath = LoadFileUtil.downLoadFromUrl(url, downloadPath);
                        String md5 = MD5Util.getMd5(localPath);
                        LoadFileUtil.delFile(localPath);
                        if (checkVideo(entity.getProductId(), tradeName, md5)) {
                            videoService.submit(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        ProductMaterial material = new ProductMaterial();
                                        BeanUtils.copyProperties(entity, material);
                                        material.setUploaderId(entity.getUserId());
                                        material.setTradeName(tradeName);
                                        material.setSignature(md5);
                                        String cosUrl = getCosUrl(url);
                                        material.setVideoUrl(cosUrl);
                                       baseMapper.insert(material);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                        } else {
                            flag = true;
                            if (msg.contains(tradeName)) {
                                msg += "第" + count + "条视频已存在，";
                            } else {
                                msg += "商品（" + tradeName + "）下的第" + count + "条视频已存在，";
                            }
                        }
                    }
                } else {
                    ProductMaterial material = new ProductMaterial();
                    BeanUtils.copyProperties(entity, material);
                    material.setTradeName(tradeName);
                    material.setVideoUrl(videoUrl);
                    material.setSignature(signature);
                    material.setUploaderId(entity.getUserId());
                    if (checkVideo(entity.getProductId(), tradeName, signature)) {
                        lists.add(material);
                    }
                }
            }
        }
        if (!Check.isNull(lists)) {
            baseMapper.replaceBatch(lists);
        }
        if (flag) {
            return Result.ok("添加完成，其中" + msg.substring(0, msg.length() - 1));
        }
        return Result.ok("添加完成");
    }

    @Override
    public List<JSONObject> getVideoDetailsReportList(ProductMaterial productMaterial) {
        String startMonth = productMaterial.getStartMonth();
        String endMonth = productMaterial.getEndMonth();
        if (!Check.isNull(startMonth)) {
            productMaterial.setStartDate(startMonth.concat("-01"));
            if (!Check.isNull(endMonth)) {
                String[] sp = endMonth.split("-");
                String lastDayStr = "-" + DateUtils.getDaysOfMonth(Integer.valueOf(sp[0]), Integer.valueOf(sp[1]));
                productMaterial.setEndDate(endMonth.concat(lastDayStr));
            }
        }
        List<JSONObject> list = baseMapper.getVideoDetailsReportList(productMaterial);
        return list;
    }

    @Override
    public Result<Object> materialList(Long productId, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize, false);
        List<MaterialInfo> list = materialInfoService.getListByProduct(productId);
        PageInfo pageInfo = new PageInfo(list);
        return Result.ok(pageInfo);
    }


    private boolean checkVideo(Long productId, String tradeName, String signature) {
        QueryWrapper<ProductMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("trade_name", tradeName);
        queryWrapper.eq("signature", signature).last("limit 1");
        ProductMaterial one = this.getOne(queryWrapper);
        if (Check.isNull(one)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 根据原始视频链接，下载到cos上
     */
    private String getCosUrl(String url) {
        try {
            if (!url.contains("http")) {
                url = KuaishouInterfaceConstant.HTTPS_PREFIX + url;
            }
            InputStream imageStream = LoadFileUtil.getFileStream(url);
            if (!Check.isNull(imageStream)) {
                String path = "XuanPinKu/" + DateUtils.formatDate(new Date(), DateUtils.SHORT_FORMAT) + "/";
                String videoName = UUID.randomUUID().toString().replace("-", "") + ".mp4";
                ResFileDTO file = CosUtils.uploadDetailInputStreamV2(imageStream, videoName, "mp4", 0L, path);
                return file.getFileUrl();
            }
        } catch (Exception e) {
            log.error("上传COS异常", e);
            return "上传COS失败";
        }
        return null;
    }


}
