package com.pj.project.tb_vehicle;

import com.pj.api.client.level_one_server.LevelOneServerInterface;
import com.pj.api.dto.EnterpriseDto;
import com.pj.api.dto.GoodsTransitDto;
import com.pj.api.dto.OrderDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.current.satoken.StpAPPUserUtil;
import com.pj.enummj.DeleteStatus;
import com.pj.project.tb_car_record.TbCarRecord;
import com.pj.project.tb_vehicle.param.MakeCarRecordParam;
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 32
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class MethodVehicleService {

    @Autowired
    private TbVehicleService tbVehicleService;
    @Autowired
    private TbVehicleMapper tbVehicleMapper;

    @Autowired
    private LevelOneServerInterface levelOneServerInterface;

    /** 创建叫车记录 */
    public TbCarRecord makeCarRecord(MakeCarRecordParam makeCarRecordParam){
        //创建返回值对象
        TbCarRecord carRecord = new TbCarRecord();
        //数据拷贝
        BeanUtils.copyProperties(makeCarRecordParam,carRecord);
        //获取先决条件
        TbVehicle tbVehicle = tbVehicleMapper.selectById(makeCarRecordParam.getVehicleId());
        if(tbVehicle == null)throw new ServiceException("车辆信息有误!");
        OrderDto orderDtoById = levelOneServerInterface.getOrderDtoById(makeCarRecordParam.getOrderId());
        if(orderDtoById == null)throw new ServiceException("一级市场订单信息异常!");
        GoodsTransitDto goodsTransitById = levelOneServerInterface.getGoodsTransitById(orderDtoById.getGoodsId(), orderDtoById.getEnterpriseId());
        if(goodsTransitById == null)throw new ServiceException("商品信息异常!");
        EnterpriseDto enterpriseById = levelOneServerInterface.getEnterpriseById(makeCarRecordParam.getEnterpriseId());
        if(enterpriseById == null)throw new ServiceException("一级市场商户信息错误!");
        //将订单状态修改成正在叫车
        boolean carStatus = levelOneServerInterface.updateOrderCallCarStatus(orderDtoById);
        if(!carStatus)throw new ServiceException("叫车状态修改异常!");
        //赋值基本信息
        carRecord.setLoadingAddress(makeCarRecordParam.getLoadingAddress());  // 装货地址
        carRecord.setVehicleType(tbVehicle.getVehicleType()); // 车辆类型
        carRecord.setVehicleModel(tbVehicle.getVehicleModel());  // 车辆品牌型号
        carRecord.setGoodsName(goodsTransitById.getGoodsName()); //过审商品名称
        carRecord.setGoodsImg(goodsTransitById.getGoodsImg()); // 过审商品图片
        carRecord.setGoodsWeight(goodsTransitById.getGrossWeight()); // 过审商品毛重
        carRecord.setShopName(goodsTransitById.getShopName());  // 一级市场商铺名称
        carRecord.setEnterpriseName(goodsTransitById.getMerchantName()); // 一级市场商户名称
        carRecord.setEnterprisePhone(enterpriseById.getOwnerTel()); // 一级市场商户电话
        //司机处理[0=待处理,1=同意,2=拒绝]
        carRecord.setDriverResult(0); // 默认待处理
        //公共字段属性赋值
        carRecord.setCreateBy(StpAPPUserUtil.getAPPLoginInfo().getLoginId());
        carRecord.setCreateName(StpAPPUserUtil.getAPPLoginInfo().getLoginName());
        carRecord.setCreateTime(new Date());
        carRecord.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
        return carRecord;
    }












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

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

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

            if(row.getCell(2) != null)
                tbVehicle.setOwner(row.getCell(2).getStringCellValue());

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

            HSSFCell cell4 = row.getCell(4);
            if (cell4 != null && (cell4.getCellType() == CellType.NUMERIC || cell4.getCellType() == CellType.FORMULA))
                tbVehicle.setParentId((int) cell4.getNumericCellValue());

            if(row.getCell(5) != null)
                tbVehicle.setVehicleSize(row.getCell(5).getStringCellValue());

            if(row.getCell(6) != null)
                tbVehicle.setVehicleModel(row.getCell(6).getStringCellValue());

            if(row.getCell(7) != null)
                tbVehicle.setVehicleLoad(row.getCell(7).getStringCellValue());

            if(row.getCell(8) != null)
                tbVehicle.setVehicleWeight(row.getCell(8).getStringCellValue());

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

            if(row.getCell(10) != null)
                tbVehicle.setAuditBy(row.getCell(10).getStringCellValue());

            if(row.getCell(11) != null)
                tbVehicle.setNopassReason(row.getCell(11).getStringCellValue());

            HSSFCell cell12 = row.getCell(12);
            if (cell12 != null && cell12.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell12)) {
                tbVehicle.setAuditTime(cell12.getDateCellValue());
            }



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

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

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

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

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

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

        }

        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<TbVehicle> enterpriseList = list.subList(start, end);

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

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

        return count;
    }

}
