package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.constant.CtopRoleCodeConstant;
import cn.com.ctop.common.module.entity.ByteDanceCleanMaterialReport;
import cn.com.ctop.common.module.entity.MaterialAscription;
import cn.com.ctop.common.module.entity.MaterialCutFrame;
import cn.com.ctop.common.module.entity.MaterialImageInfo;
import cn.com.ctop.common.module.entity.MaterialInfo;
import cn.com.ctop.common.module.entity.MaterialParameter;
import cn.com.ctop.common.module.entity.MaterialTag;
import cn.com.ctop.common.module.entity.Product;
import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.entity.UserCompany;
import cn.com.ctop.common.module.enums.MaterialSupplierEnum;
import cn.com.ctop.common.module.service.IByteDanceCleanMaterialReportService;
import cn.com.ctop.common.module.service.IMaterialAscriptionService;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.service.IMaterialImageInfoService;
import cn.com.ctop.common.module.service.IMaterialInfoService;
import cn.com.ctop.common.module.service.IMaterialParameterService;
import cn.com.ctop.common.module.service.IMaterialTagService;
import cn.com.ctop.common.module.service.IMessageTemplate;
import cn.com.ctop.common.module.service.IProductService;
import cn.com.ctop.common.module.service.IProjectService;
import cn.com.ctop.common.module.service.ISendMessageService;
import cn.com.ctop.common.module.service.ISysUserService;
import cn.com.ctop.common.module.service.IUserCompanyService;
import cn.com.ctop.common.module.service.IVideoWatermarkTaskService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CloudVideoProcessUtil;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.JsonUtil;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.common.module.utils.StringUtils;
import cn.com.ctop.toutiao.modules.material.entity.ByteDanceCreativeWordPackage;
import cn.com.ctop.toutiao.modules.material.entity.BytedanceVideoSlogenInfo;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCreativeWordPackageService;
import cn.com.ctop.toutiao.modules.material.service.IBytedanceVideoSlogenInfoService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.service.IProjectMemberService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 素材信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-10-11
 */
@Slf4j
@Api(tags = "素材信息")
@RestController
@RequestMapping("/ctop/materialInfo")
public class MaterialInfoController {
    @Autowired
    private IMaterialInfoService materialInfoService;
    @Resource
    private IMaterialCutFrameService materialCutFrameService;
    @Autowired
    private IMaterialAscriptionService materialAscriptionService;
    @Autowired
    private IMaterialParameterService materialParameterService;
    @Autowired
    private IMaterialTagService materialTagService;
    @Autowired
    private IByteDanceCleanMaterialReportService byteDanceCleanMaterialReportService;
    @Autowired
    private IVideoWatermarkTaskService watermarkTaskService;
    @Autowired
    private IProjectMemberService memberService;
    @Autowired
    private IMaterialImageInfoService iMaterialImageInfoService;
    @Autowired
    private IMessageTemplate messageTemplate;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISendMessageService sendMessageService;
    @Autowired
    private IBytedanceVideoSlogenInfoService slogenInfoService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IProjectMemberService projectMemberService;
    @Resource
    IUserCompanyService userCompanyService;
    @Autowired
    private IByteDanceCreativeWordPackageService byteDanceGeneralCopywriterService;
    @Autowired
    private ISysUserService userService;


