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

import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouDirectionalPackage;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouMaterialPoolOperationRecordService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
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-04-20
 */
@Slf4j
@Api(tags = "自动投放-定向包详情")
@RestController
@RequestMapping("/kuaishouDirectionalPackage")
public class KuaishouDirectionalPackageController {
    @Autowired
    private IKuaishouDirectionalPackageService kuaishouDirectionalPackageService;

    @Autowired
    private IKuaishouMaterialPoolOperationRecordService kuaishouMaterialPoolOperationRecordService;

    @Autowired
    private ICtopOauthTokenService oauthTokenService;

    /**
     * 查询定向包列表
     *
     * @param
     * @return org.jeecg.common.api.vo.Result<java.lang.Object>
     * @throws
     * @author ZHAOXA
     */
    @GetMapping(value = "/queryList")
    public Result<Object> queryList(KuaishouDirectionalPackage directionalPackage,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            return kuaishouDirectionalPackageService.queryList(directionalPackage, pageNo, pageSize);
        } catch (Exception e) {
            log.error("查询异常,", e);
            return Result.error("查询失败，" + e.getMessage());
        }

    }

    @GetMapping(value = "/getProjectTarget")
    public Result<Object> getProjectTarget(Long projectId, String templateName,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(projectId)) {
                return Result.error("缺少参数");
            }
            return kuaishouDirectionalPackageService.getProjectTarget(projectId, templateName, pageNo, pageSize);
        } catch (Exception e) {
            log.error("查询异常,", e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @PostMapping(value = "/getProjectTargetByIds")
    public Result<Object> getProjectTargetByIds(@RequestBody JSONObject data) {
        try {
            JSONArray ids = data.getJSONArray("ids");
            if (Check.isNull(ids)) {
                return Result.error("缺少参数");
            }
            List<String> list = JSONObject.parseObject(JSONObject.toJSONString(ids), List.class);
            if (Check.isNull(list)) {
                return Result.error("缺少参数");
            }


            List<KuaishouDirectionalPackage> targets = kuaishouDirectionalPackageService.getProjectTargetByIds(list);
            return Result.ok(targets);
        } catch (Exception e) {
            log.error("查询异常,", e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    /**
     * 相关账户/组
     *
     * @param projectId 账户ID
     * @param type      1是账户，2是组维度
     * @return org.jeecg.common.api.vo.Result<java.lang.Object>
     * @throws
     * @author ZHAOXA
     */
    @GetMapping(value = "/getRelatedAccountGroup")
    public Result<Object> getRelatedAccountGroup(String id, Integer type, Long accountId, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(id)) {
                return Result.error("请选择定向包");
            }
            if (Check.isNull(type)) {
                return Result.error("请选择查询类型");
            }
            return kuaishouDirectionalPackageService.getRelatedAccountGroup(id, type, accountId, pageNo, pageSize);
        } catch (Exception e) {
            log.error("查询异常,", e);
            return Result.error("查询失败");
        }

    }

    /**
     * 编辑定向包
     *
     * @param projectId 账户ID
     * @return org.jeecg.common.api.vo.Result<java.lang.Object>
     * @throws
     * @author ZHAOXA
     */
    @PostMapping(value = "/editPopulation")
    public Result<Object> editPopulation(@RequestBody JSONObject requestJson) {
        try {
            if (Check.isNull(requestJson.getString("id"))) {
                return Result.error("请选择定向包");
            }
            if (Check.isNull(requestJson.getLong("accountId"))) {
                return Result.error("请选择账户");
            }
            if (Check.isNull(requestJson.getLong("templateId"))) {
                return Result.error("未获取到定向包ID");
            }
            if (Check.isNull(requestJson.getString("templateName"))) {
                return Result.error("未获取到定向包名称");
            }
            Result<Object> result = kuaishouDirectionalPackageService.editPopulation(requestJson);
            if (result.getCode() == 200) {
                kuaishouMaterialPoolOperationRecordService.addRecord(requestJson, "/editPopulation", 1, "update");
            }
            return result;
        } catch (Exception e) {
            log.error("查询异常,", e.getMessage());
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    /**
     * 查询项目下有效账户
     *
     * @param projectId 账户ID
     * @return org.jeecg.common.api.vo.Result<java.lang.Object>
     * @throws
     * @author ZHAOXA
     */
    @GetMapping(value = "/getAccountByProjectId")
    public Result<Object> getAccountByProjectId(Long projectId, String id,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(projectId)) {
                return Result.error("请选择项目");
            }
            if (Check.isNull(id)) {
                return Result.error("请选择定向包");
            }
            PageHelper.startPage(pageNo, pageSize);
            return kuaishouDirectionalPackageService.getAccountByProjectId(projectId, id);
        } catch (Exception e) {
            log.error("查询异常,", e.getMessage());
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    /**
     * 创建定向包
     *
     * @param
     * @return
     */
    @PostMapping(value = "/createDirectionalPackage")
    public Result<Object> createDirectionalPackage(@RequestBody JSONObject requestJson) {
        try {
            if (Check.isNull(requestJson.getString("templateName"))) {
                return Result.error("定向模板名称为必传项");
            }
            Long accountId = requestJson.getLong("projectId");
            if (Check.isNull(accountId)) {
                return Result.error("请选择账户id");
            }
            Result<Object> result = kuaishouDirectionalPackageService.createDirectionalPackage(requestJson);
            if (result.getCode() == 200) {
                kuaishouMaterialPoolOperationRecordService.addRecord(requestJson, "/createDirectionalPackage", 1, "add");
            }
            return result;
        } catch (Exception e) {
            log.error("创建定向包失败", e);
            return Result.error("创建失败" + e.getMessage());
        }
    }

    /**
     * 修改定向包
     *
     * @param
     * @return
     */
    @PostMapping(value = "/updateDirectionalPackage")
    public Result<Object> updateDirectionalPackage(@RequestBody JSONObject requestJson) {
        Result<JSONObject> result = new Result<>();
        try {
            if (Check.isNull(requestJson.getString("id"))) {
                return Result.error("请选择定向包");
            }
            if (Check.isNull(requestJson.getString("projectId"))) {
                return Result.error("请选择项目");
            }
            Result<Object> result1 = kuaishouDirectionalPackageService.updateDirectionalPackage(requestJson);
            if (result1.getCode() == 200) {
                kuaishouMaterialPoolOperationRecordService.addRecord(requestJson, "/updateDirectionalPackage", 1, "update");
            }
            return result1;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
        }
        return Result.error("上传失败");
    }

    /**
     * 推送定向包
     *
     * @param
     * @return
     */
    @PostMapping(value = "/pushDirectionalPackage")
    public Result<Object> pushDirectionalPackage(@RequestBody JSONObject requestJson) {
        try {
            String id = requestJson.getString("id");
            JSONArray datas = requestJson.getJSONArray("datas");
            if (Check.isNull(id)) {
                return Result.error("请选择定向包");
            }
            if (Check.isNull(datas)) {
                return Result.error("请选择推送账户");
            }
            Result<Object> result = kuaishouDirectionalPackageService.pushDirectionalPackage(id, datas, requestJson);
            return result;
        } catch (Exception e) {
            log.error("推送定向包异常", e);
        }
        return Result.error("推送失败");
    }

    /**
     * 查询推送结果
     *
     * @param
     * @return
     */
    @PostMapping(value = "/queryPushResults")
    public Result<Object> queryPushResults(@RequestBody JSONObject requestJson) {
        try {
            String id = requestJson.getString("id");
            JSONArray accountIds = requestJson.getJSONArray("accountIds");
            if (Check.isNull(id)) {
                return Result.error("请选择定向包");
            }
            Integer pageNo = requestJson.getInteger("pageNo");
            Integer pageSize = requestJson.getInteger("pageSize");
            if (Check.isNull(pageNo)) {
                pageNo = 1;
            }
            if (Check.isNull(pageSize)) {
                pageSize = 10;
            }
            PageHelper.startPage(pageNo, pageSize);
            return kuaishouDirectionalPackageService.queryPushResults(id, accountIds, requestJson.getString("status"));
        } catch (Exception e) {
            log.error("查询推送结果异常", e);
        }
        return Result.error("查询失败");
    }

    /**
     * 删除定向模板
     *
     * @param
     * @return org.jeecg.common.api.vo.Result<?>
     * @throws
     * @author ZHAOXA
     */
    @GetMapping(value = "/delete")
    public Result<Object> delete(String id) {
        try {

            KuaishouDirectionalPackage directionalPackage = kuaishouDirectionalPackageService.getById(id);
            if (Check.isNull(directionalPackage)) {
                return Result.error("未查到实体");
            }
            boolean b = kuaishouDirectionalPackageService.removeById(id);
            if (b) {
                JSONObject data = new JSONObject();
                data.put("id", id);
                data.put("projectId", directionalPackage.getProjectId());
                kuaishouMaterialPoolOperationRecordService.addRecord(data, "/kuaishouDirectionalPackage/delete", 1, "delete");
                return Result.ok("删除成功");
            }
        } catch (Exception e) {
            log.error("删除异常", e);
        }
        return Result.error("删除失败!");
    }

    /**
     * 添加
     *
     * @param kuaishouDirectionalPackage
     * @return
     */
    @AutoLog(value = "自动投放-定向包详情-添加")
    @ApiOperation(value = "自动投放-定向包详情-添加", notes = "自动投放-定向包详情-添加")
    @PostMapping(value = "/add")
    public Result<KuaishouDirectionalPackage> add(@RequestBody KuaishouDirectionalPackage kuaishouDirectionalPackage) {
        Result<KuaishouDirectionalPackage> result = new Result<>();
        try {
            kuaishouDirectionalPackageService.save(kuaishouDirectionalPackage);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param kuaishouDirectionalPackage
     * @return
     */
    @AutoLog(value = "自动投放-定向包详情-编辑")
    @ApiOperation(value = "自动投放-定向包详情-编辑", notes = "自动投放-定向包详情-编辑")
    @PutMapping(value = "/edit")
    public Result<KuaishouDirectionalPackage> edit(@RequestBody KuaishouDirectionalPackage kuaishouDirectionalPackage) {
        Result<KuaishouDirectionalPackage> result = new Result<KuaishouDirectionalPackage>();
        KuaishouDirectionalPackage kuaishouDirectionalPackageEntity = kuaishouDirectionalPackageService.getById(kuaishouDirectionalPackage.getId());
        if (kuaishouDirectionalPackageEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = kuaishouDirectionalPackageService.updateById(kuaishouDirectionalPackage);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "自动投放-定向包详情-批量删除")
    @ApiOperation(value = "自动投放-定向包详情-批量删除", notes = "自动投放-定向包详情-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<KuaishouDirectionalPackage> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<KuaishouDirectionalPackage> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.kuaishouDirectionalPackageService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 查询待修改的定向包
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<Object> queryById(@RequestParam(name = "id", required = true) String id) {
        KuaishouDirectionalPackage kuaishouDirectionalPackage = kuaishouDirectionalPackageService.getById(id);
        if (kuaishouDirectionalPackage == null) {
            return Result.error("未找到对应实体");
        } else {
            JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(kuaishouDirectionalPackage)).toJavaObject(JSONObject.class);
            if (!Check.isNull(data.getString("keyword"))) {
                data.put("keyword", data.getJSONArray("keyword"));
            }
            return Result.ok(data);
        }
    }

    /**
     * 查询待修改的定向包
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryPopulationById")
    public Result<Object> queryPopulationById(Long templateId, Long accountId) {
        try {
            if (Check.isNull(templateId) || Check.isNull(accountId)) {
                return Result.error("缺少参数");
            }
            return kuaishouDirectionalPackageService.queryPopulationById(templateId, accountId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("查询失败");

    }

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

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<KuaishouDirectionalPackage> pageList = kuaishouDirectionalPackageService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "自动投放-定向包详情列表");
        mv.addObject(NormalExcelConstants.CLASS, KuaishouDirectionalPackage.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<KuaishouDirectionalPackage> listKuaishouDirectionalPackages = ExcelImportUtil.importExcel(file.getInputStream(), KuaishouDirectionalPackage.class, params);
                kuaishouDirectionalPackageService.saveBatch(listKuaishouDirectionalPackages);
                return Result.ok("文件导入成功！数据行数:" + listKuaishouDirectionalPackages.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("文件导入失败！");
    }

}
