/*
 *
 *      Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: hnqz
 *
 */

package com.qunzhixinxi.hnqz.admin.controller;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qunzhixinxi.hnqz.admin.api.entity.SysDept;
import com.qunzhixinxi.hnqz.admin.config.UpmsConfig;
import com.qunzhixinxi.hnqz.admin.entity.WmReport;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.entity.input.WmPackageExportApiInput;
import com.qunzhixinxi.hnqz.admin.enums.ReportEnum;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.common.core.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 报告审核导出
 * </p>
 *
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/reportExport")
@Api(value = "reportExport", tags = "导出管理模块")
public class ReportExportController {

	private final WmTaskService wmTaskService;

	private final WmScorePackageService wmScorePackageService;

	private final WmReportService wmReportService;

	private final ReportExportService reportExportService;

	private final SysDeptService sysDeptService;

	private final JavaMailSender sender;

	private final UpmsConfig upmsConfig;



	/**
	 * 报告导出--个人报告导出分页查询
	 *
	 * @param page           分页对象
	 * @param wmScorePackage 积分包
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getExportPackageZbTotalList")
	public R getExportPackageZbTotalList(Page page, WmScorePackage wmScorePackage) {
		return reportExportService.getExportPackageZbTotalList(page,wmScorePackage);
	}

	/**
	 * 报告导出--查看任务
	 *
	 * @param page           分页对象
	 * @param wmTask
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/getExportPackageZbTaskList")
	public R getExportPackageZbTaskList(Page page, WmTask wmTask) {
		if(StringUtil.isEmpty(wmTask.getScorePackageId())){
			return R.failed("积分包ID不能为空");
		}
		return reportExportService.getExportPackageZbTaskList(page,wmTask);
	}




	/**
	 * 结算报告管理--导出汇总或详情
	 * @param wmReport
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/exportNbReport")
	public R exportNbReport(WmReport wmReport ) throws IOException {
		wmReport=wmReportService.getById(wmReport.getId());
		List<WmTask> taskList=new ArrayList<>();//该报告关联的所有未提交的任务
		//更新任务表审批意见
		WmScorePackage scorePackage=wmScorePackageService.getById(wmReport.getScoreId());
		WmTask wmTask=new WmTask();
		wmTask.setDelFlag("0");
		wmTask.setEnableFlag("0");
		wmTask.setRealFlag("0");

		SysDept sysDept = sysDeptService.getById(scorePackage.getSendPackageDeptId());


		if("0".equals(scorePackage.getTypeid())){//药企
			wmTask.setReportDrugId(wmReport.getId());
			wmTask.setReportDrugApprovalOpinion(ReportEnum.APPROVAL_OPINION_YES.getType());//审核通过的状态
			taskList=wmTaskService.list(Wrappers.query(wmTask));
		}else if("1".equals(scorePackage.getTypeid())){//一级代理商类型
			wmTask.setReportOneId(wmReport.getId());
			if(sysDept.getLevel() == 2){
				wmTask.setReportDrugApprovalOpinion(ReportEnum.APPROVAL_OPINION_YES.getType());//审核通过的状态
			}else {
				wmTask.setReportOneApprovalOpinion(ReportEnum.APPROVAL_OPINION_YES.getType());//审核通过的状态
			}

			taskList=wmTaskService.list(Wrappers.query(wmTask));
		}else if("2".equals(scorePackage.getTypeid())){//二级代理商类型
			wmTask.setReportSecondId(wmReport.getId());
			wmTask.setReportSecondApprovalOpinion(ReportEnum.APPROVAL_OPINION_YES.getType());//审核通过的状态
			taskList=wmTaskService.list(Wrappers.query(wmTask));
		}
		if(null==taskList||taskList.size()<=0){
			return R.failed("未查询到该报告关联的审批通过的任务");
		}
		String ids = taskList.stream().map(WmTask::getId).collect(Collectors.joining("," ));
		wmTask.setScorePackageId(wmReport.getScoreId().toString());
		wmTask.setId(ids);

			return reportExportService.exportNb(wmTask,wmReport);//报告汇总


	}



	/**
	 * 个人报告导出--导出汇总或详情  汇总和详情合为一个模版
	 * @param wmTask
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/exportZbReport")
	public R exportZbReport(WmTask wmTask) throws IOException {
		String packageId=wmTask.getScorePackageDrugId();
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}
		LambdaQueryWrapper<WmTask> queryWrapper=new LambdaQueryWrapper();
		queryWrapper.in(WmTask::getScorePackageId, Arrays.asList(packageId.split(",")));
		queryWrapper.eq(WmTask::getTaskStatus,"3");
		queryWrapper.eq(WmTask::getDelFlag,"0");
		queryWrapper.eq(WmTask::getEnableFlag,"0");
		queryWrapper.eq(WmTask::getRealFlag,"0");
		List<WmTask> taskList=wmTaskService.list(queryWrapper);
		if(taskList.isEmpty()){
			return R.failed("未查询到审核通过的任务");
		}
		String ids = taskList.stream().map(WmTask::getId).collect(Collectors.joining("," ));
		wmTask.setScorePackageId(packageId);
		wmTask.setId(ids);

		return reportExportService.exportZb(wmTask);//报告汇总


	}

	/**
	 * 个人报告导出--导出汇总或详情  汇总和详情合为一个模版
	 * @param packageId 积分包id
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/exportHCPReport")
	public R exportHCPReport(String packageId) throws IOException {
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}

		return reportExportService.exportHCP(packageId);
	}

	/**
	 * 个人报告导出--导出汇总或详情  汇总和详情合为一个模版
	 * @param input
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/exportZbInfoFormWeiNew")
	public R exportZbInfoFormWeiNew(WmPackageExportApiInput input) {
		String packageId=input.getId();
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}
		LambdaQueryWrapper<WmTask> queryWrapper=new LambdaQueryWrapper();
		queryWrapper.in(WmTask::getScorePackageId, Arrays.asList(packageId.split(",")));
		queryWrapper.eq(WmTask::getTaskStatus,"3");
		queryWrapper.eq(WmTask::getDelFlag,"0");
		queryWrapper.eq(WmTask::getEnableFlag,"0");
		queryWrapper.eq(WmTask::getRealFlag,"0");
		List<WmTask> taskList=wmTaskService.list(queryWrapper);
		if(taskList.isEmpty()){
			return R.failed("未查询到审核通过的任务");
		}
		String ids = taskList.stream().map(WmTask::getId).collect(Collectors.joining("," ));

		WmTask wmTask = new WmTask();
		wmTask.setScorePackageId(packageId);
		wmTask.setId(ids);

//		return reportExportService.exportZb(wmTask);//报告汇总

		R r = R.ok();
		try {
			r = reportExportService.exportZb(wmTask);//报告汇总

			if (r.getCode() == 0) {
				log.info("文件生成成功");
			} else {
				return r;
			}
			Map<String, String> resultMap = (Map<String, String>) r.getData();

			MimeMessage mail = sender.createMimeMessage();
			try {

				MimeMessageHelper helper = new MimeMessageHelper(mail, true);

				helper.setFrom(upmsConfig.getFormMail());
				helper.setTo(input.getEmail());

				helper.setSubject("要易云平台学术信息沟通专员业绩报告");

				helper.setText("要易云平台学术信息沟通专员业绩报告","尊敬的学术信息沟通专员：" +
				"<br/>&nbsp;&nbsp;&nbsp;&nbsp;感谢您使用要易平台，下载业绩报告请<a href=" + resultMap.get("url") + ">点击链接</a >");
				/**
				 * 附件
				 */
//				helper.addAttachment("众包代表业绩报告明细", multipartFile);

