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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
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.permission.mapper.SysUserPermissionMapper;
import com.yifu.cloud.plus.v1.permission.service.SysUserPermissionService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.permission.entity.SysUserPermission;
import com.yifu.cloud.plus.v1.yifu.permission.vo.SysDictVo;
import com.yifu.cloud.plus.v1.yifu.permission.vo.SysUserDeptVo;
import com.yifu.cloud.plus.v1.yifu.permission.vo.SysUserPermissionSearchVo;
import com.yifu.cloud.plus.v1.yifu.permission.vo.SysUserPermissionVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

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

@Log4j2
@Service
public class SysUserPermissionServiceImpl extends ServiceImpl<SysUserPermissionMapper, SysUserPermission> implements SysUserPermissionService {

	/**
	 * 新权限-用户权限表简单分页查询
	 *
	 * @param sysUserPermission 新权限-用户权限表
	 * @return
	 */
	@Override
	public IPage<SysUserPermission> getSysUserPermissionPage(Page<SysUserPermission> page, SysUserPermissionSearchVo sysUserPermission) {
		return baseMapper.getSysUserPermissionPage(page, sysUserPermission);
	}

	/**
	 * 新权限-用户权限表批量导出
	 *
	 * @param searchVo 新权限-用户权限表
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, SysUserPermissionSearchVo searchVo) {
		String fileName = "用户权限表批量导出" + DateUtil.getThisTime() + ".xlsx";
		//获取要导出的列表
		List<SysUserPermissionVo> list = new ArrayList<>();
		long count = baseMapper.userSelectCount(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, SysUserPermissionVo.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.userSelectList(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();
			}
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		}
	}

	@Override
	public IPage<SysUserDeptVo> getNameCodePage(Page<SysUserDeptVo> page, SysUserDeptVo searchVo) {
		if (Common.isNotNull(searchVo) && Common.isNotNull(searchVo.getType())) {
			YifuUser user = SecurityUtils.getUser();
			IPage<SysUserDeptVo> iPage;
			//客户权限
			if (CommonConstants.ONE_STRING.equals(searchVo.getType())) {
				iPage = baseMapper.selectUnitVO(page,searchVo.getName());
			} else if (CommonConstants.TWO_STRING.equals(searchVo.getType())) {
				//商机权限
				iPage = baseMapper.selectBusinessVO(page, searchVo.getName());
			} else if (CommonConstants.THREE_STRING.equals(searchVo.getType())) {
				//报价单权限
				iPage = baseMapper.selectQuotationVO(page, searchVo.getName());
			} else if (CommonConstants.FOUR_STRING.equals(searchVo.getType())) {
				//合同权限
				if (CommonConstants.ONE_STRING.equals(user.getId())) {
					iPage = baseMapper.selectContractVO(page, searchVo.getName());
				} else {
					iPage = baseMapper.selectContractSimpleVO(page, searchVo.getName(),searchVo.getName(),searchVo.getType());
				}
			} else if (CommonConstants.EIGHT_STRING.equals(searchVo.getType()) || CommonConstants.NINE_STRING.equals(searchVo.getType())) {
				//部门&&收入归属权限
				iPage = baseMapper.selectDeptVO(page, searchVo.getName());
			} else {
				//项目权限
				if (CommonConstants.ONE_STRING.equals(user.getId())) {
					iPage = baseMapper.selectSettleVO(page, searchVo.getName());
				} else {
					iPage = baseMapper.selectContractSimpleVO(page, searchVo.getName(),searchVo.getName(),searchVo.getType());
				}
			}
			return iPage;
		}
		return null;
	}

	@Override
	public List<SysDictVo> selectDictByType(String type) {
		return baseMapper.selectDictByType(type);
	}

	@Override
	public R<List<ErrorMessage>> importDiy(InputStream inputStream) {
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		ExcelUtil<SysUserPermissionVo> util1 = new ExcelUtil<>(SysUserPermissionVo.class);
		// 写法2：
		// 匿名内部类 不用额外写一个DemoDataListener
		// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
		try {
			EasyExcel.read(inputStream, SysUserPermissionVo.class, new ReadListener<SysUserPermissionVo>() {
				/**
				 * 单次缓存的数据量
				 */
				public static final int BATCH_COUNT = CommonConstants.BATCH_COUNT;
				/**
				 *临时存储
				 */
				private List<SysUserPermissionVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

				@Override
				public void invoke(SysUserPermissionVo data, AnalysisContext context) {
					ReadRowHolder readRowHolder = context.readRowHolder();
					Integer rowIndex = readRowHolder.getRowIndex();
					data.setRowIndex(rowIndex + 1);
					ErrorMessage errorMessage = util1.checkEntity(data, data.getRowIndex());
					if (Common.isNotNull(errorMessage)) {
						errorMessageList.add(errorMessage);
					} else {
						cachedDataList.add(data);
					}
					if (cachedDataList.size() >= BATCH_COUNT) {
						saveData();
						// 存储完成清理 list
						cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
					}
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext context) {
					saveData();
				}

				/**
				 * 加上存储数据库
				 */
				private void saveData() {
					log.info("{}条数据，开始存储数据库！", cachedDataList.size());
					importSysUserPermission(cachedDataList, errorMessageList);
					log.info("存储数据库成功！");
				}
			}).sheet().doRead();
		} catch (Exception e) {
			log.error(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR, e);
			return R.failed(CommonConstants.IMPORT_DATA_ANALYSIS_ERROR);
		}
		return R.ok(errorMessageList);
	}

	private void importSysUserPermission(List<SysUserPermissionVo> excelVOList, List<ErrorMessage> errorMessageList) {

		// 执行数据插入操作 组装
		for (int i = 0; i < excelVOList.size(); i++) {
			SysUserPermissionVo excel = excelVOList.get(i);
			// 插入
			insertExcel(excel);
			errorMessageList.add(new ErrorMessage(excel.getRowIndex(), CommonConstants.SAVE_SUCCESS));
		}
	}

	/**
	 * 插入excel bad record
	 */
	private void insertExcel(SysUserPermissionVo excel) {
		SysUserPermission insert = new SysUserPermission();
		BeanUtil.copyProperties(excel, insert);
		this.save(insert);
	}
}
