package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.annotation.AutoLog;
import cn.com.ctop.common.module.constant.CtopRoleCodeConstant;
import cn.com.ctop.common.module.entity.*;
import cn.com.ctop.common.module.enums.MaterialSupplierEnum;
import cn.com.ctop.common.module.service.*;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CloudVideoProcessUtil;
import cn.com.ctop.common.module.utils.JsonUtil;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouReportDailyMaterialService;
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.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.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.*;

/**
 * 素材信息
 *
 * @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 IKuaiShouReportDailyMaterialService kuaiShouReportDailyMaterialService;


    @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;
    }


    @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) {
        Result<Object> result = new Result<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        materialInfoService.watermarkVideo(id, watermarkTemplateId, sysUser.getId());
        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;
    }

    @Autowired
    private ISysRoleService roleService;

    @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.getProjectId())) {
                    List<Long> projects = memberService.selectProjectsByUserId(userId);
                    if (!Check.isNull(projects)) {
                        queryWrapper.in("project_id", projects);
                    } 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));
                }


                Project project = projectService.getById(material.getProjectId());
                if (!Check.isNull(project)) {
                    material.setMediaId(project.getMediaId());
                    material.setProjectName(project.getProjectName());
                }

                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;
    }

    @GetMapping(value = "/listV2")
    public Map<String, Object> queryPageList(String type, Integer status, Long projectId, String materialName, String code,
                                             String startDate, String endDate, String tagCode,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<Long> projectIds = null;
        String userId = user.getId();
        String roleCode = roleService.getRoleCodeByUserId(userId);
        if (null == tagCode || "".equals(tagCode.trim())) {
            tagCode = null;
        }
        if (CtopRoleCodeConstant.COMMON_ROLE_CODE_ADMIN.equals(roleCode) || "operator".equals(roleCode) || "kuaishouOperationManager".equals(roleCode) || "operationAssistant".equals(roleCode) || "touTiaoOperationManager".equals(roleCode) || roleCode.contains("sale")) {
            //查询所有
            if (null != projectId && projectId != 0) {
                projectIds = new ArrayList<>();
                projectIds.add(projectId);
            }
            return materialInfoService.getListByParams(tagCode, type, status, projectIds, materialName, code, startDate, endDate, null, pageNo, pageSize);
        } else if ("designTeamLeader".equals(roleCode) || "planeLeader".equals(roleCode) || "plane".equals(roleCode) || "plan".equals(roleCode) || "shot".equals(roleCode)) {
            //查询自己所在项目下的数据
            if (null == projectId || projectId == 0) {
                projectIds = memberService.selectProjectsByUserId(userId);
            } else {
                projectIds = new ArrayList<>();
                projectIds.add(projectId);
            }
            return materialInfoService.getListByParams(tagCode, type, status, projectIds, materialName, code, startDate, endDate, null, pageNo, pageSize);
        } else {
            //查询自己上传的视频
            if (null != projectId && projectId != 0) {
                projectIds = new ArrayList<>();
                projectIds.add(projectId);
            }
            return materialInfoService.getListByParams(tagCode, type, status, projectIds, materialName, code, startDate, endDate, userId, pageNo, pageSize);
        }
    }


    @AutoLog(value = "素材信息-分页列表查询")
    @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) {
                Project project = projectService.getById(material.getProjectId());
                if (!Check.isNull(project)) {
                    material.setMediaId(project.getMediaId());
                    material.setProjectName(project.getProjectName());
                }

                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
     */
    @AutoLog(value = "素材信息-添加")
    @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 projectId = jsonObject.getLong("projectId");
            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.setProjectId(projectId);
                materialInfoService.updateById(updateMaterial);

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

    /**
     * 编辑
     *
     * @param materialInfo
     * @return
     */
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IMessageTemplate messageTemplate;
    @Autowired
    private ISendMessageService sendMessageService;

    @AutoLog(value = "素材信息-编辑")
    @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("未找到对应实体");
        }
        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);
            }
        }

        //  审核通过自动同步到到媒体后台
       /* Long projectId = materialInfoEntity.getProjectId();
        Project project = projectService.getById(projectId);
        if (!Check.isNull(projectId)) {
            if ("2".equals(project.getMediaId())) {
                if (!Check.isNull(materialInfo.getStatus())) {
                    Integer status = materialInfo.getStatus();
                    if (status == 1) {
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                log.info("开始自动同步素材，code：{}", materialInfoEntity.getCode());
                                uploadService.upload(materialInfoEntity);
                            }
                        };
                        thread.start();
                    }
                }
            }

        }*/

        boolean ok = materialInfoService.updateById(materialInfo);
        if (ok) {
            result.success("修改成功!");
        }

        Integer status = materialInfo.getStatus();
        // 如果状态为2 审核拒绝 给上传人发送消息
        if (status == 2) {
            Project project = projectService.getById(materialInfoEntity.getProjectId());
            String text = messageTemplate.getMaterialRejectTemplate(project.getProjectName(), materialInfoEntity.getMaterialName(), materialInfo.getRefuseReason());
            sendMessageService.sendMessage(materialInfoEntity.getUserId(), text);
        }
        return result;

    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "素材信息-通过id删除")
    @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
     */
    @AutoLog(value = "素材信息-批量删除")
    @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
     */
    @AutoLog(value = "素材信息-通过id查询")
    @ApiOperation(value = "素材信息-通过id查询", notes = "素材信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MaterialInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<MaterialInfo> result = new Result<>();
        MaterialInfo materialInfo = materialInfoService.getById(id);
        if (materialInfo == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(materialInfo);
            result.setSuccess(true);
        }
        return result;
    }

    @AutoLog(value = "获取有效素材")
    @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;
    }

    /**
     * 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> projects = memberService.getProjectByAccountIds(requestBody.getJSONArray("accountIds"));
            if (!Check.isNull(projects)) {
                queryWrapper.in("project_id", projects);
            }
        }
        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;
    }

}
