package com.zcloud.primeport.plan.mjDevice;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.zcloud.gbscommon.dahuaDevice.DaHuaDeviceCommon;
import com.zcloud.gbscommon.dahuaDevice.DhuaConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcloud.gbscommon.hkDevice.HKDeviceUtil;
import com.zcloud.gbscommon.utils.DateUtil;
import com.zcloud.gbscommon.utils.Tools;
import com.zcloud.gbscommon.zclouduser.facade.ZcloudUserFacade;
import com.zcloud.gbscommon.zclouduser.request.ZcloudUserImgQry;
import com.zcloud.gbscommon.zclouduser.response.ZcloudUserImgBase64Co;
import com.zcloud.primeport.persistence.dataobject.ClosedAreaCarApplyDO;
import com.zcloud.primeport.persistence.dataobject.ClosedAreaPersonApplyDO;
import com.zcloud.primeport.persistence.dataobject.VehicleApplyDO;
import com.zcloud.primeport.persistence.repository.ClosedAreaCarApplyRepository;
import com.zcloud.primeport.persistence.repository.ClosedAreaPersonApplyRepository;
import com.zcloud.primeport.persistence.repository.VehicleApplyRepository;
import com.zcloud.primeport.plan.mjDevice.dto.CarEnum;
import com.zcloud.primeport.plan.mjDevice.dto.OneLevelCarSaveDto;
import com.zcloud.primeport.plan.mjDevice.dto.TwoLevelCar;
import com.zcloud.primeport.plan.mjDevice.dto.TwoLevelUser;
import jodd.util.Base64;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 一级人员门禁对接  前缀
 *
 */
@Component
public class TwoCarUtil {
    @Resource
    private ClosedAreaCarApplyRepository closedAreaCarApplyRepository;
    @Resource
    private VehicleApplyRepository vehicleApplyRepository;
    @Resource
    private OneLevelCarUtil oneLevelCarUtil;


    private static Integer dockFlag = 0;
    private static String prefix;

    /*
     * 定时任务对接二级口门车辆
     * 单个异常跳过不影响其他车辆同步
     * */
    public void scheduledCarCompany() {
        if (!dockFlag.equals(1)) return;
        // 所有今日有效的分公司/相关方二级口门车（car_belong_type IN 1,2,3,5）
        List<TwoLevelCar> fgsCarList = closedAreaCarApplyRepository.getFgsCarToDay(null);
        for (TwoLevelCar twoLevelCar : fgsCarList) {
            try {
                HKDeviceUtil.saveOrUpdCar(twoLevelCar.getLicenceNo(), 0);
                HKDeviceUtil.vehicleTopUp(twoLevelCar.getLicenceNo(), 0,
                        twoLevelCar.getHkIndexCode(), twoLevelCar.getKhParkSysCode(),
                        DateUtil.date2Str(new Date(), "yyyy-MM-dd"),
                        DateUtil.date2Str(new Date(), "yyyy-MM-dd"));
            } catch (Exception e) {
                System.err.println("二级门禁分公司车辆同步失败, licenceNo=" + twoLevelCar.getLicenceNo() + ", 原因: " + e.getMessage());
            }
        }
        // 所有今日有效的临时二级口门车（car_belong_type = 4）
        List<TwoLevelCar> tmpCarList = closedAreaCarApplyRepository.dockTmpCarLevelTwo(null);
        for (TwoLevelCar twoLevelCar : tmpCarList) {
            try {
                HKDeviceUtil.saveOrUpdCar(twoLevelCar.getLicenceNo(), 0);
                HKDeviceUtil.vehicleTopUp(twoLevelCar.getLicenceNo(), 0,
                        twoLevelCar.getHkIndexCode(), twoLevelCar.getKhParkSysCode(),
                        DateUtil.date2Str(new Date(), "yyyy-MM-dd"),
                        DateUtil.date2Str(new Date(), "yyyy-MM-dd"));
            } catch (Exception e) {
                System.err.println("二级门禁临时车辆同步失败, licenceNo=" + twoLevelCar.getLicenceNo() + ", 原因: " + e.getMessage());
            }
        }
    }

    public static void main(String[] args) throws Exception {
    }

    /**
     * 审批时候的主入口 传一个申请id来
     * 同步二级门禁(海康) + 一级门禁(车行系统)
     * 所有类型都走一级检查流程：有权限且有效则跳过，无权限则按类型新增
     */
    public void levelTwoCarCompanyByApplyId(Long applyId) {
        if (!dockFlag.equals(1)) return;
        ClosedAreaCarApplyDO byId = closedAreaCarApplyRepository.getById(applyId);
        Integer carBelongType = byId.getCarBelongType();
        // 二级门禁(海康)同步 — 所有类型都需要
        if (carBelongType.equals(4)) {
            dockTmpCarLevelTwo(byId.getLicenceNo());
        } else {
            dockFgsCarLevelTwo(byId.getLicenceNo());
        }
        // 一级门禁(车行系统)同步 — 先查vehicle_apply表该车是否有有效权限，没有再新增
        dockOneLevelCar(byId, carBelongType);
    }

