package com.pj.project.tb_driver;

import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.dto.OrderDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.dto.APPLoginUserInfo;
import com.pj.enummj.DeleteStatus;
import com.pj.project.tb_car_record.TbCarRecord;
import com.pj.project.tb_car_record.TbCarRecordMapper;
import com.pj.project.tb_logistics.TbLogistics;
import com.pj.project.tb_logistics.TbLogisticsMapper;
import com.pj.project.tb_vehicle.TbVehicle;
import com.pj.project.tb_vehicle.TbVehicleMapper;
import com.pj.project.tb_driver.param.SucessDriverResultParam;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author Mechrevo
 * @Date 2023 07 22 12 08
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class MethodDriverService {
    
    @Autowired
    private TbDriverService tbDriverService;

    @Autowired
    private TbLogisticsMapper tbLogisticsMapper;

    @Autowired
    private TbCarRecordMapper tbCarRecordMapper;

    @Autowired
    private TbVehicleMapper tbVehicleMapper;

    @Autowired
    private LevelOneServerInterface levelOneServerInterface;
    /** 司机同意 */
    public boolean agree(APPLoginUserInfo appLoginInfo, SucessDriverResultParam driverResultParam){

        TbCarRecord tbCarRecord = tbCarRecordMapper.selectById(driverResultParam.getCarRecordId());
        if(tbCarRecord == null)throw new ServiceException("服务器繁忙!");
        tbCarRecord.setDriverResult(1); // 同意
        int update = tbCarRecordMapper.updateById(tbCarRecord);
        if(update != 1)throw new RuntimeException("接单失败~");
        //修改车辆状态
        TbVehicle tbVehicle = tbVehicleMapper.selectById(driverResultParam.getVehicleId());
        if(tbVehicle == null)throw new ServiceException("车辆信息异常!");
        tbVehicle.setVehicleStatus(1); // 将状态修改成作业中
        int updateById = tbVehicleMapper.updateById(tbVehicle);
        if(updateById != 1)throw new RuntimeException("车辆状态异常");
        //修改一级订单表叫车状态
        OrderDto orderDto = levelOneServerInterface.getOrderDtoById(driverResultParam.getLevelOneOrderId());
        orderDto.setCallCarStatus(2); // 2=已完成叫车
        boolean b = levelOneServerInterface.updateOrderCallCarStatus(orderDto);
        if(!b)throw new ServiceException("一级市场订单表状态异常!");
        //生成物流信息
        TbLogistics logistics = new TbLogistics();
        //数据拷贝
        BeanUtils.copyProperties(driverResultParam,logistics);
//        logistics.setDeclarationNumber(); //申报订单号
//        logistics.setPrepare();  //订单待确认(0=待确认,1=订单已确认,2=订单确认失败)[j switch=true]
        logistics.setPrepareTime(new Date()); // 确认接单时间
        logistics.setLoading(0); //装货状态0,默认待装货
//        logistics.setLoadingTime(); //  装货时间
        logistics.setDelivery(0); // 发货状态,默认未发货
//        logistics.setDeliveryTime(); // 发货时间
        logistics.setClearedCustom(0); // 海关状态0, 默认未出海关
//        logistics.setClearedCustomTime();  // 出海关时间
        logistics.setMakeCargo(1);  // 接货人确定接货(0=禁用,1=启用)[j switch=true]
        logistics.setMakeCargoTime(null); // 接货完成时间
        logistics.setConfirmReceipt(1);  // 收购商确认(0=禁用,1=启用)[j switch=true]
        logistics.setConfirmReceiptTime(null);  // 收货方确认时间(相当于订单完成时间)
        logistics.setOrderFinish(0); // 订单完成状态, 默认未完成

        //设置基本字段属性
        logistics.setCreateBy(appLoginInfo.getLoginId());
        logistics.setCreateName(appLoginInfo.getLoginName());
        logistics.setCreateTime(new Date());
        logistics.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode()); // 默认可用

        //保存物流信息
        int insert = tbLogisticsMapper.insert(logistics);
        if(insert != 1)throw new RuntimeException("物流信息保存异常!");

        return true;
    }



    /**
     * 方法抽取  导入
     * @param row
     * @param sheet
     * @param count
     * @return
     */
    public int importMethod(HSSFRow row, HSSFSheet sheet, int count){

        //创建接收集合
        List<TbDriver> list = new ArrayList<>();

        for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
            //封装数据到行对象
            row = sheet.getRow(i);
            //定义返回值实体
            TbDriver tbDriver = new TbDriver();
            //解析数据
            if(row.getCell(1) != null)
                tbDriver.setName(row.getCell(1).getStringCellValue());

            HSSFCell cell21 = row.getCell(2);
            if (cell21 != null && (cell21.getCellType() == CellType.NUMERIC || cell21.getCellType() == CellType.FORMULA))
                tbDriver.setAge((int) cell21.getNumericCellValue());

            HSSFCell cell3 = row.getCell(3);
            if (cell3 != null && (cell3.getCellType() == CellType.NUMERIC || cell3.getCellType() == CellType.FORMULA))
                tbDriver.setSex((int) cell3.getNumericCellValue());

            if(row.getCell(4) != null)
                tbDriver.setPhone(row.getCell(4).getStringCellValue());

            if(row.getCell(5) != null)
                tbDriver.setAddress(row.getCell(5).getStringCellValue());

            if(row.getCell(6) != null)
                tbDriver.setBankCode(row.getCell(6).getStringCellValue());

            if(row.getCell(7) != null)
                tbDriver.setBankName(row.getCell(7).getStringCellValue());

            if(row.getCell(8) != null)
                tbDriver.setIdCard(row.getCell(8).getStringCellValue());

            if(row.getCell(9) != null)
                tbDriver.setIdCardImg(row.getCell(9).getStringCellValue());

            if(row.getCell(10) != null)
                tbDriver.setDrivingLicenseId(row.getCell(10).getStringCellValue());

            if(row.getCell(11) != null)
                tbDriver.setDrivingLicenseImg(row.getCell(11).getStringCellValue());

            if(row.getCell(12) != null)
                tbDriver.setIdCard(row.getCell(12).getStringCellValue());

            if(row.getCell(13) != null)
                tbDriver.setVehicleDrivingId(row.getCell(13).getStringCellValue());

            if(row.getCell(14) != null)
                tbDriver.setVehicleDrivingImg(row.getCell(14).getStringCellValue());

            if(row.getCell(15) != null)
                tbDriver.setVehicleImg(row.getCell(15).getStringCellValue());


            HSSFCell cell16 = row.getCell(16);
            if (cell16 != null && cell16.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell16)) {
                tbDriver.setRegisterTime(cell16.getDateCellValue());
            }

            HSSFCell cell7 = row.getCell(17);
            if (cell7 != null && (cell7.getCellType() == CellType.NUMERIC || cell7.getCellType() == CellType.FORMULA))
                tbDriver.setIsLock((int) cell7.getNumericCellValue());

            if(row.getCell(18) != null)
                tbDriver.setNopassReason(row.getCell(18).getStringCellValue());

            HSSFCell cell9 = row.getCell(19);
            if (cell9 != null && (cell9.getCellType() == CellType.NUMERIC || cell9.getCellType() == CellType.FORMULA))
                tbDriver.setAuditStatus((int) cell9.getNumericCellValue());

            if(row.getCell(20) != null)
                tbDriver.setAuditBy(row.getCell(20).getStringCellValue());

            HSSFCell cell121 = row.getCell(21);
            if (cell121 != null && cell121.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell121)) {
                tbDriver.setAuditTime(cell121.getDateCellValue());
            }

            //公共字段
            HSSFCell cell18 = row.getCell(22);
            if (cell18 != null && cell18.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell18)) {
                tbDriver.setCreateTime(cell18.getDateCellValue());
            }

            if(row.getCell(23) != null && !row.getCell(23).toString().trim().equals(""))
                tbDriver.setCreateBy(row.getCell(23).getStringCellValue());

            if(row.getCell(24) != null && !row.getCell(24).toString().trim().equals(""))
                tbDriver.setCreateName(row.getCell(24).getStringCellValue());

            if(row.getCell(25) != null && !row.getCell(25).toString().trim().equals(""))
                tbDriver.setUpdateBy(row.getCell(25).getStringCellValue());

            if(row.getCell(26) != null && !row.getCell(26).toString().trim().equals(""))
                tbDriver.setUpdateName(row.getCell(26).getStringCellValue());

            HSSFCell cell27 = row.getCell(27);
            if (cell27 != null && cell27.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell27)) {
                tbDriver.setUpdateTime(cell27.getDateCellValue());
            }
            //删除状态,默认可用
            tbDriver.setDeleteStatus(1);
			//添加到集合
			list.add(tbDriver);

        }

        System.out.println("待处理数据量为: " + list.size() + " 条。");

        //创建多线程
        ExecutorService executorService = Executors.newFixedThreadPool(6);

        //每次100条
        int bai = 100;
        //计算需要创建的线程数
        int threads = (int) Math.ceil((double) list.size() / bai);
        for (int i = 0; i < threads; i++) {
            int start = i * bai;
            int end = Math.min(start + bai,list.size());

            //截取集合数量
            List<TbDriver> enterpriseList = list.subList(start, end);

            //多线程执行任务
            executorService.submit(() -> {
                tbDriverService.saveBatch(enterpriseList);
            });
            //计数
            count += enterpriseList.size();

        }
        //关闭线程池
        executorService.shutdown();

        return count;
    }
    
}
