package com.yifu.cloud.plus.v1.business.service.settle.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;
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.business.entity.settle.TBusSettle;
import com.yifu.cloud.plus.v1.business.mapper.settle.TBusSettleMapper;
import com.yifu.cloud.plus.v1.business.service.settle.TBusSettleService;
import com.yifu.cloud.plus.v1.business.service.system.TBusAttaInfoService;
import com.yifu.cloud.plus.v1.business.vo.BusFileVo;
import com.yifu.cloud.plus.v1.business.vo.settle.SettleAdditionTypeEnum;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.CheckedException;
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.util.RandomUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * B端结算表
 *
 * @author hgw
 * @date 2021-08-16 15:58:09
 */
@AllArgsConstructor
@Slf4j
@Service
public class TBusSettleServiceImpl extends ServiceImpl<TBusSettleMapper, TBusSettle> implements TBusSettleService {

	private final TBusAttaInfoService busAttaInfoService;

	public static final String DEPART_ALREADY_EXIST_MONTH_DATA = "该部门该结算月份已有数据，若要更新，请先将原数据删除后，再次导入！";

	public static final String SETTLE_MONTH_MATCH = "([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(0[1-9]{1}|1[0-2]{1})";

	public static final String FILE_NAME_DATE_FORMAT_ERROR = "文件名格式中日期格式错误！";

	public static final String SAVE_SETTLE_ERROR = "保存结算记录出错";

	public static final String FILE_NAME_ERROT = "命名格式不规范";

	public static final String HRB_SETTLE_FILE_PATH = "hrb/settle";

	public static final String ZIP_FILE_NAME_VALID_FAILD = "zip压缩文件名格式不正确";

	public static final String ZIP_EXTRACT_ERROR = "结算管理导入zip文件解压功能出错";

	/**
	 * B端结算表简单分页查询
	 *
	 * @param tBusSettle B端结算表
	 * @return
	 */
	@Override
	public IPage<TBusSettle> getTBusSettlePage(Page<TBusSettle> page, TBusSettle tBusSettle) {
		return baseMapper.getTBusSettlePage(page, tBusSettle);
	}

	@Override
	public List<TBusSettle> getTBusSettleList(TBusSettle tBusSettle) {
		return baseMapper.getTBusSettleList(tBusSettle);
	}

	/**
	 * @param file zip文件包
	 * @description: 解析zip文件包中的多个附件，并生成结算记录
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.Boolean>
	 * @author: wangweiguo
	 * @date: 2021/8/19
	 */
	@Override
	@Transactional
	public R<Boolean> importZip(MultipartFile file) {
		File unzip = null;

		YifuUser user = SecurityUtils.getUser();
		if (null == user) {
			return R.failed("用户未登录");
		}
		File etractFile = null;
		try {
			String fileType = FileTypeUtil.getType(file.getInputStream());
			if (!StringUtils.equalsIgnoreCase(fileType, CommonConstants.JAR_TYPE)) {
				return R.failed("导入的文件格式不正确");
			}

			String[] destoryName = StringUtils.split(StringUtils.removeEndIgnoreCase(file.getOriginalFilename()
							.replace(".jar","")
							.replace(".zip","")
					, CommonConstants.SPOT.concat(fileType)), CommonConstants.DOWN_LINE_CHAR);
			if (null != destoryName && destoryName.length == 2) {
				TBusSettle busSettle = this.lambdaQuery()
						.eq(TBusSettle::getSettleMonth, destoryName[1])
						.eq(TBusSettle::getAccountDeptName, destoryName[0])
						.eq(TBusSettle::getDeleteFlag, CommonConstants.ZERO_INT)
						.last(CommonConstants.LAST_ONE_SQL).one();
				if (null != busSettle) {
					return R.failed(DEPART_ALREADY_EXIST_MONTH_DATA);
				}

				etractFile = new File(UUID.randomUUID().toString());
				unzip = ZipUtil.unzip(file.getInputStream(), etractFile, CharsetUtil.CHARSET_GBK);

				// 正常解压后创建结算记录
				busSettle = new TBusSettle();
				busSettle.setAccountDeptName(destoryName[0]);
				busSettle.setSettleMonth(destoryName[1]);
				busSettle.setCreateUserId(String.valueOf(user.getId()));
				busSettle.setCreateUserName(user.getNickname());
				busSettle.setCreateTime(LocalDateTime.now());
				if (!busSettle.getSettleMonth().matches(SETTLE_MONTH_MATCH)) {
					return R.failed(FILE_NAME_DATE_FORMAT_ERROR);
				}
				busSettle.setId(DateUtil.getCurrentDateString() + RandomUtil.getSix());
				List<File> files = FileUtil.loopFiles(unzip);
				for (File fl : files) {
					String fileName = FileUtil.getName(fl);
					SettleAdditionTypeEnum settleAdditionTypeEnum = SettleAdditionTypeEnum.getTypeEnumByFileName(fileName);
					if (null == settleAdditionTypeEnum) {
						return R.failed(fileName + "：" + FILE_NAME_ERROT);
					}
					R<BusFileVo> busFileVoR = this.busAttaInfoService.uploadFile(fileCovertMultipartFile(fl)
							, HRB_SETTLE_FILE_PATH, settleAdditionTypeEnum.getType(), busSettle.getId());
					if (!R.isSuccess(busFileVoR)) {
						return R.failed(busFileVoR.getMsg());
					}
				}

				boolean saveBusSettleSuccess = this.save(busSettle);
				if (!saveBusSettleSuccess) {
					return R.failed(SAVE_SETTLE_ERROR);
				}

			} else {
				return R.failed(ZIP_FILE_NAME_VALID_FAILD);
			}

		} catch (IOException e) {
			runTimeExceptionDiy(ZIP_EXTRACT_ERROR.concat(": ").concat(e.getCause().toString()));
		} finally {
			if (etractFile != null) {
				FileUtil.del(etractFile);
			}
		}
		return R.ok();
	}

	private static void runTimeExceptionDiy(String errorInfo) {
		throw new CheckedException(errorInfo);
	}

	/**
	 * File转MultipartFile
	 *
	 * @param file 需要转换的文件
	 * @description: File转MultipartFile
	 * @return: org.springframework.web.multipart.MultipartFile
	 * @author: wangweiguo
	 * @date: 2021/8/19
	 */
	private MultipartFile fileCovertMultipartFile(File file) {
		FileItemFactory factory = new DiskFileItemFactory(16, null);
		String textFieldName = "textField";
		FileItem item = factory.createItem(textFieldName, "text/plain", true, file.getName());
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		try {
			FileInputStream fis = new FileInputStream(file);
			OutputStream os = item.getOutputStream();
			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new CommonsMultipartFile(item);
	}

}
