package com.pj.tb_purchaser;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pj.api.client.admin.AdminInterface;
import com.pj.api.dto.AppUserDto;
import com.pj.api.dto.MessageDto;
import com.pj.api.dto.PurchaserDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.satoken.StpUserUtil;
import com.pj.enummj.*;
import com.pj.tb_purchaser.param.PurchaserParam;
import com.pj.tb_purchaser.vo.PurchaserParamVo;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.so.SoMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.swing.filechooser.FileSystemView;

/**
 * Service: tb_purchaser -- 收购商
 * @author qzy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbPurchaserService extends ServiceImpl<TbPurchaserMapper, TbPurchaser> implements IService<TbPurchaser>{

	/** 底层 Mapper 对象 */
	@Autowired
	TbPurchaserMapper tbPurchaserMapper;

	@Autowired
	AdminInterface adminInterface;

	@Autowired
	private MethodPurchaserService methodPurchaserService;


	/** 增 */
	void add(TbPurchaser t){
		save(t);
	}

	/** 删 */
	void delete(Long id){
		removeById(id);
	}

	/** 改 */
	void update(TbPurchaser t){
		updateById(t);

	}

	/** 查 */
	TbPurchaser getById(Long id){
		return super.getById(id);
	}

	/** 查集合 - 根据条件（参数为空时代表忽略指定条件） */
	List<TbPurchaser> getList(SoMap so) {
		return tbPurchaserMapper.getList(so);
	}

	/** 收购商认证 */
	boolean identification(PurchaserParam purchaser) throws ParseException {
		if(null == purchaser) return false;
		//验证之前是否有被拒的
		List<TbPurchaser> tbPurchasers = tbPurchaserMapper.selectList(new LambdaQueryWrapper<TbPurchaser>().eq(TbPurchaser::getCreateBy, purchaser.getLoginUserId()));
		if(tbPurchasers.size() > 0){
			tbPurchasers.forEach(item -> {
				tbPurchaserMapper.deleteById(item.getId());
			});
		}
		//身份证号去重
		String idCard = purchaser.getCorporateIdCard();
		if(tbPurchaserMapper.selectList(new LambdaQueryWrapper<TbPurchaser>().eq(TbPurchaser::getIdCard,idCard).eq(TbPurchaser::getDeleteStatus,DeleteStatus.DELETE_STATUS_ON.getCode())).size() != 0)
			throw new RuntimeException("当前身份证号已被认证!");
		//手机号去重
		String contact = purchaser.getLinkPhone();
		if(tbPurchaserMapper.selectList(new LambdaQueryWrapper<TbPurchaser>().eq(TbPurchaser::getContact,contact).eq(TbPurchaser::getDeleteStatus,DeleteStatus.DELETE_STATUS_ON.getCode())).size() != 0)
			throw new RuntimeException("当前手机号已被认证!");
		//TODO:是否需要手机发送验证码认证?

		//封装收购商信息
		TbPurchaser tbPurchaser = methodPurchaserService.setPurchaserProperties(purchaser);
		// 保存收购商信息
		int insert = tbPurchaserMapper.insert(tbPurchaser);
		return insert == 1;
	}

	/**
	 *  收购商审核
	 * @param purchaserId 二级市场商户表主键
	 * @param judgeStatus 审核状态(0=待审核,1=审核通过,2=审核驳回)
	 * @param judgeContent 审核备注
	 * @return
	 */
	public boolean audit(Long purchaserId,Integer judgeStatus,String judgeContent){
		//审核不通过
		if(judgeStatus.equals(JudgeStatus.JUDGE_STATUS_TWO.getCode())){
			TbPurchaser selectById = tbPurchaserMapper.selectById(purchaserId);
			if(selectById == null)throw new ServiceException("商户信息异常!");
			selectById.setJudgeStatus(JudgeStatus.JUDGE_STATUS_TWO.getCode());
			selectById.setJudgeContent(judgeContent);
			tbPurchaserMapper.updateById(selectById);
			//发送通知给收购商
			MessageDto dto = new MessageDto();
			dto.setUrl("/pages/market/one/merchant/order/list");
			dto.setUserId(purchaserId);
			dto.setContents("您发起的收购商认证审核不通过,原因是: " + judgeContent);
			adminInterface.messageSave(dto);
			return true;
		}
		if(!judgeStatus.equals(1))
			return false;
		//审核通过
		TbPurchaser tbPurchaser = tbPurchaserMapper.selectById(purchaserId);
		if(tbPurchaser == null)throw new ServiceException("收购商信息异常。");
		//审核同构且完成数据插入则进行关联
		AppUserDto appUser = adminInterface.getByPhoneAndUserType(tbPurchaser.getContact(), UserType.USER_TYPE_PURCHASER.getCode());
		if(appUser == null)throw new ServiceException("审核的用户的信息异常!");
		if(appUser.getAuth().equals("1") || appUser.getFkId() != null)
			throw new ServiceException("该用户认证信息异常。");
		//设置审核人和审核时间
		tbPurchaser.setJudgeTime(new Date());
		tbPurchaser.setPersonId(StpUserUtil.getLoginIdAsString());
		tbPurchaser.setJudgeStatus(JudgeStatus.JUDGE_STATUS_ONE.getCode());
		tbPurchaserMapper.updateById(tbPurchaser);
		//设置关联属性
		appUser.setFkId(String.valueOf(tbPurchaser.getId()));
		appUser.setAuth(1 + "");  // 1=审核通过
		//保存
		Boolean aBoolean = adminInterface.saveAppUserInfo(appUser);
		//发送message
		if(aBoolean){
			//发送通知给收购商
			MessageDto dto = new MessageDto();
			dto.setUserId(appUser.getId());
			dto.setContents("恭喜商户信息认证成功!");
			adminInterface.messageSave(dto);
		}
		return aBoolean;
	}

	/** 获取审核状态 */
	public PurchaserParamVo auditStatus(Long appUserId){
		List<TbPurchaser> purchaserList = tbPurchaserMapper.selectList(new LambdaQueryWrapper<TbPurchaser>().eq(TbPurchaser::getCreateBy, appUserId).orderByDesc(TbPurchaser::getCreateTime));
		if(purchaserList.size() == 0)return null;
		PurchaserParamVo purchaserParam = methodPurchaserService.setPurchaserParamProperties(purchaserList.get(0));
		return purchaserParam;
	}
	/** 收购商批量审核 */
	public void auditBatch(List<Long> ids, Integer judgeStatus, String judgeContent) {
		if (ids.isEmpty()) {
			throw new AjaxError("必要参数不能为空");
		}
		List<TbPurchaser> list = listByIds(ids);
		String name = StpUserUtil.getLoginName();
		list.forEach(tbPurchaser -> {
			tbPurchaser.setJudgeStatus(judgeStatus).setJudgeContent(judgeContent).setJudgeTime(new Date()).setJudgeBy(name);
		});
		this.updateBatchById(list);
	}


	/** 是否锁住收购商 */
	public int isLock(TbPurchaserDto purchaserDto) {
		// 获取当前登录用户id
		Long loginId = StpUserUtil.getLoginIdAsLong();

		// 根据id获取收购商
		TbPurchaser purchaser = tbPurchaserMapper.selectById(purchaserDto.getId());
		// 如果收购商不存在则抛出异常
		if(Objects.isNull(purchaser)){
			throw new RuntimeException("该收购商不存在");
		}
		BeanUtils.copyProperties(purchaserDto,purchaser);
		// 写入更新者id
		purchaser.setUpdateBy(String.valueOf(loginId));
		// 更新收购商锁定状态
		int  line = tbPurchaserMapper.updateById(purchaser);
		//获取收购商锁定状态
		int isLock = purchaser.getIsLock();
		// 如果收购商被锁住则禁止app端登录
		adminInterface.isLock(String.valueOf(purchaser.getId()), People.PEOPLE_TYPE_THREE.getCode(),isLock);
		return line;
	}

	/**
	 * 导入
	 * @param file excel文件
	 * @return
	 * @throws IOException
	 */
	public String importData(MultipartFile file) throws IOException {
		System.out.println("\n开始执行文件上传....\n");

		//判空
		if(file.isEmpty()) return "文件为空,无法执行上传...";
		//获取文件上传数据
		HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
		//获取第一页sheet
		HSSFSheet sheet = wb.getSheetAt(0);
		//定义计数器
		int count = 0;
		//定义行对象
		HSSFRow row = null;
		//解析数据封装到集合
		count = methodPurchaserService.importMethod(row, sheet, count);
		wb.close();
		System.out.println("\n文件上传完成,共上传 " + count + "条 " + "数据...\n");
		return "上传完成,共上传"  + count + "条"  + "数据。";
	}

	/**
	 * 导出 excel文件
	 * @param keyword
	 * @return
	 */
	public String outportExcel(String keyword,String filepath) throws IOException {
		System.out.println("\n开始执行文件导出....\n");
		//导出的文件的路径
		if(filepath == null){
			// 获取当前用户的桌面路径
			FileSystemView fileSystemView = FileSystemView.getFileSystemView();
			filepath = fileSystemView.getHomeDirectory().getPath();
		}
		filepath = filepath + "\\收购商数据表_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".xlsx";
		//根据需求查询数据
		List<TbPurchaser> selectedList = tbPurchaserMapper.selectList
				(new LambdaQueryWrapper<TbPurchaser>().eq(StringUtils.isNoneBlank(keyword), TbPurchaser::getName, keyword));
		if(selectedList.size() == 0)return "没有可导出的数据。";
		//建立excel对象封装数据
		HSSFWorkbook workbook = new HSSFWorkbook();
		//创建excel表格右下角的sheet页名称
		HSSFSheet sheet = workbook.createSheet("1");
		//创建表头
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue("序号");
		row.createCell(1).setCellValue("名称");
		row.createCell(2).setCellValue("法人");
		row.createCell(3).setCellValue("身份证");
		row.createCell(4).setCellValue("手机号码");
		row.createCell(5).setCellValue("营业执照");
		row.createCell(6).setCellValue("银行编号");
		row.createCell(7).setCellValue("银行名称");
		row.createCell(8).setCellValue("银行账号");
		row.createCell(9).setCellValue("税号");
		row.createCell(10).setCellValue("地址编号");
		row.createCell(10).setCellValue("地址");
		row.createCell(11).setCellValue("审核状态");
		row.createCell(13).setCellValue("审核意见");
		row.createCell(12).setCellValue("上次审核时间");
		row.createCell(12).setCellValue("注册时间");
		row.createCell(12).setCellValue("人脸编号");

		row.createCell(14).setCellValue("创建时间");
		row.createCell(15).setCellValue("创建人编号");
		row.createCell(16).setCellValue("创建人名称");
		row.createCell(17).setCellValue("更新时间");
		row.createCell(18).setCellValue("更新人编号");
		row.createCell(19).setCellValue("更新人名称");
		row.createCell(20).setCellValue("删除状态");

		//定义计数器
		int count = 0;
		//遍历集合
		for (int i = 0; i < selectedList.size(); i++) {
			HSSFRow sheetRow = sheet.createRow(sheet.getLastRowNum() + 1);
			sheetRow.createCell(0).setCellValue(i + 1);
			sheetRow.createCell(1).setCellValue((selectedList.get(i).getName() + "").equals("null")? "": selectedList.get(i).getName() + "");
			sheetRow.createCell(2).setCellValue((selectedList.get(i).getLegalPerson() + "").equals("null")? "": selectedList.get(i).getLegalPerson() + "");
			sheetRow.createCell(3).setCellValue((selectedList.get(i).getIdCard() + "").equals("null")? "": selectedList.get(i).getIdCard() + "");
			sheetRow.createCell(4).setCellValue((selectedList.get(i).getContact() + "").equals("null")? "": selectedList.get(i).getContact() + "");
			sheetRow.createCell(5).setCellValue((selectedList.get(i).getBusinessLicense() + "").equals("null")? "": selectedList.get(i).getBusinessLicense() + "");
			sheetRow.createCell(6).setCellValue((selectedList.get(i).getBankNo() + "").equals("null")? "": selectedList.get(i).getBankNo() + "");
			sheetRow.createCell(7).setCellValue((selectedList.get(i).getBankName() + "").equals("null")? "": selectedList.get(i).getBankName() + "");
			sheetRow.createCell(8).setCellValue((selectedList.get(i).getBankAccount() + "" ).equals("null")? "": selectedList.get(i).getBankAccount() + "");
			sheetRow.createCell(9).setCellValue((selectedList.get(i).getDutyParagraph() + "").equals("null")? "": selectedList.get(i).getDutyParagraph() + "");
			sheetRow.createCell(10).setCellValue((selectedList.get(i).getAddressIds() + "").equals("null")? "": selectedList.get(i).getAddressIds() + "");
			sheetRow.createCell(11).setCellValue((selectedList.get(i).getAddress() + "").equals("null")? "": selectedList.get(i).getAddress() + "");
			sheetRow.createCell(12).setCellValue((selectedList.get(i).getJudgeStatus() + "").equals("null")? "": selectedList.get(i).getJudgeStatus() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getJudgeContent() + "").equals("null")? "": selectedList.get(i).getJudgeContent() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getJudgeTime() + "").equals("null")? "": selectedList.get(i).getJudgeTime() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getRegisterTime() + "").equals("null")? "": selectedList.get(i).getRegisterTime() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getPersonId() + "").equals("null")? "": selectedList.get(i).getPersonId() + "");
			//公共字段
			sheetRow.createCell(22).setCellValue((selectedList.get(i).getCreateTime() + "").equals("null")? "": selectedList.get(i).getCreateTime() + "");
			sheetRow.createCell(23).setCellValue((selectedList.get(i).getCreateBy() + "").equals("null")? "": selectedList.get(i).getCreateBy() + "");
			sheetRow.createCell(24).setCellValue((selectedList.get(i).getCreateName() + "").equals("null")? "": selectedList.get(i).getCreateName() + "");
			sheetRow.createCell(25).setCellValue((selectedList.get(i).getUpdateTime() + "").equals("null")? "": selectedList.get(i).getUpdateTime() + "");
			sheetRow.createCell(26).setCellValue((selectedList.get(i).getUpdateBy() + "").equals("null")? "": selectedList.get(i).getUpdateBy() + "");
			sheetRow.createCell(27).setCellValue((selectedList.get(i).getUpdateName() + "").equals("null")? "": selectedList.get(i).getUpdateName() + "");
			sheetRow.createCell(28).setCellValue((selectedList.get(i).getDeleteStatus() + "").equals("null")? "": selectedList.get(i).getDeleteStatus() + "");
			count += 1;
		}
		//建立输出流，输出文件
		FileOutputStream fos = new FileOutputStream(filepath);

		workbook.write(fos);
		fos.flush();
		//关闭输出流
		fos.close();
		workbook.close();
		System.out.println("\n数据导出完成!共导出 " + count + " 条数据。");
		return "数据导出完成!共导出 " + count + " 条数据。";
	}

	/** 远程调用方法 注册身份为国内收购商时调用*/
	public boolean purchaserDto(PurchaserDto purchaserDto){
		TbPurchaser tbPurchaser = new TbPurchaser();
		BeanUtils.copyProperties(purchaserDto,tbPurchaser);
		boolean save = this.save(tbPurchaser);
		return save;
	}

	/** 远程调用方法 根据ID查询国内收购商*/
	public PurchaserDto getByPurchaserId(Long id){
		TbPurchaser byId = getById(id);
		PurchaserDto purchaserDto = new PurchaserDto();
		BeanUtils.copyProperties(byId,purchaserDto);
		return purchaserDto;
	}


}
