package com.yifu.cloud.plus.v1.yifu.archives.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TRiskMonitor;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TRiskMonitorMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TRiskMonitorService;
import com.yifu.cloud.plus.v1.yifu.archives.vo.RiskMonitorPerVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TRiskMonitorSearchVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TRiskMonitorVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ClientNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.DateUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.MenuUtil;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 风险管控统计
 *
 * @author huych
 * @date 2024-09-25 10:01:06
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class TRiskMonitorServiceImpl extends ServiceImpl<TRiskMonitorMapper, TRiskMonitor> implements TRiskMonitorService {

	private final MenuUtil menuUtil;

	/**
	 * 风险管控统计简单分页查询
	 *
	 * @param tRiskMonitor 风险管控统计
	 * @return
	 */
	@Override
	public IPage<TRiskMonitor> getTRiskMonitorPage(Page<TRiskMonitor> page, TRiskMonitorSearchVo tRiskMonitor) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1839501715787390978L;
		boolean isSsc =	this.haveRole(user, roleId);
		if (!isSsc) {
			menuUtil.setAuthSql(user, tRiskMonitor);
		}
		return baseMapper.getTRiskMonitorPage(page, tRiskMonitor);
	}

	/**
	 * 风险管控统计批量导出
	 * @param searchVo 风险管控统计
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TRiskMonitorSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1839501715787390978L;
		boolean isSsc =	this.haveRole(user, roleId);
		if (!isSsc) {
			menuUtil.setAuthSql(user, searchVo);
		}
		String fileName = "运营风险管控" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<TRiskMonitorVo> list = new ArrayList<>();
		//获取要导出的数量
		long count = baseMapper.getTRiskMonitorExportCount(searchVo);

		try(ServletOutputStream out = response.getOutputStream()) {

			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, CommonConstants.UTF8));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			ExcelWriter excelWriter = EasyExcel.write(out, TRiskMonitorVo.class).build();
			int index = 0;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT);
					list = baseMapper.getRiskMonitorExportList(searchVo);
					if (Common.isNotNull(list)) {
						WriteSheet writeSheet = EasyExcel.writerSheet("运营风险管控" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
					}
					if (Common.isNotNull(list)) {
						list.clear();
					}
				}
			} else {
				WriteSheet writeSheet = EasyExcel.writerSheet("运营风险管控" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}

	/**
	 * 风险管控统计批量生成
	 * @return
	 */
	@Override
	public void createRiskMonitor() {
		//批量删除之前生成的管控统计
		baseMapper.deleteAllRiskMonitorInfo();
		//批量生成统计数据
		List<TRiskMonitor> list = baseMapper.selectRiskMonitorList();
		if (!list.isEmpty()) {
			this.saveBatch(list);
		}
	}

	/**
	 * 查询风险占比
	 * @return
	 */
	@Override
	public R selectCurrentRiskMonitor(TRiskMonitorSearchVo tRiskMonitor) {
		YifuUser user = SecurityUtils.getUser();
		long roleId = 1839501715787390978L;
		boolean isSsc =	this.haveRole(user, roleId);
		if (!isSsc) {
			menuUtil.setAuthSql(user, tRiskMonitor);
		}
		RiskMonitorPerVo RiskMonitorPerVo = baseMapper.getTRiskMonitorPer(tRiskMonitor);
		return R.ok(RiskMonitorPerVo);
	}

	public boolean haveRole(YifuUser user, long roleId) {
		List<Long> roleList = user.getClientRoleMap().get(ClientNameConstants.CLIENT_MVP);
		for (Long role : roleList) {
			if (role == roleId) {
				return true;
			}
		}
		return false;
	}
}
