package org.jeecg.modules.fileupload.controller;

import cn.com.ctop.common.module.entity.MaterialTagInfo;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.ExternalMaterialCollection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.fileupload.service.IExternalMaterialCollectionService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 外部素材集信息表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2022-01-12
 */
@Slf4j
@Api(tags = "外部素材集信息表")
@RestController
@RequestMapping("/external/materialCollection")
public class ExternalMaterialCollectionController {
    @Autowired
    private IExternalMaterialCollectionService externalMaterialCollectionService;

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/list")
    public Result<Object> queryPageList(ExternalMaterialCollection externalMaterialCollection,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                        HttpServletRequest req) {
        try {
            return externalMaterialCollectionService.queryPageList(externalMaterialCollection, pageNo, pageSize);
        } catch (Exception e) {
            log.error("查询异常,", e.getMessage());
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    /**
     * 上传单素材——视频
     */
    @PostMapping(value = "/addByVideo")
    public Result<ExternalMaterialCollection> addByVideo(@RequestBody JSONObject json) {
        Result<ExternalMaterialCollection> result = new Result<>();
        try {
            ExternalMaterialCollection materialCollection = JSONObject.parseObject(json.toJSONString(), ExternalMaterialCollection.class);
            if (Check.isNull(materialCollection)) {
                throw new Exception("数据格式异常");
            }
            externalMaterialCollectionService.addByVideo(materialCollection);
            result.success("素材异步上传中");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 上传单素材——链接
     */
    @PostMapping(value = "/addByUrl")
    public Result<ExternalMaterialCollection> addByUrl(@RequestBody JSONObject json) {
        Result<ExternalMaterialCollection> result = new Result<>();
        try {
            ExternalMaterialCollection materialCollection = JSONObject.parseObject(json.toJSONString(), ExternalMaterialCollection.class);
            if (Check.isNull(materialCollection)) {
                throw new Exception("数据格式异常");
            }
            externalMaterialCollectionService.addByUrl(materialCollection);
            result.success("素材异步上传中！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 上传批量素材——视频
     */
    @PostMapping(value = "/addMoreVideos")
    public Result<ExternalMaterialCollection> addMoreVideos(@RequestBody JSONArray array) {
        Result<ExternalMaterialCollection> result = new Result<>();
        try {
            if (array.size() < 1) {
                return result.error500("缺少参数");
            }
            externalMaterialCollectionService.addMoreVideos(array);
            result.success("素材异步上传中！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    /**
     * 上传批量素材——链接
     */
    @PostMapping(value = "/addMoreVideosByUrl")
    public Result<ExternalMaterialCollection> addMoreVideosByUrl(@RequestBody JSONArray array) {
        Result<ExternalMaterialCollection> result = new Result<>();
        try {
            if (array.size() < 1) {
                return result.error500("缺少参数");
            }
            externalMaterialCollectionService.addMoreVideosByUrl(array);
            result.success("素材异步上传中！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 上传批量素材——excel
     */
    @PostMapping(value = "/addMoreVideosByExcel")
    @ResponseBody
    public Result<Object> addMoreVideosByExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file, @RequestParam("materialSource") String materialSource, @RequestParam("userId") String userId, @RequestParam("mediaType") Integer mediaType) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (Check.isNull(file) || Check.isNull(materialSource) || Check.isNull(userId) || Check.isNull(mediaType)) {
                return Result.error("缺少参数");
            }
            return externalMaterialCollectionService.addMoreVideosByExcel(file, materialSource, userId, mediaType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("excel批量导入链接异常", e);
            return Result.error("excel批量导入链接失败，" + e.getMessage());
        }
    }

    /**
     * 校验素材是否已存在
     */
    @GetMapping(value = "/checkMaterialByMd5")
    public Result<ExternalMaterialCollection> checkMaterialByMd5(String md5) {
        Result<ExternalMaterialCollection> result = new Result<>();
        try {
            if (Check.isNull(md5)) {
                return result.error500("缺少参数");
            }
            boolean f = externalMaterialCollectionService.checkMaterialByMd5(md5);
            if (f) {
                result.success("success");
            } else {
                result.error500("fail");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 行业标签
     */
    @GetMapping(value = "/getIndustry")
    public Result<Object> getIndustry() {
        try {
            return externalMaterialCollectionService.getIndustryLabel();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    /**
     * 标签回显
     */
    @GetMapping(value = "/getTagDetail")
    public Result<Object> getTagDetail(String md5, Integer mediaType) {
        return externalMaterialCollectionService.getTagDetail(md5, mediaType);
    }


    /**
     * 同步内部素材
     */
    @GetMapping(value = "/createInternalMaterial")
    public Result<Object> createInternalMaterial() {
        try {
            return externalMaterialCollectionService.createInternalMaterial();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    /**
     * 编辑
     */
    @PostMapping(value = "/edit")
    public Result<ExternalMaterialCollection> edit(@RequestBody ExternalMaterialCollection externalMaterialCollection) {
        Result<ExternalMaterialCollection> result = new Result<ExternalMaterialCollection>();
        ExternalMaterialCollection externalMaterialCollectionEntity = externalMaterialCollectionService.getById(externalMaterialCollection.getId());
        if (externalMaterialCollectionEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = externalMaterialCollectionService.updateById(externalMaterialCollection);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

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

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "外部素材集信息表-通过id查询", notes = "外部素材集信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ExternalMaterialCollection> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ExternalMaterialCollection> result = new Result<>();
        ExternalMaterialCollection externalMaterialCollection = externalMaterialCollectionService.getById(id);
        if (externalMaterialCollection == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(externalMaterialCollection);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<ExternalMaterialCollection> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                ExternalMaterialCollection externalMaterialCollection = JSON.parseObject(deString, ExternalMaterialCollection.class);
                queryWrapper = QueryGenerator.initQueryWrapper(externalMaterialCollection, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<ExternalMaterialCollection> pageList = externalMaterialCollectionService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "外部素材集信息表列表");
        mv.addObject(NormalExcelConstants.CLASS, ExternalMaterialCollection.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("外部素材集信息表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ExternalMaterialCollection> listExternalMaterialCollections = ExcelImportUtil.importExcel(file.getInputStream(), ExternalMaterialCollection.class, params);
                externalMaterialCollectionService.saveBatch(listExternalMaterialCollections);
                return Result.ok("文件导入成功！数据行数:" + listExternalMaterialCollections.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 导出excel模板
     */
    @GetMapping("/exportTemplate")
    public Result<Object> exportTemplate(HttpServletResponse response) {
        try {

            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] titles = {
                    "行业（如：综合游戏、休闲益智、动作射击、棋牌桌游、综合服务、小额贷款、第三方支付、金融综合线上平台、综合电商、电商商家、跨境、其他电商零售类、服饰、美妆日化、快消、工具、影音娱乐、婚恋/交友、生活/健康）请严格按照以上的行业填写，否则无法识别",
                    "产品",
                    "素材链接",
                    "版位",
                    "素材描述"
            };
            eeu.putHeaders(workbook, 0, "Sheet1", titles);
            eeu.putResponseHeader(response, "exportTemplate.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return Result.ok("success");
    }
}
