package com.pj.project.tb_driver;

import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.dto.DriverDto;
import com.pj.api.dto.OrderDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.project.tb_car_record.TbCarRecord;
import com.pj.project.tb_driver.param.SucessDriverResultParam;
import com.pj.project.tb_driver.param.FailDriverResultParam;
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;

import static com.pj.project.tb_car_record.TbCarRecordUtil.tbCarRecordMapper;

/**
 * Service: tb_driver -- 司机
 * @author qzy 
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbDriverService extends ServiceImpl<TbDriverMapper, TbDriver> implements IService<TbDriver>{

	/** 底层 Mapper 对象 */
	@Autowired
	TbDriverMapper tbDriverMapper;

	@Autowired
	private MethodDriverService methodDriverService;

	@Autowired
	private LevelOneServerInterface levelOneServerInterface;


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

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

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

	}

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

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

	/**
	 * 司机处理订单,同意
	 * @return
	 */
	public boolean driverAgree(SucessDriverResultParam driverResultParam){
		//获取当前登录人
		APPLoginUserInfo appLoginInfo = StpAPPUserUtil.getAPPLoginInfo();
		boolean agree = methodDriverService.agree(appLoginInfo, driverResultParam);
		//todo: 将司机车辆状态返还给航通
		if(agree){
			//车辆状态, 默认作业中

		}
		return agree;
	}


	/**
	 * 司机处理订单,拒绝
	 * @param failDriverResultParam
	 * @return
	 */
	public boolean driverRefuse(FailDriverResultParam failDriverResultParam) throws Exception {

		//将叫车表状态改成已拒绝
		TbCarRecord tbCarRecord = tbCarRecordMapper.selectById(failDriverResultParam.getCarRecordId());
		if(tbCarRecord == null)throw new ServiceException("叫车记录信息异常!");
		tbCarRecord.setDriverResult(2); // 2=司机拒绝接单
		//执行保存
		int i = tbCarRecordMapper.updateById(tbCarRecord);
		if(i == 1){
			//修改一级订单表叫车状态
			OrderDto orderDto = levelOneServerInterface.getOrderDtoById(failDriverResultParam.getLevelOneOrderId());
			orderDto.setCallCarStatus(0); // 修改成未叫车状态
			boolean b = levelOneServerInterface.updateOrderCallCarStatus(orderDto);
			if(!b)throw new RuntimeException("一级市场订单表状态异常!");
			//todo:司机拒绝,发送通知短信给收购商
//		smsRetryService.sendSmsMsg(failDriverResultParam.getEnterprisePhone());
		}
		return i == 1;

	}












	/**
	 * 导入
	 * @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 = methodDriverService.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<TbDriver> selectedList = tbDriverMapper.selectList
				(new LambdaQueryWrapper<TbDriver>().eq(StringUtils.isNoneBlank(keyword), TbDriver::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(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("审核时间");

		row.createCell(21).setCellValue("创建时间");
		row.createCell(22).setCellValue("创建人编号");
		row.createCell(23).setCellValue("创建人名称");
		row.createCell(24).setCellValue("更新时间");
		row.createCell(25).setCellValue("更新人编号");
		row.createCell(26).setCellValue("更新人名称");
		row.createCell(27).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).getAge() + "").equals("null")? "": selectedList.get(i).getAge() + "");
			sheetRow.createCell(3).setCellValue((selectedList.get(i).getSex() + "").equals("null")? "": selectedList.get(i).getSex() + "");
			sheetRow.createCell(4).setCellValue((selectedList.get(i).getPhone() + "").equals("null")? "": selectedList.get(i).getPhone() + "");
			sheetRow.createCell(5).setCellValue((selectedList.get(i).getAddress() + "").equals("null")? "": selectedList.get(i).getAddress() + "");
			sheetRow.createCell(6).setCellValue((selectedList.get(i).getBankCode() + "").equals("null")? "": selectedList.get(i).getBankCode() + "");
			sheetRow.createCell(7).setCellValue((selectedList.get(i).getBankName() + "").equals("null")? "": selectedList.get(i).getBankName() + "");
			sheetRow.createCell(8).setCellValue((selectedList.get(i).getIdCard() + "" ).equals("null")? "": selectedList.get(i).getIdCard() + "");
			sheetRow.createCell(9).setCellValue((selectedList.get(i).getIdCardImg() + "").equals("null")? "": selectedList.get(i).getIdCardImg() + "");
			sheetRow.createCell(10).setCellValue((selectedList.get(i).getDrivingLicenseId() + "").equals("null")? "": selectedList.get(i).getDrivingLicenseId() + "");
			sheetRow.createCell(11).setCellValue((selectedList.get(i).getDrivingLicenseImg() + "").equals("null")? "": selectedList.get(i).getDrivingLicenseImg() + "");
			sheetRow.createCell(12).setCellValue((selectedList.get(i).getVehicleDrivingId() + "").equals("null")? "": selectedList.get(i).getVehicleDrivingId() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getVehicleDrivingImg() + "").equals("null")? "": selectedList.get(i).getVehicleDrivingImg() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getRegisterTime() + "").equals("null")? "": selectedList.get(i).getRegisterTime() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getIsLock() + "").equals("null")? "": selectedList.get(i).getIsLock() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getNopassReason() + "").equals("null")? "": selectedList.get(i).getNopassReason() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getAuditStatus() + "").equals("null")? "": selectedList.get(i).getAuditStatus() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getAuditBy() + "").equals("null")? "": selectedList.get(i).getAuditBy() + "");
			sheetRow.createCell(13).setCellValue((selectedList.get(i).getAuditTime() + "").equals("null")? "": selectedList.get(i).getAuditTime() + "");
			//公共字段
			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 driverDto(DriverDto driverDto){
		TbDriver tbDriver = new TbDriver();
		BeanUtils.copyProperties(driverDto,tbDriver);
		boolean save = this.save(tbDriver);
		return save;
	}

	/** 远程调用: 根据ID查询司机信息 */
	DriverDto getByDriverId(Long id){
		TbDriver driver = getById(id);
		DriverDto driverDto = new DriverDto();
		BeanUtils.copyProperties(driver,driverDto);
		return driverDto;
	}

}
