package cn.com.ctop.kuaishou.modules.ai.controller;

import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouVideoDirectionalPackage;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouVideoDirectionalPackageService;
import com.alibaba.fastjson.JSON;
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.oConvertUtils;
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.PutMapping;
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.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.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 素材绑定的定向包模板
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-05-25
 */
@Slf4j
@Api(tags = "素材绑定的定向包模板")
@RestController
@RequestMapping("/kuaishouVideoDirectionalPackage")
public class KuaishouVideoDirectionalPackageController {
    @Autowired
    private IKuaishouVideoDirectionalPackageService kuaishouVideoDirectionalPackageService;
    @Autowired
    private IUserAllocationService userAllocationService;
    /**
     * 分页列表查询
     *
     * @param kuaishouVideoDirectionalPackage
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "素材绑定的定向包模板-分页列表查询", notes = "素材绑定的定向包模板-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<KuaishouVideoDirectionalPackage>> queryPageList(KuaishouVideoDirectionalPackage kuaishouVideoDirectionalPackage,
                                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                        HttpServletRequest req) {
        Result<IPage<KuaishouVideoDirectionalPackage>> result = new Result<>();
        QueryWrapper<KuaishouVideoDirectionalPackage> queryWrapper = QueryGenerator.initQueryWrapper(kuaishouVideoDirectionalPackage, req.getParameterMap());
        Page<KuaishouVideoDirectionalPackage> page = new Page<KuaishouVideoDirectionalPackage>(pageNo, pageSize);
        IPage<KuaishouVideoDirectionalPackage> pageList = kuaishouVideoDirectionalPackageService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 创建定向包
     *
     * @param
     * @return
     */
    @PostMapping(value = "/saveOrUpdate")
    public Result<Object> saveOrUpdate(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            String videoGetId = requestJson.getString("videoGetId");
            if (Check.isNull(videoGetId)) {
                return Result.error("请选择素材");
            }
            KuaishouVideoDirectionalPackage directionalPackage = JSONObject.toJavaObject(requestJson, KuaishouVideoDirectionalPackage.class);
            if (!Check.isNull(requestJson.getJSONArray("keyword"))) {
                directionalPackage.setKeyword(JSONObject.toJSONString(requestJson.getJSONArray("keyword")));
            }
            if("0".equals(requestJson.getJSONObject("allForm").getString("behaviorInterest"))){
                directionalPackage.setSceneType("[]");
                directionalPackage.setTimeType(-1);
                directionalPackage.setStrengthType(0);
                directionalPackage.setLabel("[]");
                directionalPackage.setInterestLabel("[]");
            }
            kuaishouVideoDirectionalPackageService.saveOrUpdate(directionalPackage);
            String id = "";
            if (!Check.isNull(directionalPackage.getId())) {
                id = directionalPackage.getId();
            } else {
                QueryWrapper<KuaishouVideoDirectionalPackage> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("video_get_id", videoGetId);
                queryWrapper.eq("signature", directionalPackage.getSignature());
                KuaishouVideoDirectionalPackage one = kuaishouVideoDirectionalPackageService.getOne(queryWrapper);
                if(!Check.isNull(one)){
                    id = one.getId();
                }
            }
            return Result.ok(id);
        } catch (Exception e) {
            log.error("创建定向包失败", e);
            return Result.error("创建失败" + e.getMessage());
        }
    }

    /**
     * 编辑
     *
     * @param kuaishouVideoDirectionalPackage
     * @return
     */
    @ApiOperation(value = "素材绑定的定向包模板-编辑", notes = "素材绑定的定向包模板-编辑")
    @PutMapping(value = "/edit")
    public Result<KuaishouVideoDirectionalPackage> edit(@RequestBody KuaishouVideoDirectionalPackage kuaishouVideoDirectionalPackage) {
        Result<KuaishouVideoDirectionalPackage> result = new Result<KuaishouVideoDirectionalPackage>();
        KuaishouVideoDirectionalPackage kuaishouVideoDirectionalPackageEntity = kuaishouVideoDirectionalPackageService.getById(kuaishouVideoDirectionalPackage.getId());
        if (kuaishouVideoDirectionalPackageEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = kuaishouVideoDirectionalPackageService.updateById(kuaishouVideoDirectionalPackage);
            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 {
            kuaishouVideoDirectionalPackageService.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<KuaishouVideoDirectionalPackage> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<KuaishouVideoDirectionalPackage> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.kuaishouVideoDirectionalPackageService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "素材绑定的定向包模板-通过id查询", notes = "素材绑定的定向包模板-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<KuaishouVideoDirectionalPackage> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<KuaishouVideoDirectionalPackage> result = new Result<>();
        KuaishouVideoDirectionalPackage kuaishouVideoDirectionalPackage = kuaishouVideoDirectionalPackageService.getById(id);
        if (kuaishouVideoDirectionalPackage == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(kuaishouVideoDirectionalPackage);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 查询素材定向
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryDirctional")
    public Result<Object> queryDirctional(String id) {
        if (Check.isNull(id)) {
            return Result.error("缺失参数");
        }
        Result<KuaishouVideoDirectionalPackage> result = new Result<>();
        QueryWrapper<KuaishouVideoDirectionalPackage> advertiserQueryWrapper = new QueryWrapper<>();
        advertiserQueryWrapper.eq("video_get_id", id);
        advertiserQueryWrapper.last("limit 1");
        KuaishouVideoDirectionalPackage kuaishouVideoDirectionalPackage = kuaishouVideoDirectionalPackageService.getOne(advertiserQueryWrapper);
        if (kuaishouVideoDirectionalPackage == null) {
            return Result.ok("该素材未配置定向");
        } else {
            JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(kuaishouVideoDirectionalPackage)).toJavaObject(JSONObject.class);
            if (!Check.isNull(data.getString("keyword"))) {
                data.put("keyword", data.getJSONArray("keyword"));
            }
            return Result.ok(data);
        }
    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<KuaishouVideoDirectionalPackage> pageList = kuaishouVideoDirectionalPackageService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "素材绑定的定向包模板列表");
        mv.addObject(NormalExcelConstants.CLASS, KuaishouVideoDirectionalPackage.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<KuaishouVideoDirectionalPackage> listKuaishouVideoDirectionalPackages = ExcelImportUtil.importExcel(file.getInputStream(), KuaishouVideoDirectionalPackage.class, params);
                kuaishouVideoDirectionalPackageService.saveBatch(listKuaishouVideoDirectionalPackages);
                return Result.ok("文件导入成功！数据行数:" + listKuaishouVideoDirectionalPackages.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("文件导入失败！");
    }

}
