package org.jeecg.modules.duxiaoman.controller;

import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.mapper.MaterialAscriptionMapper;
import cn.com.ctop.common.module.service.IMaterialTagInfoService;
import cn.com.ctop.common.module.service.IMessageTemplate;
import cn.com.ctop.common.module.service.IProjectService;
import cn.com.ctop.common.module.service.ISendMessageService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CloudVideoProcessUtil;
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.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.MD5Util;
import org.jeecg.modules.duxiaoman.entity.DuxiaomanMaterialInfo;
import org.jeecg.modules.duxiaoman.service.IDuxiaomanMaterialInfoService;
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.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 java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 度小满素材信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2022-08-15
 */
@Slf4j
@Api(tags = "度小满素材信息")
@RestController
@RequestMapping("/duxiaoman/materialInfo")
public class DuxiaomanMaterialInfoController {
    @Autowired
    private IDuxiaomanMaterialInfoService duxiaomanMaterialInfoService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IMessageTemplate messageTemplate;

    @Autowired
    private ISendMessageService sendMessageService;

    @Resource
    private MaterialAscriptionMapper materialAscriptionMapper;

    @Autowired
    private IMaterialTagInfoService materialTagInfoService;

    /**
     * 分页列表查询
     *
     * @param duxiaomanMaterialInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "度小满素材信息-分页列表查询", notes = "度小满素材信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<DuxiaomanMaterialInfo>> queryPageList(DuxiaomanMaterialInfo duxiaomanMaterialInfo,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        String materialName = duxiaomanMaterialInfo.getMaterialName();
        duxiaomanMaterialInfo.setMaterialName(null);
        duxiaomanMaterialInfo.setUserId(null);
        Result<IPage<DuxiaomanMaterialInfo>> result = new Result<>();
        QueryWrapper<DuxiaomanMaterialInfo> queryWrapper = QueryGenerator.initQueryWrapper(duxiaomanMaterialInfo, req.getParameterMap());
        if (!Check.isNull(materialName)) {
            queryWrapper.like("material_name", materialName);
        }
        if (!Check.isNull(duxiaomanMaterialInfo.getType())) {
            queryWrapper.eq("type", duxiaomanMaterialInfo.getType());
        }
        if (!Check.isNull(duxiaomanMaterialInfo.getStatus())) {
            queryWrapper.eq("status", duxiaomanMaterialInfo.getStatus());
        }
        if (!Check.isNull(duxiaomanMaterialInfo.getProductId())) {
            queryWrapper.eq("product_id", duxiaomanMaterialInfo.getProductId());
        }
        if (!Check.isNull(duxiaomanMaterialInfo.getProjectId())) {
            queryWrapper.eq("project_id", duxiaomanMaterialInfo.getProjectId());
        }
        if (!Check.isNull(duxiaomanMaterialInfo.getSignature())) {
            queryWrapper.eq("signature", duxiaomanMaterialInfo.getSignature());
        }
        if (!Check.isNull(duxiaomanMaterialInfo.getEndDate())) {
            queryWrapper.le("stat_date", duxiaomanMaterialInfo.getEndDate());
            queryWrapper.gt("stat_date", duxiaomanMaterialInfo.getStartDate());
        }
        queryWrapper.orderByDesc("create_time");
        Page<DuxiaomanMaterialInfo> page = new Page<DuxiaomanMaterialInfo>(pageNo, pageSize);
        IPage<DuxiaomanMaterialInfo> pageList = duxiaomanMaterialInfoService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     */
    @PostMapping(value = "/add")
    public Result<Object> add(@RequestBody JSONObject json) {
        try {
            return duxiaomanMaterialInfoService.add(json);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("失败");
    }

    /**
     * 批量添加
     */
    @PostMapping(value = "/addMore")
    public Result<Object> addMore(@RequestBody JSONObject json) {
        try {
            JSONArray array = json.getJSONArray("videoArray");
            Long projectId = json.getLong("projectId");
            for (int i = 0; i < array.size(); i++) {
                JSONObject data = array.getJSONObject(i);
                String url = "https:" + data.getString("url");
                data.put("url", url);
                data.put("signature", MD5Util.md5ByUrl(url));
                data.put("projectId", projectId);
                duxiaomanMaterialInfoService.add(data);
                Thread.sleep(1000);
            }
            return Result.ok("成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("失败");
    }

    /**
     * 上传素材
     */
    @PostMapping(value = "/upload")
    public Result<Object> upload(@RequestBody DuxiaomanMaterialInfo materialInfo) {
        try {
            return duxiaomanMaterialInfoService.upload(materialInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("失败");
    }

    /**
     * 编辑
     */
    @ApiOperation(value = "度小满素材信息-编辑", notes = "度小满素材信息-编辑")
    @PostMapping(value = "/edit")
    public Result<DuxiaomanMaterialInfo> edit(@RequestBody DuxiaomanMaterialInfo duxiaomanMaterialInfo) {
        Result<DuxiaomanMaterialInfo> result = new Result<DuxiaomanMaterialInfo>();
        DuxiaomanMaterialInfo duxiaomanMaterialInfoEntity = duxiaomanMaterialInfoService.getById(duxiaomanMaterialInfo.getId());
        if (duxiaomanMaterialInfoEntity == null) {
            result.error500("未找到对应实体");
        } else {
            if (!Check.isNull(duxiaomanMaterialInfo.getUrl()) && !duxiaomanMaterialInfo.getUrl().contains("https")) {
                duxiaomanMaterialInfo.setUrl("https:" + duxiaomanMaterialInfo.getUrl());
                String md5 = MD5Util.md5ByUrl(duxiaomanMaterialInfo.getUrl());
                duxiaomanMaterialInfo.setSignature(md5);
                materialAscriptionMapper.updateBySignature(duxiaomanMaterialInfoEntity.getSignature(), md5);
                materialTagInfoService.updateBySignature(duxiaomanMaterialInfoEntity.getSignature(), md5);
                String videoUrl = URLDecoder.decode(duxiaomanMaterialInfo.getUrl()).replace("https://media-1301855440.cos.ap-chongqing.myqcloud.com/", "");
                String loadImage = "cutFrame/" + md5 + "/zero.jpg";
                try {
                    String coverUrl = CloudVideoProcessUtil.videoCutPictureHandle(videoUrl, loadImage);
                    duxiaomanMaterialInfo.setCoverUrl(coverUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (duxiaomanMaterialInfo.getStatus() == 0) {
                    duxiaomanMaterialInfo.setRefuseReason("");
                    duxiaomanMaterialInfo.setAuditImagesId("");
                }
                duxiaomanMaterialInfo.setCreateTime(new Date());
            }

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

            if (duxiaomanMaterialInfo.getStatus() == 6) {
                Project project = projectService.getById(duxiaomanMaterialInfo.getProjectId());
                String text = messageTemplate.getDuXiaoManMaterialTemplate(duxiaomanMaterialInfo.getProductName(), project.getProjectName(), duxiaomanMaterialInfo.getMaterialName(), duxiaomanMaterialInfo.getRefuseReason(), false);
                sendMessageService.sendMessage(duxiaomanMaterialInfo.getUserId(), text);
            }

        }
        return result;
    }


    /**
     * 编辑
     */
    @PostMapping(value = "/editMore")
    public Result<DuxiaomanMaterialInfo> editMore(@RequestBody JSONObject datas) {
        Result<DuxiaomanMaterialInfo> result = new Result<DuxiaomanMaterialInfo>();
        try {
            JSONArray array = datas.getJSONArray("array");
            List<DuxiaomanMaterialInfo> list = JSONArray.parseObject(array.toJSONString(), List.class);
            boolean ok = duxiaomanMaterialInfoService.updateBatchById(list);
            if (ok) {
                result.success("修改成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.error500("修改失败");
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "度小满素材信息-通过id删除", notes = "度小满素材信息-通过id删除")
    @GetMapping(value = "/deleteById")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            duxiaomanMaterialInfoService.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<DuxiaomanMaterialInfo> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<DuxiaomanMaterialInfo> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.duxiaomanMaterialInfoService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "度小满素材信息-通过id查询", notes = "度小满素材信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Object> queryById(@RequestParam(name = "id", required = true) String id) {
        JSONObject obj = new JSONObject();
        DuxiaomanMaterialInfo duxiaomanMaterialInfo = duxiaomanMaterialInfoService.getById(id);
        if (Check.isNull(duxiaomanMaterialInfo)) {
            return Result.error("未查询到实体");
        }
        return duxiaomanMaterialInfoService.getPersonnelInfo(duxiaomanMaterialInfo);
    }


    /**
     * 将1-待上传状态的素材 进行 上传媒体
     */
    @GetMapping(value = "/uploadMaterial")
    public void uploadMaterial(String id) {
        DuxiaomanMaterialInfo materialInfo = duxiaomanMaterialInfoService.getById(id);
        duxiaomanMaterialInfoService.uploadMaterial(materialInfo);
    }

    /**
     * 将7-上传成功状态的素材 进行 素材报备
     */
    @GetMapping(value = "/materialReport")
    public void materialReport(String id) {
        DuxiaomanMaterialInfo materialInfo = duxiaomanMaterialInfoService.getById(id);
        duxiaomanMaterialInfoService.materialReport(materialInfo);
    }


    /**
     * 将2-审批中状态的素材 进行 更新报备状态
     */
    @GetMapping(value = "/materialDetail")
    public void materialDetail(String id) {
        DuxiaomanMaterialInfo materialInfo = duxiaomanMaterialInfoService.getById(id);
        duxiaomanMaterialInfoService.materialDetail(materialInfo);
    }

    /**
     * 审核图片预览
     */
    @GetMapping(value = "/materialBos")
    public Result<Object> materialBos(String id) {
        return duxiaomanMaterialInfoService.materialBos(id);
    }

    /**
     * 将2-审批中状态的素材 进行 更新报备状态
     */
    @GetMapping(value = "/getMaterialChannelAndType")
    public Result<Object> getMaterialChannelAndType(String id) {
        JSONObject obj = new JSONObject();
        obj.put("channel", duxiaomanMaterialInfoService.getMaterialChannel());
        obj.put("type", duxiaomanMaterialInfoService.getMaterialType());
        return Result.ok(obj);
    }

}