				sender.send(mail);
			} catch (MessagingException ex) {
				log.error("邮件发送失败");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return R.failed();
		}
		return r;


	}





	/**
	 * 个人报告导出--导出汇总或详情
	 * @param wmTask
	 *@param exportType  1 导出汇总  2导出详情
	 * @return
	 * @throws IOException
	 */
//	@GetMapping("/exportZbReport")
//	public R exportZbReport(WmTask wmTask, String exportType) throws IOException {
//		String packageId=wmTask.getScorePackageDrugId();
//		if (null == packageId) {
//			return R.failed("积分包ID不能为空");
//		}
//		LambdaQueryWrapper<WmTask> queryWrapper=new LambdaQueryWrapper();
//		queryWrapper.in(WmTask::getScorePackageId, Arrays.asList(packageId.split(",")));
//		queryWrapper.eq(WmTask::getTaskStatus,"3");
//		queryWrapper.eq(WmTask::getDelFlag,"0");
//		queryWrapper.eq(WmTask::getEnableFlag,"0");
//		List<WmTask> taskList=wmTaskService.list(queryWrapper);
//		if(taskList.isEmpty()){
//			return R.failed("未查询到审核通过的任务");
//		}
//		String ids = taskList.stream().map(WmTask::getId).collect(Collectors.joining("," ));
//		wmTask.setScorePackageId(packageId);
//		wmTask.setId(ids);
//
//		if("1".equals(exportType)){
//			return reportExportService.exportZb(wmTask);//报告汇总
//		}else  if("2".equals(exportType)){
//			return reportExportService.exportZbInfo(wmTask);
//		}else {
//			return R.failed("参数类型不对");
//		}
//
//	}



	/**
	 * 结算包-报告导出--导出汇总或详情
	 * @param wmTask
	 *@param exportType  1 导出汇总  2导出详情
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/exportZbInfoJs")
	public R exportZbInfoJs(WmTask wmTask, String exportType) throws IOException {
		String packageId=wmTask.getScorePackageDrugId();
		if (null == packageId) {
			return R.failed("积分包ID不能为空");
		}
		LambdaQueryWrapper<WmTask> queryWrapper=new LambdaQueryWrapper();
		queryWrapper.in(WmTask::getScorePackageId, Arrays.asList(packageId.split(",")));
		queryWrapper.eq(WmTask::getTaskStatus,"3");
		queryWrapper.eq(WmTask::getDelFlag,"0");
		queryWrapper.eq(WmTask::getEnableFlag,"0");
		List<WmTask> taskList=wmTaskService.list(queryWrapper);
		if(taskList.isEmpty()){
			return R.failed("未查询到审核通过的任务");
		}
		String ids = taskList.stream().map(WmTask::getId).collect(Collectors.joining("," ));
		wmTask.setScorePackageId(packageId);
		wmTask.setId(ids);

		//if("1".equals(exportType)){
			return reportExportService.exportZbJs(wmTask);//报告汇总
//		}else  if("2".equals(exportType)){
//			return reportExportService.exportZbInfoJs(wmTask);
//		}else {
//			return R.failed("参数类型不对");
//		}

	}


	/**
	 * 历史数据导出报告
	 * @param wmScorePackage
	 * @return
	 * @throws IOException
	 */
	@GetMapping("/exportNbaHistory")
	public R exportNbaHistory(WmScorePackage wmScorePackage) throws IOException {
		wmScorePackage=wmScorePackageService.getById(wmScorePackage.getId());
		if(wmScorePackage==null){
			return R.failed("未查询到积分包信息");
		}
		LambdaQueryWrapper<WmTask> queryWrapper=new LambdaQueryWrapper();
		queryWrapper.eq(WmTask::getScorePackageDrugId, wmScorePackage.getId());
		queryWrapper.eq(WmTask::getTaskStatus,"3");
		queryWrapper.eq(WmTask::getDelFlag,"0");
		queryWrapper.eq(WmTask::getEnableFlag,"0");
		queryWrapper.eq(WmTask::getRealFlag,"0");
		List<WmTask> taskList=wmTaskService.list(queryWrapper);
		//List<WmTask> taskList = wmTaskMapper.selectListByWmTask(wmScorePackage);
		//更新任务表审批意见
		WmTask wmTask=new WmTask();
		wmTask.setDelFlag("0");
		wmTask.setEnableFlag("0");

		if(null==taskList||taskList.size()<=0){
			return R.failed("未查询到该报告关联的审批通过的任务");
		}
		String ids = taskList.stream().map(WmTask::getId).collect(Collectors.joining("," ));
		wmTask.setScorePackageId(wmScorePackage.getId());
		//wmTask.setId(ids);
		wmTask.setId("(select id from wm_task where del_flag=0 and real_flag=0 and enable_flag=0 and task_status=3  and score_package_drug_id="+wmScorePackage.getId()+")");

		return reportExportService.exportNba(wmTask,wmScorePackage);//报告汇总


	}


}
