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

import com.alibaba.excel.EasyExcelFactory;
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.TProveRecord;
import com.yifu.cloud.plus.v1.yifu.archives.mapper.TProveRecordMapper;
import com.yifu.cloud.plus.v1.yifu.archives.service.TProveRecordService;
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 org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @author pwang
 * @date 2019-11-05 15:24:25
 */
@Service
public class TProveRecordServiceImpl extends ServiceImpl<TProveRecordMapper, TProveRecord> implements TProveRecordService {

	private Lock lock = new ReentrantLock();

	/**
	 * 简单分页查询
	 *
	 * @param tProveRecord
	 * @return
	 */
	@Override
	public IPage<TProveRecord> getTProveRecordPage(Page<TProveRecord> page, TProveRecord tProveRecord) {
		return baseMapper.getTProveRecordPage(page, tProveRecord);
	}

	@Override
	public synchronized void saveNo(TProveRecord record) {
		String str = "WX-";
		if (record.getUnitName() != null) {
			if (record.getUnitName().contains("易服")) {
				str = "YF-";
			} else if (record.getUnitName().contains("柯恩")) {
				str = "KE-";
			}
		}
		Integer count = 0;
		//cityName = cityName.replace("市", "");
		//str += PingYinUtil.getPYIndexStr(cityName, true) + "-";
		count = baseMapper.createNo(str);
		if (count != null) {
			count++;
			if (count < 10000) {
				str += new DecimalFormat("00000").format(count);
			} else {
				str += String.valueOf(count);
			}
		} else {
			str += "00001";
		}
		record.setNo(str);
		this.save(record);
	}

	@Override
	public List<TProveRecord> getRecordInfoNoPage(TProveRecord pr) {
		return baseMapper.getRecordInfoNoPage(pr);
	}

	/**
	 * 工资报账主表（工资条）批量导出
	 *
	 * @return
	 */
	@Override
	public void listExport(HttpServletResponse response, TProveRecord searchVo) {
		String fileName = "证明记录导出" + DateUtil.getThisTime() + CommonConstants.XLSX;
		//获取要导出的列表
		List<TProveRecord> list = new ArrayList<>();
		int count = baseMapper.getCountByExport(searchVo);
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			response.setContentType(CommonConstants.MULTIPART_FORM_DATA);
			response.setCharacterEncoding("utf-8");
			response.setHeader(CommonConstants.CONTENT_DISPOSITION, CommonConstants.ATTACHMENT_FILENAME + URLEncoder.encode(fileName, "UTF-8"));
			// 这里 需要指定写用哪个class去写，然后写到第一个sheet，然后文件流会自动关闭
			if (Common.isEmpty(searchVo.getExportFields())) {
				//String[] exportFields = {"姓名", "证明编号", "身份证", "结算主体", "计算类型", "开始月份", "结束月份"
				// , "平均工资", "开具人", "开具日期", "用途", "是否作废", "作废原因"}
				String[] exportFields = {"employeeName", "no", "employeeIdCard", "employeeSettleDepartName", "sumType"
						, "startMonth", "endMonth", "proveSalary", "creatUserName", "creatDate", "purpose", "isInvalid"
						, "invalidReason"};
				Set<String> exportSet = Arrays.stream(exportFields).collect(Collectors.toSet());
				searchVo.setExportFields(exportSet);
			}
			ExcelWriter excelWriter = EasyExcelFactory.write(out, TProveRecord.class).includeColumnFiledNames(searchVo.getExportFields()).build();
			int index = 0;
			WriteSheet writeSheet;
			if (count > CommonConstants.ZERO_INT) {
				for (int i = 0; i <= count; i += CommonConstants.EXCEL_EXPORT_LIMIT_3) {
					// 获取实际记录
					searchVo.setLimitStart(i);
					searchVo.setLimitEnd(CommonConstants.EXCEL_EXPORT_LIMIT_3);
					list = baseMapper.getRecordInfoNoPage(searchVo);
					if (Common.isNotNull(list)) {
						writeSheet = EasyExcelFactory.writerSheet("证明记录" + index).build();
						excelWriter.write(list, writeSheet);
						index++;
						list.clear();
					}
				}
			} else {
				writeSheet = EasyExcelFactory.writerSheet("证明记录" + index).build();
				excelWriter.write(list, writeSheet);
			}
			if (Common.isNotNull(list)) {
				list.clear();
			}
			out.flush();
			excelWriter.finish();
		} catch (Exception e) {
			log.error("执行异常", e);
		} finally {
			try {
				if (null != out) {
					out.close();
				}
			} catch (IOException e) {
				log.error("执行异常", e);
			}
		}
	}
}
