/*
 *    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.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.entity.WmImportUser;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.mapper.WmImportUserMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskMapper;
import com.qunzhixinxi.hnqz.admin.service.WmImportUserService;
import com.qunzhixinxi.hnqz.admin.util.ValidateUtils;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.service.HnqzUser;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 导入任务成员表
 *
 * @author pigx code generator
 * @date 2021-01-06 19:39:17
 */
@Service
@AllArgsConstructor
public class WmImportUserServiceImpl extends ServiceImpl<WmImportUserMapper, WmImportUser> implements WmImportUserService {

	private final WmTaskMapper wmTaskMapper;


	/**
	 * 添加任务成员
	 * @param wmImportUser
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R saveImportUser(WmImportUser wmImportUser) throws Exception {
//		boolean isphone=ValidateUtils.validPhoneNum("0",wmImportUser.getImportPhone());
//		if(!isphone){
//			return R.failed("手机号有误");
//		}
//		boolean isIdCard=ValidateUtils.IDCardValidate(wmImportUser.getImportIdCardNumber()+"");
//		if(!isIdCard){
//			return R.failed("身份证号有误");
//		}
		HnqzUser user= SecurityUtils.getUser();
		wmImportUser.setCreateUser(user.getId());
		wmImportUser.setCreateTime(LocalDateTime.now());
		wmImportUser.setDelFlag("0");
		wmImportUser.setRealFlag("0");
		return R.ok(this.save(wmImportUser));
	}

	/**
	 * 导入任务成员
	 * @param file
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class)
	public R impImportUser(MultipartFile file, String scoreId) throws Exception {
		HnqzUser user= SecurityUtils.getUser();
		String fileName = file.getOriginalFilename().toLowerCase();
		InputStream inputStream = file.getInputStream();
		Workbook wbs = null;//工作簿对象
		if (fileName.endsWith("xls")) {
			//2003
			wbs = new HSSFWorkbook(inputStream);
		} else if (fileName.endsWith("xlsx")) {
			//2007
			wbs = new XSSFWorkbook(inputStream);
		}else{
			return R.failed("上传文件格式错误!");
		}
		if (wbs.isSheetHidden(0)) {
			return R.failed("导入表中有隐藏列");
		}
		Sheet sheet = wbs.getSheetAt(0);
		Row row0 = sheet.getRow(0);
		if (row0 == null) {
			return R.failed("导入模版错误！");
		}
		String name=row0.getCell(0).getStringCellValue();
		if(!"姓名".equals(name)){
			return R.failed("导入模版第一列错误！");
		}
		String phone=row0.getCell(1).getStringCellValue();
		if(!"手机号".equals(phone)){
			return R.failed("导入模版第二列错误！");
		}
		String idcard=row0.getCell(2).getStringCellValue();
		if(!"身份证号".equals(idcard)){
			return R.failed("导入模版第三列错误！");
		}
		int rowNum = sheet.getLastRowNum();
		if(rowNum<=1){
			return R.failed("导入表中缺少数据！");
		}

		//数据
		List<WmImportUser> importUserList=new ArrayList<>();
		String errorInfo="";
		for (int i = 1; i <= rowNum; i++) {//行数据
			if (i > 1000) {
				break;
			}
			Row row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			int colNum = row.getLastCellNum();

			WmImportUser importUser=new WmImportUser();
			importUser.setScoreId(scoreId);
			importUser.setCreateUser(user.getId());
			importUser.setCreateTime(LocalDateTime.now());
			for (int j = 0; j < colNum; j++) {//列数据
				if (j > 1000) {
					break;
				}
				if(null==row.getCell(j)){
					errorInfo=errorInfo+"第"+(i+1)+"行第"+(j+1)+"列数据为空！";
					continue;
				}

				row.getCell(j).setCellType(CellType.STRING);
				String value = row.getCell(j).getStringCellValue()
						.replaceAll(" ", "").replaceAll(",", "").
								replaceAll("\\u00A0", "").
								replaceAll((char) 12288 + "", "");


				if(j==0){
					if(StringUtil.isEmpty(value)){
						errorInfo=errorInfo+"第"+(i+1)+"行姓名"+value+"有误！";
						continue;
					}
					importUser.setImportName(value);
				}else if(j==1){
//					boolean isphone=ValidateUtils.validPhoneNum("0",value);
//					if(!isphone){
//						errorInfo=errorInfo+"第"+(i+1)+"行手机号"+value+"有误！";
//						continue;
//					}
					importUser.setImportPhone(value);
				}else if(j==2){
//					boolean isIdCard=ValidateUtils.IDCardValidate(value);
//					if(!isIdCard){
//						errorInfo=errorInfo+"第"+(i+1)+"行身份证号"+value+"有误！";
//						continue;
//					}
					importUser.setImportIdCardNumber(value);
				}
			}
			importUserList.add(importUser);
		}
		if(!StringUtil.isEmpty(errorInfo)){
			return R.failed(errorInfo);
		}
		this.saveBatch(importUserList);

		return R.ok("上传成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R delImportUser(Integer id) {
		WmImportUser importUser=this.getById(id);
		importUser.setDelFlag("1");
		this.updateById(importUser);
		//更新举证状态为已删除
		WmTask wmTask=new WmTask();
		wmTask.setScorePackageId(importUser.getScoreId());
		wmTask.setDelFlag("1");
		wmTaskMapper.update(wmTask,
				Wrappers.<WmTask>lambdaUpdate().eq(WmTask::getScorePackageId,importUser.getScoreId())
		.eq(WmTask::getTaskUserId,importUser.getId()));

		return R.ok();
	}


}
