package com.ruixuan.live.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.utils.Check;
import com.ruixuan.data.service.IKuaishouLiveDataAnalysisService;
import com.ruixuan.data.service.IKuaishouLiveDataFunnelService;
import com.ruixuan.data.service.IKuaishouLiveDataKanbanService;
import com.ruixuan.data.service.IKuaishouLiveDataOverviewService;
import com.ruixuan.data.utils.LiveDataExcelUtils;
import com.ruixuan.live.entity.KuaishouLiveBroadcast;
import com.ruixuan.live.entity.KuaishouLiveBroadcastFiles;
import com.ruixuan.live.mapper.KuaishouLiveBroadcastFilesMapper;
import com.ruixuan.live.mapper.KuaishouLiveBroadcastMapper;
import com.ruixuan.live.service.IKuaishouLiveBroadcastService;
import com.ruixuan.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

/**
 * 快手—直播Service业务层处理
 *
 * @author ruoyi
 * @date 2022-05-31
 */
@Service
public class KuaishouLiveBroadcastServiceImpl implements IKuaishouLiveBroadcastService {
    @Autowired
    private KuaishouLiveBroadcastMapper kuaishouLiveBroadcastMapper;

    @Autowired
    private KuaishouLiveBroadcastFilesMapper filesMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IKuaishouLiveDataAnalysisService analysisService;
    @Autowired
    private IKuaishouLiveDataFunnelService funnelService;
    @Autowired
    private IKuaishouLiveDataKanbanService kanbanService;
    @Autowired
    private IKuaishouLiveDataOverviewService overviewService;

    /**
     * 查询快手—直播
     *
     * @param id 快手—直播主键
     * @return 快手—直播
     */
    @Override
    public ResultResponse selectKuaishouLiveBroadcastById(String id) {
        KuaishouLiveBroadcast liveBroadcast = kuaishouLiveBroadcastMapper.selectKuaishouLiveBroadcastById(id);
        return ResultResponse.success(liveBroadcast);
    }

    @Override
    public ResultResponse getForEdit(String id) {
        KuaishouLiveBroadcast liveBroadcast = kuaishouLiveBroadcastMapper.selectKuaishouLiveBroadcastById(id);
        JSONObject object = JSONObject.parseObject(JSON.toJSONString(liveBroadcast));
        object.put("traderArray", getUsers(liveBroadcast.getTraderId()));
        object.put("centralControlArray", getUsers(liveBroadcast.getCentralControlId()));
        object.put("fieldControlArray", getUsers(liveBroadcast.getFieldControlId()));
        object.put("contentControlArray", getUsers(liveBroadcast.getContentControlId()));
        object.put("inputControlArray", getUsers(liveBroadcast.getInputControlId()));
        object.put("anchorArray", getUsers(liveBroadcast.getAnchorId()));
        return ResultResponse.success(object);
    }

    private List<JSONObject> getUsers(String ids) {
        if (ids != null && ids != "-") {
            ids = ids.replace("，", ",");
            List<String> userIds = Arrays.asList(ids.split(","));
            return sysUserService.queryUserByIds(userIds);
        }
        return null;
    }

    /**
     * 查询快手—直播列表
     *
     * @param kuaishouLiveBroadcast 快手—直播
     * @return 快手—直播
     */
    @Override
    public List<KuaishouLiveBroadcast> selectKuaishouLiveBroadcastList(KuaishouLiveBroadcast kuaishouLiveBroadcast) {
        return kuaishouLiveBroadcastMapper.selectKuaishouLiveBroadcastList(kuaishouLiveBroadcast);
    }

    /**
     * 新增快手—直播
     *
     * @param kuaishouLiveBroadcast 快手—直播
     * @return 结果
     */
    @Override
    public ResultResponse insertKuaishouLiveBroadcast(KuaishouLiveBroadcast broadcast) {
        KuaishouLiveBroadcast one = kuaishouLiveBroadcastMapper.getOne(broadcast);
        if (one != null) {
            return ResultResponse.error("当前时间段已存在直播！");
        }
        broadcast.setId(UUID.randomUUID().toString().replace("-", ""));
        int num = kuaishouLiveBroadcastMapper.insertKuaishouLiveBroadcast(broadcast);
        if (num > 0) {
            return ResultResponse.success();
        }
        return ResultResponse.error("fail");
    }

