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

import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.service.IProjectService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouAppPackage;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouAppPackageRel;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouAppPackageRelService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouAppPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouMaterialPoolOperationRecordService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
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.aspect.annotation.AutoLog;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 项目绑定的应用
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-05-12
 */
@Slf4j
@Api(tags = "项目绑定的应用")
@RestController
@RequestMapping("/kuaishouAppPackage")
public class KuaishouAppPackageController {
    @Autowired
    private IKuaishouAppPackageService kuaishouAppPackageService;
    @Autowired
    private IKuaishouAppPackageRelService kuaishouAppPackageRelService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IKuaishouMaterialPoolOperationRecordService kuaishouMaterialPoolOperationRecordService;

    /**
     * 分页列表查询
     *
     * @param kuaishouAppPackage
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/list")
    public Result<Object> queryPageList(KuaishouAppPackage kuaishouAppPackage, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            return kuaishouAppPackageService.queryPageList(kuaishouAppPackage, pageNo, pageSize);
        } catch (Exception e) {
            log.error("查询应用列表异常", e);
        }
        return Result.error("查询应用列表失败");
    }

    @GetMapping(value = "/getProjectAppList")
    public Result<Object> getProjectAppList(Long projectId) {
        try {
            if (Check.isNull(projectId)) {
                return Result.error("缺少参数");
            }
            return kuaishouAppPackageService.getProjectAppList(projectId);
        } catch (Exception e) {
            log.error("查询项目下应用异常", e);
        }
        return Result.error("查询项目下应用失败");
    }

    @PostMapping(value = "/getAppsDetail")
    public Result<Object> getAppsDetail(@RequestBody JSONObject data) {
        try {
            String ids = data.getString("apptemIds");
            if (Check.isNull(ids)) {
                return Result.error("缺少参数");
            }
            List<Long> list = JSONObject.parseObject(ids, List.class);
            if (list.size() == 0) {
                return Result.error("缺少参数");
            }
            return kuaishouAppPackageService.getAppsDetail(list);
        } catch (Exception e) {
            log.error("查询项目下应用异常", e);
        }
        return Result.error("查询项目下应用失败");
    }

    @PostMapping(value = "/edit")
    public Result<Object> edit(@RequestBody JSONObject data) {
        String impressionUrl = data.getString("impressionUrl");
        String trackUrl = data.getString("trackUrl");
        String actionbarClickUrl = data.getString("actionbarClickUrl");
        String adPhotoPlayedT3sUrl = data.getString("adPhotoPlayedT3sUrl");

        if (Check.isNull(impressionUrl) && Check.isNull(actionbarClickUrl) && Check.isNull(adPhotoPlayedT3sUrl) && Check.isNull(trackUrl)) {
            return Result.error("缺少参数");
        }
        Long id = data.getLong("id");
        KuaishouAppPackageRel packageRel = kuaishouAppPackageRelService.getById(id);
        if (packageRel == null) {
            return Result.error("未找到对应实体");
        } else {
            boolean ok = false;
            if (!Check.isNull(impressionUrl) || !Check.isNull(actionbarClickUrl) || !Check.isNull(adPhotoPlayedT3sUrl)) {
                if (!Check.isNull(impressionUrl)) {
                    packageRel.setImpressionUrl(impressionUrl);
                }
                if (!Check.isNull(actionbarClickUrl)) {
                    packageRel.setActionbarClickUrl(actionbarClickUrl);
                }
                if (!Check.isNull(adPhotoPlayedT3sUrl)) {
                    packageRel.setAdPhotoPlayedT3sUrl(adPhotoPlayedT3sUrl);
                }
                ok = kuaishouAppPackageRelService.updateById(packageRel);
            }
            if (!Check.isNull(trackUrl)) {
                KuaishouAppPackage appTem = kuaishouAppPackageService.getById(packageRel.getApptemId());
                if (!Check.isNull(appTem)) {
                    appTem.setTrackUrl(trackUrl);
                    ok = kuaishouAppPackageService.updateById(appTem);
                }
            }
            if (ok) {
                return Result.ok("修改成功!");
            }
        }
        return Result.error("修改失败");
    }

    /**
     * 查询相关账户
     *
     * @param
     * @return org.jeecg.common.api.vo.Result<java.lang.Object>
     * @throws
     * @author ZHAOXA
     */
    @GetMapping(value = "/getRelatedAccounts")
    public Result<Object> getRelatedAccounts(Long id, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(id)) {
                return Result.error("缺少参数");
            }
            PageHelper.startPage(pageNo, pageSize);
            return kuaishouAppPackageService.getRelatedAccounts(id);
        } catch (Exception e) {
            log.error("查询异常", e);
        }
        return Result.error("查询失败");

    }

    /**
     * 查询相关组
     *
     * @param
     * @return org.jeecg.common.api.vo.Result<java.lang.Object>
     * @throws
     * @author ZHAOXA
     */
    @GetMapping(value = "/getRelatedGroups")
    public Result<Object> getRelatedGroups(Long id, Long accountId, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            if (Check.isNull(id)) {
                return Result.error("缺少参数");
            }
            PageHelper.startPage(pageNo, pageSize);
            return kuaishouAppPackageService.getRelatedGroups(id, accountId);
        } 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
     */
    @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 kuaishouAppPackageService.getAccountByProjectId(projectId, id);
        } catch (Exception e) {
            log.error("查询异常,", e.getMessage());
            e.printStackTrace();
        }
        return Result.error("查询失败");
    }

    /**
     * 推送应用
     *
     * @param
     * @return
     */
    @PostMapping(value = "/pushAppPackage")
    public Result<Object> pushAppPackage(@RequestBody JSONObject requestJson) {
        try {
            Long id = requestJson.getLong("id");
            JSONArray accountIds = requestJson.getJSONArray("accountIds");
            if (Check.isNull(id)) {
                return Result.error("请选择应用");
            }
            if (Check.isNull(accountIds)) {
                return Result.error("请选择推送账户");
            }
            Result<Object> result = kuaishouAppPackageService.pushAppPackage(id, accountIds, 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 kuaishouAppPackageService.queryPushResults(id, accountIds, null);
        } catch (Exception e) {
            log.error("查询推送结果异常", e);
        }
        return Result.error("查询失败");
    }

    /**
     * 查询推送历史
     *
     * @param
     * @return
     */
    @PostMapping(value = "/queryPushHistory")
    public Result<Object> queryPushHistory(@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 kuaishouAppPackageService.queryPushResults(id, accountIds, requestJson.getString("status"));
        } catch (Exception e) {
            log.error("查询推送历史异常", e);
        }
        return Result.error("查询失败");
    }

    /**
     * 添加——填写链接
     *
     * @param kuaishouAppPackage
     * @return
     */
    @PostMapping(value = "/fillInLink")
    public Result<Object> fillInLink(@RequestBody KuaishouAppPackage kuaishouAppPackage) {
        try {
            Integer platform = kuaishouAppPackage.getPlatform();
            if (Check.isNull(platform)) {
                return Result.error("请选择应用类型");
            }
            if (platform == 1 || platform == 2) {
                if (Check.isNull(kuaishouAppPackage.getProjectId())) {
                    return Result.error("请选择项目");
                } else if (Check.isNull(kuaishouAppPackage.getAppVersion())) {
                    return Result.error("请填写应用标记");
                } else if (Check.isNull(kuaishouAppPackage.getAppName())) {
                    return Result.error("请填写应用名称");
                } else if (Check.isNull(kuaishouAppPackage.getAppPrivacyUrl())) {
                    return Result.error("安卓类应用隐私政策url不为空");
                } else {
                    if (platform == 1 && Check.isNull(kuaishouAppPackage.getAppIconUrl())) {
                        return Result.error("请上传图标");
                    }
                    if (platform == 1 && Check.isNull(kuaishouAppPackage.getPackageName())) {
                        return Result.error("请填写应用包名");
                    }
                }
            } else {
                if (Check.isNull(kuaishouAppPackage.getAppName())) {
                    return Result.error("请填写应用名称");
                } else if (Check.isNull(kuaishouAppPackage.getAppVersion())) {
                    return Result.error("请填写应用标记");
                } else if (Check.isNull(kuaishouAppPackage.getUrl())) {
                    return Result.error("请填写链接");
                } else if (Check.isNull(kuaishouAppPackage.getProjectId())) {
                    return Result.error("请选择项目");
                } else if (platform == 3 && Check.isNull(kuaishouAppPackage.getAppIconUrl())) {
                    return Result.error("请上传图标");
                }
            }
            if (!kuaishouAppPackage.getAppIconUrl().contains("http")) {
                kuaishouAppPackage.setAppIconUrl("https:".concat(kuaishouAppPackage.getAppIconUrl()));
            }

            String newFileUrl = kuaishouAppPackageService.getDownloadPath(kuaishouAppPackage.getAppIconUrl());
            if (Check.isNull(newFileUrl)) {
                return Result.error("本地下载文件失败，路径：" + kuaishouAppPackage.getAppIconUrl());
            }
            kuaishouAppPackage.setImageMd5(LoadFileUtil.getMD5(newFileUrl));
            kuaishouAppPackage.setDataStatus(1);//有效
            String type = "update";
            if (Check.isNull(kuaishouAppPackage.getId())) {
                type = "add";
            }
            kuaishouAppPackageService.saveOrUpdate(kuaishouAppPackage);
            kuaishouMaterialPoolOperationRecordService.addRecord(JSONObject.parseObject(JSONObject.toJSONString(kuaishouAppPackage)).toJavaObject(JSONObject.class), "/fillInLink", 3, type);
            return Result.ok("操作成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("操作失败");
    }

    /**
     * 校验应用标记
     *
     */
    @GetMapping(value = "/checkAppVersion")
    public Result<Object> checkAppVersion(Long projectId, String appVersion, Long id) {
        try {
            if (Check.isNull(projectId) || Check.isNull(appVersion)) {
                return Result.error("缺失参数");
            }
            List<Long> list = kuaishouAppPackageService.queryByAppVersion(projectId, appVersion, null);
            if (Check.isNull(list)) {
                return Result.ok("success");
            } else {
                //修改校验
                if (!Check.isNull(id) && (list.size() == 1 && list.get(0) - id == 0)) {
                    return Result.ok("success");
                }
                return Result.error("重复的应用标记");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("操作失败");
    }

    /**
     * 逻辑删除，修改模板状态
     *
     * @param kuaishouAppPackage
     * @return
     */
    @PostMapping(value = "/delete")
    public Result<KuaishouAppPackage> delete(@RequestBody KuaishouAppPackage kuaishouAppPackage) {
        Result<KuaishouAppPackage> result = new Result<KuaishouAppPackage>();
        KuaishouAppPackage kuaishouAppPackageEntity = kuaishouAppPackageService.getById(kuaishouAppPackage.getId());
        if (kuaishouAppPackageEntity == null) {
            result.error500("未找到对应实体");
        } else {
            kuaishouAppPackage.setDataStatus(0);
            boolean ok = kuaishouAppPackageService.updateById(kuaishouAppPackage);
            if (ok) {
                JSONObject data = new JSONObject();
                data.put("id", kuaishouAppPackage.getId());
                data.put("projectId", kuaishouAppPackageEntity.getProjectId());
                kuaishouMaterialPoolOperationRecordService.addRecord(data, "/kuaishouAppPackage/delete", 3, "delete");
                result.success("刪除成功!");
            }
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目绑定的应用-通过id删除")
    @ApiOperation(value = "项目绑定的应用-通过id删除", notes = "项目绑定的应用-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            kuaishouAppPackageService.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<KuaishouAppPackage> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<KuaishouAppPackage> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.kuaishouAppPackageService.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<KuaishouAppPackage> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<KuaishouAppPackage> result = new Result<>();
        KuaishouAppPackage kuaishouAppPackage = kuaishouAppPackageService.getById(id);
        if (kuaishouAppPackage == null) {
            result.error500("未找到对应实体");
        } else {
            Project project = projectService.getById(kuaishouAppPackage.getProjectId());
            if (!Check.isNull(project)) {
                kuaishouAppPackage.setProjectName(project.getProjectName());
            }
            result.setResult(kuaishouAppPackage);
            result.setSuccess(true);
        }
        return result;
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//            response.setContentType("multipart/form-data;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 导出应用模板
     */
    @GetMapping("/exportAppTemplate")
    public void getExcel(HttpServletResponse response) {
        try {
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            String[] titles = {"应用名称", "应用包名", "应用标记", "隐私政策链接", "下载链接", "监测链接", "是否接入广告监测sdk（0否 1 是）"};
            eeu.exportExcelForAttendance(workbook, 0, "Sheet1", titles, new ArrayList<>());
            this.setResponseHeader(response, "应用模板.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }


    /**
     * 导入应用程序excel
     *
     * @param
     * @return org.jeecg.common.api.vo.Result<java.lang.Object>
     * @throws
     * @author ZHAOXA
     */
    @PostMapping(value = "/importAppExcel")
    @ResponseBody
    public Result<Object> importExcel(HttpServletResponse response,
                                      @RequestParam("file") MultipartFile file,
                                      @RequestParam("projectId") Long projectId,
                                      @RequestParam("platform") Integer platform,
                                      @RequestParam("imageUrl") String imageUrl) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        try {
            if (Check.isNull(platform)) {
                return Result.error("请选择应用类型");
            }
            if (Check.isNull(file)) {
                return Result.error("执行失败，请上传应用Excel文件");
            } else if (Check.isNull(projectId)) {
                return Result.error("请选择项目");
            } else if ((platform == 1 || platform == 3) && Check.isNull(imageUrl)) {
                return Result.error("请上传图标");
            }
            if (!imageUrl.contains("http")) {
                imageUrl = "https:".concat(imageUrl);
            }
            return kuaishouAppPackageService.importExcel(file, projectId, platform, imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析应用Excel文档异常", e);
            return Result.error("解析应用Excel文档失败，" + e.getMessage());
        }
    }

}