    /**
     * 素材同步
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "/materialSync")
    public Result<JSONObject> materialSync(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参为空");
            }
            Long projectId = requestJson.getLong("projectId");
            if (Check.isNull(projectId)) {
                throw new Exception("请传入被同步的项目ID");
            }
            JSONArray toProjectIds = requestJson.getJSONArray("toProjectIds");
            if (Check.isNull(toProjectIds)) {
                throw new Exception("请传入需同步的项目ID");
            }
            materialInfoService.materialSync(projectId, toProjectIds);
            result.setSuccess(true);


        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;
    }


    @GetMapping("/supplierWatermark")
    public Result<String> supplierWatermark(String id) {
        Result<String> result = new Result<>();
        try {
            if (Check.isNull(id)) {
                throw new Exception("请选择素材");
            }
            MaterialInfo materialInfo = materialInfoService.getById(id);
            if (Check.isNull(materialInfo)) {
                throw new Exception("素材信息为空");
            }
            QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
            parameterQueryWrapper.eq("material_id", materialInfo.getCode());
            parameterQueryWrapper.last("limit 1");
            MaterialParameter parameter = materialParameterService.getOne(parameterQueryWrapper);
            if (Check.isNull(parameter)) {
                throw new Exception("素材基本信息为空");
            }

            Long templateId = MaterialSupplierEnum.getTemplateIdBySize(Integer.valueOf(parameter.getWidth()), Integer.valueOf(parameter.getHeight()));
            String s = null;
            if (!Check.isNull(templateId)) {
                s = materialInfoService.watermarkVideoBySupplierCode(materialInfo.getCode(), materialInfo.getUrl(), templateId);
            }
            if (Check.isNull(s)) {
                result.setSuccess(false);
                result.setMessage("水印生成失败");
            } else {
                result.setSuccess(true);
                result.setResult(s);
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }

        return result;
    }

    /**
     * 修改名称
     *
     * @param data
     * @return
     */
    @PostMapping("/editName")
    public Map<String, Object> editName(@RequestBody JSONObject data) {
        Map<String, Object> result = new HashMap<>();
        String id = data.getString("id");
        String name = data.getString("name");
        if (null == id || "".equals(id.trim()) || null == name || "".equals(name.trim())) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        MaterialInfo info = materialInfoService.getById(id);
        if (null == info) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_DATA_NOT_EXIST);
            return result;
        }
        if (info.getStatus() == 1) {
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_DATA_NO_PERMMISSION);
            return result;
        }
        info.setMaterialName(name);
        materialInfoService.updateById(info);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @PostMapping("/correlationUpload")
    public Map<String, Object> insertFile(@RequestBody JSONObject json) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        json.put("userId", user.getId());
        return materialInfoService.correlationUpload(json);
    }

    @PostMapping("/supplementFrameUrl")
    public Result<Object> supplementFrameUrl(@RequestParam String videoMD5) {
        Result<Object> result = new Result<>();
        boolean bool = materialCutFrameService.updateTencentCutFrame(videoMD5);
        if (!bool) {
            result.setSuccess(false);
            result.error500("补全截帧url失败");
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    @GetMapping(value = "/report")
    public JSONObject report(String userId) {
        return materialInfoService.report(userId);
    }

    @GetMapping(value = "/getDetail")
    public JSONObject getDetail(String materialId) {
        return materialInfoService.getDetail(materialId);
    }

    @PostMapping("watermark")
    public Result<Object> watermarkVideo(@RequestParam(name = "id") String id, @RequestParam(name = "watermarkTemplateId") Long watermarkTemplateId, @RequestParam(name = "userId") String userId) {
        Result<Object> result = new Result<>();
        Thread thread = new Thread(() -> materialInfoService.watermarkVideo(id, watermarkTemplateId, userId));
        thread.start();
        result.setCode(200);
        result.setSuccess(true);
        result.setMessage("水印合成任务执行成功，请稍后查看");
        return result;
    }

    @GetMapping("excellent/set")
    public Result<Object> setExcellent(@RequestParam(name = "id") String code, @RequestParam(name = "excellent") Integer excellent) {
        Result<Object> result = new Result<>();
        materialInfoService.setExcellent(code, excellent);
        result.setCode(200);
        result.setSuccess(true);
        result.setMessage("设置成功");
        return result;
    }

    @GetMapping("/excellent/list")
    public Result<IPage<MaterialInfo>> excellentList(MaterialInfo materialInfo,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Result<IPage<MaterialInfo>> result = new Result<>();
        Object createTime = materialInfo.getCreateTime();
        materialInfo.setCreateTime(null);
        materialInfo.setExcellent(1);
        QueryWrapper<MaterialInfo> queryWrapper = QueryGenerator.initQueryWrapper(materialInfo, req.getParameterMap());
        if (!Check.isNull(createTime)) {
            try {
                String dateString = DateUtils.getDateString(String.valueOf(createTime));
                Map<String, Object> map = DateUtils.getStartEndTime(dateString);
                queryWrapper.ge("create_time", map.get("start"));
                queryWrapper.lt("create_time", map.get("end"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        Page<MaterialInfo> page = new Page<>(pageNo, pageSize);
        IPage<MaterialInfo> pageList = materialInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @Deprecated
    @GetMapping(value = "/list")
    public Result<IPage<MaterialInfo>> queryPageList(MaterialInfo materialInfo,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Result<IPage<MaterialInfo>> result = new Result<>();
        String materialName = materialInfo.getMaterialName();
        String startDate = materialInfo.getStartDate();
        String endDate = materialInfo.getEndDate();
        materialInfo.setStartDate(null);
        materialInfo.setEndDate(null);
        materialInfo.setMaterialName(null);
        QueryWrapper<MaterialInfo> queryWrapper = new QueryWrapper<>();
        materialInfo.setCreateTime(null);
        if (!Check.isNull(materialInfo.getUserId())) {
            String roleCode = roleService.getRoleCodeByUserId(materialInfo.getUserId());
            if (CtopRoleCodeConstant.COMMON_ROLE_CODE_ADMIN.equals(roleCode) || "operator".equals(roleCode) || "kuaishouOperationManager".equals(roleCode) || "operationAssistant".equals(roleCode) || "touTiaoOperationManager".equals(roleCode) || roleCode.contains("sale")) {
                materialInfo.setUserId(null);
                queryWrapper = QueryGenerator.initQueryWrapper(materialInfo, req.getParameterMap());
            } else if ("designTeamLeader".equals(roleCode) || "planeLeader".equals(roleCode) || "plane".equals(roleCode) || "plan".equals(roleCode) || "shot".equals(roleCode)) {
                String userId = materialInfo.getUserId();
                materialInfo.setUserId(null);
                queryWrapper = QueryGenerator.initQueryWrapper(materialInfo, req.getParameterMap());
                if (Check.isNull(materialInfo.getProductId())) {
                    List<Long> products = memberService.selectProductsByUserId(userId);
                    if (!Check.isNull(products)) {
                        queryWrapper.in("product_id", products);
                    } else {
                        result.setSuccess(true);
                        result.setResult(null);
                        return result;
                    }
                }
            } else {
                queryWrapper = QueryGenerator.initQueryWrapper(materialInfo, req.getParameterMap());
            }
            if (!Check.isNull(startDate) && !Check.isNull(endDate)) {
                try {
                    String startDateStr = DateUtils.getDateString(startDate);
                    String endDateStr = DateUtils.getDateString(endDate);
                    queryWrapper.between("create_time", startDateStr, DateUtils.getEndTime(endDateStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        if (!Check.isNull(materialName)) {
            queryWrapper.like("material_name", materialName);

        }
        Page<MaterialInfo> page = new Page<>(pageNo, pageSize);
        IPage<MaterialInfo> pageList = materialInfoService.page(page, queryWrapper);
        List<MaterialInfo> materialInfoList = pageList.getRecords();
        if (materialInfoList.size() != 0) {
            for (MaterialInfo material : materialInfoList) {
                //判断是否已经同步到快手平台
                Integer kuaishouMaterialUpCount = materialInfoService.getKuaishouUpVideoCount(material.getCode());
                if (kuaishouMaterialUpCount > 0) {
                    material.setKuaishouVideoIsUp(1);
                } else {
                    material.setKuaishouVideoIsUp(0);
                }
                //判断是否已经同步到抖音平台
                Integer toutiaoMaterialUpCount = materialInfoService.getToutiaoUpVideoCount(material.getCode());
                if (toutiaoMaterialUpCount > 0) {
                    material.setToutiaoVideoIsUp(1);
                } else {
                    material.setToutiaoVideoIsUp(0);
                }


                ByteDanceCleanMaterialReport byteDance = byteDanceCleanMaterialReportService.getById(material.getCode());
                if (!Check.isNull(byteDance)) {
                    String byteDanceString = JsonUtil.objectToJson(byteDance);
                    material.setByteDance(JSONObject.parseObject(byteDanceString));
                }
                QueryWrapper<MaterialImageInfo> imageInfoQueryWrapper = new QueryWrapper<>();
                imageInfoQueryWrapper.eq("video_id", material.getCode());
                imageInfoQueryWrapper.eq("status", 0);
                List<MaterialImageInfo> imageInfoList = iMaterialImageInfoService.list(imageInfoQueryWrapper);
                material.setWhetherUnaudited(!Check.isNull(imageInfoList));
            }
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @GetMapping(value = "/listV2")
    public Map<String, Object> queryPageList(String userId, String type, Integer status, Long productId, String materialName, String code,
                                             String startDate, String endDate, String tagCode,
                                             Long projectId, String clipId, String shotId, String planId, String leaderName,
                                             Integer syncKuaishou, Integer syncBytedance, Integer materialInnovate,
                                             @RequestParam(name = "offlineFlag", required = false) Integer offlineFlag,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        List<Long> projectIds = new ArrayList<>();
        if (Check.isNull(userId)) {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = user.getId();
        }
        String roleCode = roleService.getRoleCodeByUserId(userId);
        if (null == tagCode || "".equals(tagCode.trim())) {
            tagCode = null;
        }
        //管理员、销售查询所有素材
        if (CtopRoleCodeConstant.COMMON_ROLE_CODE_ADMIN.equals(roleCode) || roleCode.contains("sale")) {
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                List<Long> projectIdsByProductId = projectService.getProjectIdsByProductId(productId);
                projectIds.addAll(projectIdsByProductId);
            }
            return materialInfoService.getListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, pageNo, pageSize, syncKuaishou, syncBytedance, materialInnovate);
            //运营经理、运营、运营助理
        } else if ("operator".equals(roleCode) || "kuaishouOperationManager".equals(roleCode) || "operationAssistant".equals(roleCode) || "touTiaoOperationManager".equals(roleCode) || "businessOperation".equals(roleCode)) {
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, userId, null, null);
                List<Long> productProjectIds = projectService.getProjectIdsByProductIdAndNotIn(productId, partakeProjectIds);
                projectIds.addAll(partakeProjectIds);
                projectIds.addAll(productProjectIds);
            } else {
                List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(null, userId, null, null);
//                List<Long> productProjectIds = projectService.getProjectIdsByProductIdAndNotIn(null, partakeProjectIds);
                projectIds.addAll(partakeProjectIds);
//                projectIds.addAll(productProjectIds);
            }
            if (Check.isNull(projectIds) || projectIds.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                ResultMapUtils.setResultMap(result, StatusCode.CTOP_PROJECT_NOT_EXIST);
                return result;
            }
            return materialInfoService.getListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, pageNo, pageSize, syncKuaishou, syncBytedance, materialInnovate);

        } else if ("designTeamLeader".equals(roleCode) || "planeLeader".equals(roleCode) || "plane".equals(roleCode) || "plan".equals(roleCode) || "shot".equals(roleCode) || "clip".equals(roleCode)) {
            //查询自己所在项目下的数据
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                projectIds = projectMemberService.getProjectIdsByProductId(productId, userId, null, null);
            } else {
                projectIds = projectMemberService.getProjectIdsByProductId(null, userId, null, null);
            }
            if (Check.isNull(projectIds) || projectIds.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                ResultMapUtils.setResultMap(result, StatusCode.CTOP_PROJECT_NOT_EXIST);
                return result;
            }
            return materialInfoService.getListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, pageNo, pageSize, syncKuaishou, syncBytedance, materialInnovate);
        } else if ("CompanyManager".equals(roleCode)) {
            UserCompany userCompany = userCompanyService.getByUserId(userId);
            if (Check.isNull(userCompany)) {
                return null;
            }
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, null, userCompany.getCompanyId(), null);
                projectIds.addAll(partakeProjectIds);
            } else {
                projectIds = roleService.getCompanyProjectIds(roleCode, userId);
            }
            if (Check.isNull(projectIds) || projectIds.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                ResultMapUtils.setResultMap(result, StatusCode.CTOP_PROJECT_NOT_EXIST);
                return result;
            }
            return materialInfoService.getListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, pageNo, pageSize, syncKuaishou, syncBytedance, materialInnovate);
        } else if ("bytedanceDirector".equals(roleCode)) {
            UserCompany userCompany = userCompanyService.getByUserId(userId);
            if (Check.isNull(userCompany)) {
                return null;
            }
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, null, userCompany.getCompanyId(), "1");
                projectIds.addAll(partakeProjectIds);
            } else {
                projectIds = roleService.getCompanyProjectIds(roleCode, userId);
            }
            if (Check.isNull(projectIds) || projectIds.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                ResultMapUtils.setResultMap(result, StatusCode.CTOP_PROJECT_NOT_EXIST);
                return result;
            }
            return materialInfoService.getListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, pageNo, pageSize, syncKuaishou, syncBytedance, materialInnovate);
        } else if ("kuaishouDirector".equals(roleCode)) {
            UserCompany userCompany = userCompanyService.getByUserId(userId);
            if (Check.isNull(userCompany)) {
                return null;
            }
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, userId, userCompany.getCompanyId(), "2");
                List<Long> productProjectIds = projectService.getProjectIdsByProductIdAndNotIn(productId, partakeProjectIds);
                projectIds.addAll(partakeProjectIds);
                projectIds.addAll(productProjectIds);
            } else {
                projectIds = roleService.getCompanyProjectIds(roleCode, userId);
            }
            if (Check.isNull(projectIds) || projectIds.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                ResultMapUtils.setResultMap(result, StatusCode.CTOP_PROJECT_NOT_EXIST);
                return result;
            }
            return materialInfoService.getListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, pageNo, pageSize, syncKuaishou, syncBytedance, materialInnovate);
        } else {
            //查询自己上传的视频
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                projectIds = projectMemberService.getProjectIdsByProductId(productId, userId, null, null);
            }
            if (Check.isNull(projectIds) || projectIds.isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                ResultMapUtils.setResultMap(result, StatusCode.CTOP_PROJECT_NOT_EXIST);
                return result;
            }
            return materialInfoService.getListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, userId, clipId, shotId, planId, leaderName, offlineFlag, pageNo, pageSize, syncKuaishou, syncBytedance, materialInnovate);
        }
    }


    /**
     * 导出数据
     *
     * @param response
     */
    @GetMapping("/v2Excel")
    public void getExcelReport(HttpServletResponse response, String userId, String type, Integer status, Long productId, String materialName, String code,
                               String startDate, String endDate, String tagCode,
                               Long projectId, String clipId, String shotId, String planId, String leaderName,
                               Integer syncKuaishou, Integer syncBytedance, Integer materialInnovate,
                               @RequestParam(name = "offlineFlag", required = false) Integer offlineFlag) {
        Map<String, Object> map = new HashMap<>();
        List<MaterialInfo> list = new ArrayList<>();
        List<Long> projectIds = new ArrayList<>();
        if (Check.isNull(userId)) {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = user.getId();
        }
        String roleCode = roleService.getRoleCodeByUserId(userId);
        if (null == tagCode || "".equals(tagCode.trim())) {
            tagCode = null;
        }
        //管理员、销售查询所有素材
        if (CtopRoleCodeConstant.COMMON_ROLE_CODE_ADMIN.equals(roleCode) || roleCode.contains("sale")) {
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                List<Long> projectIdsByProductId = projectService.getProjectIdsByProductId(productId);
                projectIds.addAll(projectIdsByProductId);
            }
            list = materialInfoService.getExcelListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, syncKuaishou, syncBytedance, materialInnovate);
            //运营经理、运营、运营助理
        } else if ("operator".equals(roleCode) || "kuaishouOperationManager".equals(roleCode) || "operationAssistant".equals(roleCode) || "touTiaoOperationManager".equals(roleCode) || "businessOperation".equals(roleCode)) {
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, userId, null, null);
                List<Long> productProjectIds = projectService.getProjectIdsByProductIdAndNotIn(productId, partakeProjectIds);
                projectIds.addAll(partakeProjectIds);
                projectIds.addAll(productProjectIds);
            } else {
                List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(null, userId, null, null);
//                List<Long> productProjectIds = projectService.getProjectIdsByProductIdAndNotIn(null, partakeProjectIds);
                projectIds.addAll(partakeProjectIds);
//                projectIds.addAll(productProjectIds);
            }
            if (!Check.isNull(projectIds) && !projectIds.isEmpty()) {
                list = materialInfoService.getExcelListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, syncKuaishou, syncBytedance, materialInnovate);
            }

        } else if ("designTeamLeader".equals(roleCode) || "planeLeader".equals(roleCode) || "plane".equals(roleCode) || "plan".equals(roleCode) || "shot".equals(roleCode) || "clip".equals(roleCode)) {
            //查询自己所在项目下的数据
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                projectIds = projectMemberService.getProjectIdsByProductId(productId, userId, null, null);
            } else {
                projectIds = projectMemberService.getProjectIdsByProductId(null, userId, null, null);
            }
            if (!Check.isNull(projectIds) && !projectIds.isEmpty()) {
                list = materialInfoService.getExcelListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, syncKuaishou, syncBytedance, materialInnovate);
            }
        } else if ("CompanyManager".equals(roleCode)) {
            UserCompany userCompany = userCompanyService.getByUserId(userId);
            if (!Check.isNull(userCompany)) {
                if (!Check.isNull(projectId)) {
                    projectIds.add(projectId);
                } else if (!Check.isNull(productId)) {
                    List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, null, userCompany.getCompanyId(), null);
                    projectIds.addAll(partakeProjectIds);
                } else {
                    projectIds = roleService.getCompanyProjectIds(roleCode, userId);
                }
                if (!Check.isNull(projectIds) && !projectIds.isEmpty()) {
                    list = materialInfoService.getExcelListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, syncKuaishou, syncBytedance, materialInnovate);
                }
            }
        } else if ("bytedanceDirector".equals(roleCode)) {
            UserCompany userCompany = userCompanyService.getByUserId(userId);
            if (!Check.isNull(userCompany)) {
                if (!Check.isNull(projectId)) {
                    projectIds.add(projectId);
                } else if (!Check.isNull(productId)) {
                    List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, null, userCompany.getCompanyId(), "1");
                    projectIds.addAll(partakeProjectIds);
                } else {
                    projectIds = roleService.getCompanyProjectIds(roleCode, userId);
                }
                if (!Check.isNull(projectIds) && !projectIds.isEmpty()) {
                    list = materialInfoService.getExcelListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, syncKuaishou, syncBytedance, materialInnovate);
                }
            }
        } else if ("kuaishouDirector".equals(roleCode)) {
            UserCompany userCompany = userCompanyService.getByUserId(userId);
            if (!Check.isNull(userCompany)) {
                if (!Check.isNull(projectId)) {
                    projectIds.add(projectId);
                } else if (!Check.isNull(productId)) {
                    List<Long> partakeProjectIds = projectMemberService.getProjectIdsByProductId(productId, userId, userCompany.getCompanyId(), "2");
                    List<Long> productProjectIds = projectService.getProjectIdsByProductIdAndNotIn(productId, partakeProjectIds);
                    projectIds.addAll(partakeProjectIds);
                    projectIds.addAll(productProjectIds);
                } else {
                    projectIds = roleService.getCompanyProjectIds(roleCode, userId);
                }
                if (!Check.isNull(projectIds) && !projectIds.isEmpty()) {
                    list = materialInfoService.getExcelListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, null, clipId, shotId, planId, leaderName, offlineFlag, syncKuaishou, syncBytedance, materialInnovate);
                }
            }
        } else {
            //查询自己上传的视频
            if (!Check.isNull(projectId)) {
                projectIds.add(projectId);
            } else if (!Check.isNull(productId)) {
                projectIds = projectMemberService.getProjectIdsByProductId(productId, userId, null, null);
            }
            if (!Check.isNull(projectIds) && !projectIds.isEmpty()) {
                list = materialInfoService.getExcelListByParams(tagCode, type, status, materialName, projectIds, code, startDate, endDate, userId, clipId, shotId, planId, leaderName, offlineFlag, syncKuaishou, syncBytedance, materialInnovate);
            }
        }

        if (!Check.isNull(list)) {
            try {
                List<List<Object>> excelList = new ArrayList<>();
                if (!list.isEmpty()) {
                    for (MaterialInfo info : list) {
                        List<Object> temp = new ArrayList<>();
                        temp.add(info.getMaterialName());
                        temp.add(info.getCode());
                        excelList.add(temp);
                    }
                }
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                String[] titles = {"素材名称", "唯一标识"};
                eeu.exportExcelForAttendance(workbook, 0, "素材信息", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

    @RequestMapping("/excelByIds")
    public void getExcelReport(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject requestJson) {
        JSONArray ids = requestJson.getJSONArray("ids");
        if (Check.isNull(ids)) {
            return;
        }
        List<JSONObject> list = materialInfoService.excelByIds(ids);
        if (!Check.isNull(list)) {
            try {
                List<List<Object>> excelList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    JSONObject jsonObject = list.get(i);
                    List<Object> temp = new ArrayList<>();
                    temp.add(jsonObject.getString("name"));
                    temp.add(jsonObject.getString("url"));

                    excelList.add(temp);

                }
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();
                String[] titles = {"素材名称", "素材链接"};
                eeu.exportExcelForAttendance(workbook, 0, "素材信息", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }


    @ApiOperation(value = "素材信息-分页列表查询", notes = "素材信息-分页列表查询")
    @GetMapping(value = "/supplierList")
    public Result<IPage<MaterialInfo>> supplierList(MaterialInfo materialInfo,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<MaterialInfo>> result = new Result<>();
        String materialName = materialInfo.getMaterialName();
        materialInfo.setMaterialName(null);
        String startDate = materialInfo.getStartDate();
        String endDate = materialInfo.getEndDate();
        materialInfo.setStartDate(null);
        materialInfo.setEndDate(null);

        QueryWrapper<MaterialInfo> queryWrapper = new QueryWrapper<>();
        if (!Check.isNull(materialInfo.getUserId())) {
            String roleCode = roleService.getRoleCodeByUserId(materialInfo.getUserId());
            if (CtopRoleCodeConstant.COMMON_ROLE_CODE_ADMIN.equals(roleCode)) {
                materialInfo.setUserId(null);
            } else {
                result.setResult(null);
                return result;
            }

            queryWrapper = QueryGenerator.initQueryWrapper(materialInfo, req.getParameterMap());

            if (!Check.isNull(startDate) && !Check.isNull(endDate)) {
                try {
                    String startDateStr = DateUtils.getDateString(startDate);
                    String endDateStr = DateUtils.getDateString(endDate);
                    queryWrapper.between("create_time", startDateStr, DateUtils.getEndTime(endDateStr));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        } else {
            result.setResult(null);
            return result;
        }
        if (!Check.isNull(materialName)) {
            queryWrapper.like("material_name", materialName);

        }
        Page<MaterialInfo> page = new Page<>(pageNo, pageSize);
        IPage<MaterialInfo> pageList = materialInfoService.page(page, queryWrapper);
        List<MaterialInfo> materialInfoList = pageList.getRecords();
        if (materialInfoList.size() != 0) {
            for (MaterialInfo material : materialInfoList) {
                QueryWrapper<MaterialImageInfo> imageInfoQueryWrapper = new QueryWrapper<>();
                imageInfoQueryWrapper.eq("video_id", material.getCode());
                imageInfoQueryWrapper.eq("status", 0);
                List<MaterialImageInfo> imageInfoList = iMaterialImageInfoService.list(imageInfoQueryWrapper);
                if (Check.isNull(imageInfoList)) {
                    material.setWhetherUnaudited(false);
                } else {
                    material.setWhetherUnaudited(true);
                }

            }

        }

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 添加
     *
     * @param materialInfo
     * @return
     */
    @ApiOperation(value = "素材信息-添加", notes = "素材信息-添加")
    @PostMapping(value = "/add")
    public Result<MaterialInfo> add(@RequestBody MaterialInfo materialInfo) {
        Result<MaterialInfo> result = new Result<>();
        try {
            materialInfoService.save(materialInfo);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 批量修改产品
     *
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/batchEdit")
    public Result<MaterialInfo> batchEdit(@RequestBody JSONObject jsonObject) {
        Result<MaterialInfo> result = new Result<>();
        try {
            Long productId = jsonObject.getLong("productId");
            JSONArray materialIds = jsonObject.getJSONArray("materialIds");
            for (int i = 0; i < materialIds.size(); i++) {
                String materialId = materialIds.getString(i);
                MaterialInfo updateMaterial = new MaterialInfo();
                updateMaterial.setId(materialId);
                updateMaterial.setProductId(productId);
                materialInfoService.updateById(updateMaterial);

            }
            result.setSuccess(true);
            result.success("修改成功!");
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 头条素材信息编辑
     *
     * @param materialInfo
     * @return
     */
    @PutMapping(value = "/bytedance/edit")
    public Result<MaterialInfo> bytedanceEdit(@RequestBody MaterialInfo materialInfo) {
        Result<MaterialInfo> result = new Result<>();
        MaterialInfo materialInfoEntity = materialInfoService.getById(materialInfo.getId());
        if (materialInfoEntity == null) {
            return result.error500("未找到对应实体");
        }
        String url = materialInfo.getUrl();
        if (!Check.isNull(url)) {
            if (!url.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                url = KuaishouInterfaceConstant.HTTPS_PREFIX + url;
            }
            materialInfo.setUrl(url);
            materialInfo.setCreateTime(new Date());
            MaterialCutFrame cutFrame = materialCutFrameService.getCutFrameByCode(materialInfo.getCode());
            if (Check.isNull(cutFrame)) {
                String videoUrl = URLDecoder.decode(url).replace("https://media-1301855440.cos.ap-chongqing.myqcloud.com/", "");
                String loadImage = "cutFrame/" + materialInfo.getCode() + "/zero.jpg";
                String coverUrl = CloudVideoProcessUtil.videoCutPictureHandle(videoUrl, loadImage);
                materialInfo.setCoverUrl(coverUrl);
           /*     Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            log.info("开始抽帧,code:{}", materialInfo.getCode());
                            materialCutFrameService.getTencentCutFrame(videoUrl, materialInfo.getCode(), coverUrl);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();*/
            } else {
                materialInfo.setCoverUrl(cutFrame.getUrl());
            }
        }

        //  修改素材库 相关联code
        if (!Check.isNull(materialInfo.getCode())) {
            String code = materialInfoEntity.getCode();
            if (!Check.isNull(code)) {
                MaterialTag updateMaterialTag = new MaterialTag();
                updateMaterialTag.setMaterialId(materialInfo.getCode());
                QueryWrapper<MaterialTag> tagQueryWrapper = new QueryWrapper<>();
                tagQueryWrapper.eq("material_id", code);
                materialTagService.update(updateMaterialTag, tagQueryWrapper);
                MaterialParameter updateParameter = new MaterialParameter();
                updateParameter.setMaterialId(materialInfo.getCode());
                QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
                parameterQueryWrapper.eq("material_id", code);
                materialParameterService.update(updateParameter, parameterQueryWrapper);
                MaterialAscription updateMaterialAscription = new MaterialAscription();
                updateMaterialAscription.setMaterialId(materialInfo.getCode());
                QueryWrapper<MaterialAscription> ascriptionQueryWrapper = new QueryWrapper<>();
                ascriptionQueryWrapper.eq("material_id", code);
                materialAscriptionService.update(updateMaterialAscription, ascriptionQueryWrapper);
            }
        }
        //添加视频文案信息
        if (!Check.isNull(materialInfo.getSlogans())) {
            JSONArray slogans = materialInfo.getSlogans();
            if (null != slogans && !slogans.isEmpty()) {
                for (int i = 0; i < slogans.size(); i++) {
                    JSONObject slogenInfo = slogans.getJSONObject(i);
                    String title = slogenInfo.getString("title");
                    title = title.trim().replaceAll("[\\{]{2,}", "{");
                    title = title.trim().replaceAll("[\\}]{2,}", "}");
                    slogenInfo.put("title", title);
                    String reg = "\\{[\\u4e00-\\u9fa5\\-]{2,6}\\}";
                    Pattern pattern = Pattern.compile(reg);
                    Matcher matcher = pattern.matcher(title);
                    JSONArray creativeWordIdsArray = new JSONArray();

                    int len = StringUtils.lengthAsSlogan(title);
                    int left = title.indexOf("{");
                    int right = title.indexOf("}");
                    if (left >= 0 || right >= 0) {
                        int times = 0;
                        while (matcher.find()) { //此处find()每次被调用后，会偏移到下一个匹配
                            times++;
                            if (times >= 3) {
                                result.setCode(500);
                                result.setMessage("动态词包不合法，词包数量超过2个");
                                return result;
                            }
                            String matchStr = matcher.group();//获取当前匹配的值
                            title = title.replace(matchStr, "");
                            ByteDanceCreativeWordPackage creativeWordPackage = byteDanceGeneralCopywriterService.selectCreativeWordPackageByName(matchStr.substring(1, matchStr.length() - 1));
                            if (Check.isNull(creativeWordPackage)) {
                                result.setCode(500);
                                result.setMessage("动态词包不合法，词包不存在或者含有单独的非词包大括号");
                                return result;
                            }
                            creativeWordIdsArray.add(creativeWordPackage.getCreativeWordId());
                            len = len - (right - left) + creativeWordPackage.getMaxWordLen();
                            left = title.indexOf("{");
                            right = title.indexOf("}");
                        }
                        if (title.contains("{") || title.contains("}")) {
                            return result.error500("大括号单独出现或大括号中内容不合法");
                        }
                        slogenInfo.put("creative_word_ids", creativeWordIdsArray.toJSONString());
                    }
                    //校验标题长度，长度小于5和大于30的全部过滤
                    if (len < 5 || len > 30) {
                        result.setCode(500);
                        result.setMessage("文案长度不合法，小于5或大于30");
                        return result;
                    }
                }

                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                slogenInfoService.deleteAllSlogens(Check.isNull(materialInfo.getProjectId()) ? materialInfoEntity.getProjectId() : materialInfo.getProjectId(), materialInfoEntity.getCode(), user.getId());
                slogenInfoService.insertSlogans(Check.isNull(materialInfo.getProjectId()) ? materialInfoEntity.getProjectId() : materialInfo.getProjectId(), materialInfoEntity.getCode(), slogans, user.getId());
            }
        }

        //如果状态为1 审核通过，则更新审核时间
        Integer status = materialInfo.getStatus();
        if (status == 1) {
            materialInfo.setConfirmTime(new Date());
        }

        boolean ok = materialInfoService.updateById(materialInfo);
        if (ok) {
            result.success("修改成功!");
        }
        // 如果状态为2 审核拒绝 给上传人发送消息
        if (status == 2) {
            Product product = productService.getById(materialInfoEntity.getProductId());
            Project project = projectService.getById(materialInfoEntity.getProjectId());
            String text = messageTemplate.getMaterialRejectTemplate(product.getProductName(), project.getProjectName(), materialInfoEntity.getMaterialName(), materialInfo.getRefuseReason());
            MaterialAscription ascription = materialAscriptionService.getInfoByCode(materialInfoEntity.getCode());
            List<String> userList = new ArrayList<>();
            if (!Check.isNull(ascription)) {
                if (!Check.isNull(ascription.getClipId())) {
                    userList.add(ascription.getClipId());
                }
                if (!Check.isNull(ascription.getPlanId())) {
                    userList.add(ascription.getPlanId());
                }
            } else {
                userList.add(materialInfoEntity.getUserId());
            }
            for (int i = 0; i < userList.size(); i++) {
                String userId = userList.get(i);
                sendMessageService.sendMessage(userId, text);
            }
        }
        result.setCode(0);
        return result;

    }

    /**
     * 头条素材信息编辑 -- 批量通过审核
     *
     * @param materialInfo
     * @return
     */
    @PutMapping(value = "/bytedance/batchedit")
    public Result<MaterialInfo> bytedanceBatchEdit(@RequestBody MaterialInfo materialInfo) {
        Result<MaterialInfo> result = new Result<>();
        String[] ids = materialInfo.getIds();
        int successNum = 0;
        for (String id : ids) {
            materialInfo.setId(id);
            Result<MaterialInfo> materialInfoResult = bytedanceEdit(materialInfo);
            if (!materialInfoResult.getCode().equals(0)) {
                return materialInfoResult;
            }
            successNum++;
        }
        result.setCode(0);
        result.setMessage("批量通过" + successNum + "个视频");
        return result;

    }


    // 批量修改状态
    @PostMapping(value = "/batchEditStatus")
    public Result<MaterialInfo> batchEditStatus(@RequestBody JSONObject requestJson) {
        Result<MaterialInfo> result = new Result<>();
        Integer status = requestJson.getInteger("status");
        String userId = requestJson.getString("userId");
        JSONArray ids = requestJson.getJSONArray("ids");
        if (Check.isNull(ids)) {
            result.setCode(-1);
            result.setMessage("请选择素材");
            return result;

        }
        String refuseReason = requestJson.getString("refuseReason");
        int successNum = 0;
        for (int i = 0; i < ids.size(); i++) {
            String id = ids.getString(i);
            MaterialInfo materialInfo = new MaterialInfo();
            materialInfo.setId(id);
            materialInfo.setStatus(status);
            materialInfo.setAuditorId(userId);
            if (status == 1) {
                materialInfo.setConfirmTime(new Date());
            } else if (status == 2) {
                materialInfo.setRefuseReason(refuseReason);
            }
            boolean b = materialInfoService.updateById(materialInfo);
            if (b) {
                successNum++;
            }

        }
        result.setCode(0);
        result.setMessage("批量通过" + successNum + "个视频");
        return result;

    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "素材信息-通过id删除", notes = "素材信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<Object> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            MaterialInfo materialInfo = materialInfoService.getById(id);
            if (!Check.isNull(materialInfo)) {
                Map<String, Object> deleteMap = new HashMap<>();
                deleteMap.put("material_id", materialInfo.getCode());
                materialAscriptionService.removeByMap(deleteMap);
                materialParameterService.removeByMap(deleteMap);
                materialTagService.removeByMap(deleteMap);
                Map<String, Object> deleteWatermarkMap = new HashMap<>();
                deleteWatermarkMap.put("video_id", id);
                watermarkTaskService.removeByMap(deleteWatermarkMap);
            }
            materialInfoService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "素材信息-批量删除", notes = "素材信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<MaterialInfo> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<MaterialInfo> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.materialInfoService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "素材信息-通过id查询", notes = "素材信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MaterialInfo> queryById(@RequestParam(name = "id") String id) {
        Result<MaterialInfo> result = new Result<>();
        MaterialInfo materialInfo = materialInfoService.getById(id);
        if (materialInfo == null) {
            result.error500("未找到对应实体");
        } else {
            //查询素材下关联的头条文案信息
            List<BytedanceVideoSlogenInfo> slogenInfos = slogenInfoService.listByParams(materialInfo.getCode(), 1);
            JSONArray slogenArray = new JSONArray();
            if (null != slogenInfos && !slogenInfos.isEmpty()) {
                slogenArray.addAll(slogenInfos);
            }
            materialInfo.setSlogans(slogenArray);
            result.setResult(materialInfo);
            result.setSuccess(true);
        }
        return result;
    }

    @ApiOperation(value = "获取有效素材", notes = "获取有效素材")
    @GetMapping(value = "/effiMaterialInfo")
    public Result<IPage<MaterialInfo>> effiMaterialInfo(MaterialInfo materialInfo,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<MaterialInfo>> result = new Result<>();
        QueryWrapper<MaterialInfo> queryWrapper = new QueryWrapper<>();

        List<String> effiList = materialInfoService.getEffiCode();
        Object createTime = materialInfo.getCreateTime();
        materialInfo.setCreateTime(null);
        queryWrapper.in("code", effiList);
        queryWrapper.groupBy("code");
        //queryWrapper = QueryGenerator.initQueryWrapper(materialInfo, req.getParameterMap());

        Page<MaterialInfo> page = new Page<>(pageNo, pageSize);
        IPage<MaterialInfo> pageList = materialInfoService.page(page, queryWrapper);

        List<MaterialInfo> materialInfoList = pageList.getRecords();
        if (materialInfoList.size() != 0) {
            for (MaterialInfo material : materialInfoList) {
                //判断是否已经同步到快手平台
                Integer kuaishouMaterialUpCount = materialInfoService.getKuaishouUpVideoCount(material.getCode());
                if (kuaishouMaterialUpCount > 0) {
                    material.setKuaishouVideoIsUp(1);
                } else {
                    material.setKuaishouVideoIsUp(0);
                }
                //判断是否已经同步到抖音平台
                Integer toutiaoMaterialUpCount = materialInfoService.getToutiaoUpVideoCount(material.getCode());
                if (toutiaoMaterialUpCount > 0) {
                    material.setToutiaoVideoIsUp(1);
                } else {
                    material.setToutiaoVideoIsUp(0);
                }
            }
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @ApiOperation(value = "素材信息-编辑", notes = "素材信息-编辑")
    @PutMapping(value = "/edit")
    public Result<MaterialInfo> edit(@RequestBody MaterialInfo materialInfo) {
        Result<MaterialInfo> result = new Result<>();
        MaterialInfo materialInfoEntity = materialInfoService.getById(materialInfo.getId());
        if (materialInfoEntity == null) {
            return result.error500("未找到对应实体");
        }
        //TODO 驳回重新上传素材时需要清空素材的水印信息数据
        String url = materialInfo.getUrl();
        if (!Check.isNull(url)) {
            if (!url.contains(KuaishouInterfaceConstant.HTTPS_PREFIX)) {
                url = KuaishouInterfaceConstant.HTTPS_PREFIX + url;
            }
            materialInfo.setUrl(url);
            materialInfo.setCreateTime(new Date());
            MaterialCutFrame cutFrame = materialCutFrameService.getCutFrameByCode(materialInfo.getCode());
            if (Check.isNull(cutFrame)) {
                String videoUrl = URLDecoder.decode(url).replace("https://media-1301855440.cos.ap-chongqing.myqcloud.com/", "");
                String loadImage = "cutFrame/" + materialInfo.getCode() + "/zero.jpg";
                String coverUrl = CloudVideoProcessUtil.videoCutPictureHandle(videoUrl, loadImage);
                materialInfo.setCoverUrl(coverUrl);
              /*  Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            log.info("开始抽帧,code:{}", materialInfo.getCode());
                            materialCutFrameService.getTencentCutFrame(videoUrl, materialInfo.getCode(), coverUrl);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();*/
            } else {
                materialInfo.setCoverUrl(cutFrame.getUrl());
            }

        }

        //  修改素材库 相关联code
        if (!Check.isNull(materialInfo.getCode())) {
            String code = materialInfoEntity.getCode();
            if (!Check.isNull(code)) {
                MaterialTag updateMaterialTag = new MaterialTag();
                updateMaterialTag.setMaterialId(materialInfo.getCode());
                QueryWrapper<MaterialTag> tagQueryWrapper = new QueryWrapper<>();
                tagQueryWrapper.eq("material_id", code);
                materialTagService.update(updateMaterialTag, tagQueryWrapper);
                MaterialParameter updateParameter = new MaterialParameter();
                updateParameter.setMaterialId(materialInfo.getCode());
                QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
                parameterQueryWrapper.eq("material_id", code);
                materialParameterService.update(updateParameter, parameterQueryWrapper);
                MaterialAscription updateMaterialAscription = new MaterialAscription();
                updateMaterialAscription.setMaterialId(materialInfo.getCode());
                QueryWrapper<MaterialAscription> ascriptionQueryWrapper = new QueryWrapper<>();
                ascriptionQueryWrapper.eq("material_id", code);
                materialAscriptionService.update(updateMaterialAscription, ascriptionQueryWrapper);
            }
        }
        Integer status = materialInfo.getStatus();
        if (status == 1) {
            materialInfo.setConfirmTime(new Date());
        }
        boolean ok = materialInfoService.updateById(materialInfo);
        if (ok) {
            result.success("修改成功!");
        }
        // 如果状态为2 审核拒绝 给上传人发送消息
        if (status == 2) {
            Product product = productService.getById(materialInfoEntity.getProductId());
            Project project = projectService.getById(materialInfoEntity.getProjectId());
            String text = messageTemplate.getMaterialRejectTemplate(product.getProductName(), project.getProjectName(), materialInfoEntity.getMaterialName(), materialInfo.getRefuseReason());
            List<String> userList = new ArrayList<>();
            MaterialAscription ascription = materialAscriptionService.getInfoByCode(materialInfoEntity.getCode());
            if (!Check.isNull(ascription)) {
                if (!Check.isNull(ascription.getClipId())) {
                    userList.add(ascription.getClipId());
                }
                if (!Check.isNull(ascription.getPlanId())) {
                    userList.add(ascription.getPlanId());
                }
            } else {
                userList.add(materialInfoEntity.getUserId());
            }
            for (int i = 0; i < userList.size(); i++) {
                String userId = userList.get(i);
                sendMessageService.sendMessage(userId, text);
            }
        }
        return result;
    }

    /**
     * adlab 新加查询素材库接口
     */
    @PostMapping(value = "/listByAccountIds")
    public Result<IPage<MaterialInfo>> listByAccountIds(@RequestBody JSONObject requestBody) {

        Result<IPage<MaterialInfo>> result = new Result<>();
        QueryWrapper<MaterialInfo> queryWrapper = new QueryWrapper<>();
        if (!Check.isNull(requestBody.getString("userId"))) {
            queryWrapper.eq("user_id", requestBody.getString("userId"));
            List<Long> products = memberService.getProductByAccountIds(requestBody.getJSONArray("accountIds"));
            if (!Check.isNull(products)) {
                queryWrapper.in("product_id", products);
            }
        }
        queryWrapper.orderByDesc(true, "create_time");
        Page<MaterialInfo> page = new Page<>(requestBody.getInteger("pageNo"), requestBody.getInteger("pageSize"));
        IPage<MaterialInfo> pageList = materialInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

}