    /**
     * 对接一级门禁车行系统
     * 在vehicle_apply表中查该车牌是否有审核通过且有进出港权限的有效记录，
     * 有则不覆盖，无则按类型新增
     */
    private void dockOneLevelCar(ClosedAreaCarApplyDO byId, Integer carBelongType) {
        // 在vehicle_apply表查该车牌是否有审核通过的长期/有效权限
        // 条件：审核通过(2)或无需审批(4)、有进出港权限(1)、当前在访问时间内
        String today = DateUtil.date2Str(new Date(), "yyyy-MM-dd");
        QueryWrapper<VehicleApplyDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("licence_no", byId.getLicenceNo());
        queryWrapper.in("audit_flag", 2, 4);
        queryWrapper.eq("mkmj_permission", 1);
        queryWrapper.le("visit_start_time", today);
        queryWrapper.ge("visit_end_time", today);

        if (!vehicleApplyRepository.list(queryWrapper).isEmpty()) {
            // vehicle_apply已有有效权限 → 不覆盖
            return;
        }

        // 无有效权限 → 走新增逻辑
        OneLevelCarSaveDto saveDto = new OneLevelCarSaveDto();
        saveDto.setTruckNo(byId.getLicenceNo());
        saveDto.setTruckCardColor(byId.getLicenceType());
        saveDto.setTruckTypCod(CarEnum.getMenuKeyByPath(byId.getVehicleType()));
        saveDto.setPortId("0");
        saveDto.setDriverNam(byId.getDrivingUserName());
        saveDto.setLinkTel(byId.getUserPhone());
        saveDto.setValidDte(today);
        saveDto.setRecTim(DateUtil.date2Str(new Date()));
        saveDto.setYqlCheckFlag("1");
        saveDto.setIsNeedCheck("0");

        if (carBelongType.equals(3) || carBelongType.equals(4)) {
            // 临时车(4)和相关方(3) → 临时车辆保存
            tmpVehicleSave(saveDto);
        } else {
            // 其他类型(1股份/2分公司/5分公司内部) → 内部车辆保存
            oneLevelCarUtil.internalVehicleSave(saveDto);
        }
    }

    //    对接一级口门车辆
    public void tmpVehicleSave(OneLevelCarSaveDto oneLevelCarSaveDto) {
        if (dockFlag.equals(1)) {
            oneLevelCarSaveDto.setIsNeedCheck("0");
            String body = HttpRequest.post(prefix + "HD_QHD_IGATE_1.0/webresources/login/CTruck/qaSaveTemp").body(new JSONObject(oneLevelCarSaveDto).toString()).execute().body();
        }
    }

    /**
     * 对接分公司二级口门车
     */
    public void dockFgsCarLevelTwo(String licence_no) {
        if (!dockFlag.equals(1)) return;
        List<TwoLevelCar> carList = closedAreaCarApplyRepository.getFgsCarToDay(licence_no);
        for (TwoLevelCar twoLevelCar : carList) {
            // todo 车牌号转一下类型
            HKDeviceUtil.saveOrUpdCar(twoLevelCar.getLicenceNo(), 0);
            HKDeviceUtil.vehicleTopUp(twoLevelCar.getLicenceNo(), 0, twoLevelCar.getHkIndexCode(), twoLevelCar.getKhParkSysCode(), DateUtil.date2Str(new Date(), "yyyy-MM-dd"), DateUtil.date2Str(new Date(), "yyyy-MM-dd"));
        }

    }

    /**
     * 对接临时访客二级口门车
     */
    public void dockTmpCarLevelTwo(String licence_no) {
        if (!dockFlag.equals(1)) return;
        List<TwoLevelCar> carList = closedAreaCarApplyRepository.dockTmpCarLevelTwo(licence_no);
        for (TwoLevelCar twoLevelCar : carList) {
            // todo 车牌号转一下类型
            HKDeviceUtil.saveOrUpdCar(twoLevelCar.getLicenceNo(), 0);
            HKDeviceUtil.vehicleTopUp(twoLevelCar.getLicenceNo(), 0, twoLevelCar.getHkIndexCode(), twoLevelCar.getKhParkSysCode(), DateUtil.date2Str(new Date(), "yyyy-MM-dd"), DateUtil.date2Str(new Date(), "yyyy-MM-dd"));
        }
    }


    private static <T> List<List<T>> partition(List<T> list, int size) {
        List<List<T>> partitions = new ArrayList<>();
        for (int i = 0; i < list.size(); i += size) {
            partitions.add(list.subList(i, Math.min(i + size, list.size())));
        }
        return partitions;
    }


}
