package com.sckw.transport.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.sckw.contract.api.RemoteContractService;
import com.sckw.core.model.constant.Global;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.easyexcel.ExcelImportListener;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.fleet.api.RemoteFleetService;
import com.sckw.manage.api.RemoteManageService;
import com.sckw.order.api.dubbo.TradeOrderInfoService;
import com.sckw.product.api.dubbo.GoodsInfoService;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.KwsEntDeptDto;
import com.sckw.transport.model.dto.CarrierOrderImportDto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc 物流订单导入
 * @author zk
 * @date 2023/12/10 0010
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class KwtLogisticsOrderImportService {
    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    RemoteSystemService remoteSystemService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    TradeOrderInfoService tradeOrderInfoService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    GoodsInfoService goodsInfoService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 8000)
    RemoteFleetService fleetService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteContractService remoteContractService;

    @DubboReference(version = "1.0.0", group = "design", check = false, timeout = 6000)
    RemoteManageService remoteManageService;

    @Autowired
    KwtTransportCommonService transportCommonService;


    /**
     * @param {}
     * @desc 导出
     * @author zk
     * @date 2023/12/10
     **/
    public HttpResult importExcel(MultipartFile file) {
        /**文件存储**/
        //importFileSave(file);

        /**参数校验**/
        HttpResult result = this.checkParams(file);
        if (result.getCode() != HttpStatus.SUCCESS_CODE) {
            return result;
        }

        List<CarrierOrderImportDto> carrierOrderExcels = (List)result.getData();
        result = checkParams(carrierOrderExcels);
        if (result.getCode() != HttpStatus.SUCCESS_CODE) {
            return HttpResult.error("导入数据存在已上报，请核对再上传！", result.getData());
        }


        return result;
    }

    /**
     * @param file 上传文件
     * @desc 参数校验
     * @author zk
     * @date 2023/12/10
     **/
    public HttpResult checkParams(MultipartFile file) {
        ExcelReader excelReader = null;
        try {
            /*数据校验**/
            if (ExcelUtil.checkExcel(file)) {
                return HttpResult.error("请上传Excel格式的文件！");
            }

            ExcelImportListener importListener = new ExcelImportListener();
            InputStream inputStream = file.getInputStream();
            excelReader = EasyExcel.read(inputStream, importListener).build();

            ReadSheet readSheet = EasyExcel.readSheet( 0) .headRowNumber(2).head(CarrierOrderImportDto.class).build();
            excelReader.read(readSheet);
            if (importListener.getErrorList().size() > 0) {
                return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "数据格式不正确，请确认！", importListener.getErrorList());
            }
            if (importListener.getDataList().size() == 0) {
                return HttpResult.error("导入数据不能空！");
            }

            return HttpResult.ok(importListener.getDataList());
        } catch (Exception e) {
            e.printStackTrace();
            return HttpResult.error("承运订单信息导入异常！");
        } finally {
            if (excelReader != null) {
                excelReader.finish();
            }
        }
    }

    /**
     * @param carrierOrderExcels 上传信息
     * @desc 校验上传参数
     * @author zk
     * @date 2023/12/10
     **/
    public HttpResult checkParams(List<CarrierOrderImportDto> carrierOrderExcels) {
        int rowNum = Global.NUMERICAL_TWO;
        List<String> errorList = new ArrayList();
        List<Map<String, Object>> orderList = new ArrayList<>();
        for (CarrierOrderImportDto orderExcel:carrierOrderExcels) {
            rowNum ++;
            StringBuilder msg = new StringBuilder("第"+ rowNum +"行数据有误,");
            //msg.append("车牌号"+ truck.getTruckNo() +"已上报！");

            //托运单位[必填] checkFirmName（企业是否存在、是否是合作托运企业）
            EntCacheResDto checkFirm = remoteSystemService.queryEntByName(orderExcel.getCheckFirmName());
            if (checkFirm == null) {
                msg.append("托运单位"+ orderExcel.getCheckFirmName() +"不存在！");
            } else {

            }

            //承运单位[必填] carrierFirmName（企业是否存在、是否是本企业或下属企业）
            EntCacheResDto carrierFirm = remoteSystemService.queryEntByName(orderExcel.getCarrierFirmName());
            if (checkFirm == null) {
                msg.append("承运单位"+ orderExcel.getCarrierFirmName() +"不存在！");
            } else {
                if (carrierFirm.getId().equals(LoginUserHolder.getEntId())) {

                }

                List<KwsEntDeptDto> entDeptDtos = remoteSystemService.queryEntDeptByPid(LoginUserHolder.getEntId());
            }



            //货物分类[必填] goodsType

            //合同编号[必填] contractNo

            //计费方式[必填] billingMode

            //运价[必填] price

            //运价单位[必填] priceType

            //税率(%)[必填] taxRate

            //分配承运量[必填] amount

            //分配承运量单位[必填] unit

            //合理耗损(‰) loss

            //扣亏货值 goodsPrice

            //扣亏货值单位 goodsPriceUnit

            //计划发货时间[必填] loadTime

            //计划卸货时间[必填] unloadTime

            //结算周期[必填] settlementCycle

            //支付方式[必填] payment

            //装货地址[必填] loadAddress

            //卸货地址[必填] unloadAddress

        }


        return HttpResult.ok();
    }

}