    /**
     * 修改快手—直播
     *
     * @param kuaishouLiveBroadcast 快手—直播
     * @return 结果
     */
    @Override
    public ResultResponse updateKuaishouLiveBroadcast(KuaishouLiveBroadcast broadcast) {
        KuaishouLiveBroadcast one = kuaishouLiveBroadcastMapper.selectKuaishouLiveBroadcastById(broadcast.getId());
        if (one == null) {
            return ResultResponse.error("未查询到直播！");
        }
        KuaishouLiveBroadcast checkOne = kuaishouLiveBroadcastMapper.getOne(broadcast);
        if (checkOne == null) {
            KuaishouLiveBroadcast copy = new KuaishouLiveBroadcast();
            BeanUtils.copyProperties(broadcast, copy);
            copy.setId(null);
            if (kuaishouLiveBroadcastMapper.getOne(copy) != null) {
                return ResultResponse.error("当前时间段已存在直播！");
            }
        }
        int i = kuaishouLiveBroadcastMapper.updateKuaishouLiveBroadcast(broadcast);
        if (i > 0) {
            return ResultResponse.success();
        }
        return ResultResponse.error("fail");
    }

    /**
     * 批量删除快手—直播
     *
     * @param ids 需要删除的快手—直播主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouLiveBroadcastByIds(String[] ids) {
        return kuaishouLiveBroadcastMapper.deleteKuaishouLiveBroadcastByIds(ids);
    }

    /**
     * 删除快手—直播信息
     *
     * @param id 快手—直播主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouLiveBroadcastById(String id) {
        return kuaishouLiveBroadcastMapper.deleteKuaishouLiveBroadcastById(id);
    }

    @Override
    public ResultResponse dataUpload(String id, String actualGmv, String dapanUrls, String portraitUrls, MultipartFile[] files) throws Exception {
        KuaishouLiveBroadcast broadcast = kuaishouLiveBroadcastMapper.selectKuaishouLiveBroadcastById(id);
        if (broadcast == null) {
            return ResultResponse.error("未查询到直播！");
        }

        // 目前支持 直播数据看板、直播数据概览、直播漏斗数据、商品分析数据 四种数据导入
        String msg = "";
        //记录上传文件
        int count = 0;
        try {
            if (!(Check.isNull(files) || "".equals(files[0].getOriginalFilename()))) {
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename();
                    if (!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx") || fileName.endsWith(".csv"))) {
                        msg += fileName + "、";
                        continue;
                    }

                    List<JSONObject> list = LiveDataExcelUtils.analysisFile(file, fileName);
                    if (Check.isNotNull(list)) {
                        if (fileName.contains("看板")) {
                            count += kanbanService.inserExcelInfo(broadcast, list);
                        } else if (fileName.contains("概览")) {
                            count += overviewService.inserExcelInfo(broadcast, list);
                        } else if (fileName.contains("漏斗")) {
                            count += funnelService.inserExcelInfo(broadcast, list);
                        } else if (fileName.contains("分析")) {
                            count += analysisService.inserExcelInfo(broadcast, list);
                        }
                    }
                }
            }
        } catch (Exception e) {
            return ResultResponse.error(e.getMessage());
        }
        //上传到cos的文件夹名称 （操盘手）
        String upFileName = "CaoPanShou";
        KuaishouLiveBroadcastFiles file = null;
        //上传数据大盘
        if (Check.isNotNull(dapanUrls) && !"[]".equals(dapanUrls)) {
            file = new KuaishouLiveBroadcastFiles();
            file.setId(id);
            List<String> urls = JSONArray.parseArray(dapanUrls, String.class);
            HashSet<String> set = new HashSet<>(urls);
            String urlFix = "";
            String names = "";
            int dapanCount = set.size();
            for (String url : set) {
//                String pictureName = "dapan_000" + (dapanCount + 1);
//                String cosUrl = CosUpload.getJPGCosUrl(url, upFileName, pictureName);
                if (Check.isNotNull(url)) {
                    int lastNo = url.lastIndexOf("/") + 1;
                    urlFix = "https:" + url.substring(0, lastNo);
                    String name = url.substring(lastNo);
                    names += "," + name;
                }
            }
            file.setUpCommonUrl(urlFix);
            file.setDapanCount(dapanCount);
            file.setDapanNames(names.substring(1));
            file.setDapanMsg("success");
        }

        //画像分析上传
        if (Check.isNotNull(portraitUrls) && !"[]".equals(portraitUrls)) {
            if (Check.isNull(file)) {
                file = new KuaishouLiveBroadcastFiles();
            }
            file.setId(id);
            List<String> urls = JSONArray.parseArray(portraitUrls, String.class);
            HashSet<String> set = new HashSet<>(urls);
            String urlFix = "";
            String names = "";
            int portraitCount = set.size();
            for (String url : set) {
//                String pictureName = "portrait_000" + (portraitCount + 1);
//                String cosUrl = CosUpload.getJPGCosUrl(url, upFileName, pictureName);
                if (Check.isNotNull(url)) {
                    int lastNo = url.lastIndexOf("/") + 1;
                    urlFix = "https:" + url.substring(0, lastNo);
                    String name = url.substring(lastNo);
                    names += "," + name;
                }
            }
            file.setUpCommonUrl(urlFix);
            file.setPortraitCount(portraitCount);
            file.setPortraitNames(names.substring(1));
            file.setPortraitMsg("success");
        }
        KuaishouLiveBroadcastFiles one = filesMapper.selectKuaishouLiveBroadcastFilesById(id);
        int uploadPictureCount = 0;
        if (Check.isNotNull(file)) {
            if (Check.isNull(one)) {
                filesMapper.insertKuaishouLiveBroadcastFiles(file);
            } else {
                filesMapper.updateKuaishouLiveBroadcastFiles(file);
            }
            Integer dapanCount = Check.isNotNull(file.getDapanCount()) ? file.getDapanCount() : 0;
            Integer portraitCount = Check.isNotNull(file.getPortraitCount()) ? file.getPortraitCount() : 0;
            uploadPictureCount = dapanCount + portraitCount;
        }

        //更新直播表
        KuaishouLiveBroadcast updateEntity = new KuaishouLiveBroadcast();
        updateEntity.setId(id);
        updateEntity.setUploadFileCount(count);
        updateEntity.setUploadPictureCount(uploadPictureCount);
        updateEntity.setActualGmv(actualGmv);
        kuaishouLiveBroadcastMapper.updateKuaishouLiveBroadcast(updateEntity);

        if (msg.length() > 0) {
            msg = msg.substring(0, msg.length() - 1) + "不支持文件格式";
        } else {
            msg = "上传完成";
        }
        return ResultResponse.successMsg(msg, null);

    }

    @Override
    public ResultResponse replay(String id, String replayPictureUrls, String replayFile) {
        //上传到cos的文件夹名称 （操盘手）
        String upFileName = "CaoPanShou";
        KuaishouLiveBroadcastFiles file = new KuaishouLiveBroadcastFiles();
        //上传复盘图片
        if (Check.isNotNull(replayPictureUrls) && !"[]".equals(replayPictureUrls)) {
            List<String> urls = JSONArray.parseArray(replayPictureUrls, String.class);
            HashSet<String> set = new HashSet<>(urls);
            String urlFix = "";
            String names = "";
            int replayPictureCount = set.size();
            for (String url : set) {
//                String pictureName = "replayPicture_000" + (replayPictureCount + 1);
//                String cosUrl = CosUpload.getJPGCosUrl(url, upFileName, pictureName);
                if (Check.isNotNull(url)) {
                    int lastNo = url.lastIndexOf("/") + 1;
                    urlFix = "https:" + url.substring(0, lastNo);
                    String name = url.substring(lastNo);
                    names += "," + name;
                }
            }
            file.setReplayCommonUrl(urlFix);
            file.setReplayPictureCount(replayPictureCount);
            file.setReplayPictureNames(names.substring(1));
            file.setReplayPictureMsg("success");
        }
        if (Check.isNotNull(replayFile)) {
            file.setReplayFileUrl(replayFile);
        }
        KuaishouLiveBroadcastFiles one = filesMapper.selectKuaishouLiveBroadcastFilesById(id);
        file.setId(id);
        if (Check.isNull(one)) {
            filesMapper.insertKuaishouLiveBroadcastFiles(file);
        } else {
            filesMapper.updateKuaishouLiveBroadcastFiles(file);
        }
        return ResultResponse.success();
    }

}
