package nckd.jimin.jyyy.fi.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.exception.ErrorCode;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.fi.er.business.trip.model.DailyVehicleBillModel;
import kd.fi.er.business.trip.model.TripReqbillModel;
import kd.fi.er.business.trip.supplier.didi.invoke.DiDiTripDailyVehicleBillInvoke;
import kd.fi.er.business.trip.supplier.didi.systemexternal.DiDiServiceUtil;
import kd.fi.er.business.trip.supplier.didi.systemexternal.DiDiTripCarRegulationUtil;
import kd.fi.er.business.trip.util.TripCityUtil;
import kd.fi.er.business.trip.util.TripCommonUtil;
import kd.fi.er.business.trip.util.TripSyncDataMappingUtil;
import org.apache.commons.lang.StringUtils;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 滴滴用车申请，全复制的7.0.1的标准源码后改造
 * @author wanghaiwu_kd
 * @date 2025/06/16
 */
public class DiDiTripDailyVehicleBillCusInvoke extends DiDiTripDailyVehicleBillInvoke {
    private static final Log logger = LogFactory.getLog(DiDiTripDailyVehicleBillCusInvoke.class);
    @Override
    protected JSONObject convertPushBill(Object info, boolean updateFlag) {
        DailyVehicleBillModel reqbill = (DailyVehicleBillModel)info;
        String out_approval_id = reqbill.getBillNo();
        logger.info("商旅集成,滴滴用车申请单,推送单据,开始数据转换,出差单号:" + out_approval_id);
        Map<String, String> supplierMap = TripCommonUtil.getTripServiceInfo(this.supplier());
        String client_id = (String)supplierMap.get("appkey");
        String company_id = (String)supplierMap.get("orationid");

        String access_token;
        try {
            access_token = DiDiServiceUtil.getCacheToken(new Date());
        } catch (KDBizException var24) {
            this.tripSyncLogParam.setRequesturl(TripCommonUtil.getTravelNoOneApiUrl("tokenurlkey"));
            this.tripSyncLogParam.setStatus("B");
            throw new KDBizException(new ErrorCode("doPost", String.format(ResManager.loadKDString("执行请求过程中出现异常。%s", "DiDiTripDailyVehicleBillInvoke_0", "fi-er-business", new Object[0]), var24)), new Object[0]);
        }

        if (access_token == null) {
            this.tripSyncLogParam.setMessage(String.format(ResManager.loadKDString("商旅集成,用车单号:%s,获取滴滴token为空,请检查配置!", "DiDiTripDailyVehicleBillInvoke_1", "fi-er-business", new Object[0]), out_approval_id));
            this.tripSyncLogParam.setStatus("B");
            return null;
        } else {
            String phone = reqbill.getApplyEmpPhone();
            String vehicletype = reqbill.getVehicletype();
            int approval_type = 3;

            String regulation_id = DiDiTripCarRegulationUtil.getUserTripCarRegulationByVehicle(phone, approval_type);
            if (StringUtils.isBlank(regulation_id)) {
                this.tripSyncLogParam.setMessage(String.format(ResManager.loadKDString("商旅集成,用车单号:%s,获取出差用车制度为空,请检查配置!", "DiDiTripDailyVehicleBillInvoke_2", "fi-er-business", new Object[0]), out_approval_id));
                this.tripSyncLogParam.setStatus("B");
                return null;
            } else {
                String reason = reqbill.getDesc();
                String timestamp = String.valueOf(System.currentTimeMillis() / 1000L);
                HashMap<String, Object> signMap = new HashMap();
                signMap.put("client_id", client_id);
                signMap.put("company_id", company_id);
                signMap.put("access_token", access_token);
                signMap.put("regulation_id", regulation_id);
                signMap.put("out_approval_id", out_approval_id);
                signMap.put("phone", phone);
                signMap.put("type", 1);
                QFilter uFilter = new QFilter("server", "=", this.supplier());
                uFilter.and(new QFilter("datatype", "=", "bos_org"));
                Map<Object, Object> dataOrgMappingMap = TripSyncDataMappingUtil.getDataMappingMapByFilter(uFilter, "innerdataid", "outdataid");
                Object budgetCenterId = null;
                if (dataOrgMappingMap != null && dataOrgMappingMap.size() > 0) {
                    budgetCenterId = TripSyncDataMappingUtil.getBudgetCenterId(reqbill, (TripReqbillModel)null, dataOrgMappingMap);
                }

                if (budgetCenterId != null) {
                    signMap.put("budget_center_id", budgetCenterId);
                }

                signMap.put("approval_type", approval_type);
                signMap.put("reason", reason.trim());
                JSONObject jsonObject = converTravelDetailInfo(reqbill, approval_type);
                signMap.put("business_trip_detail", gbEncoding(jsonObject.toString()));
                signMap.put("timestamp", timestamp);
                JSONObject tripReqObj = new JSONObject();
                if (updateFlag) {
                    QFilter updateFilter = new QFilter("server", "=", this.supplier());
                    updateFilter.and(new QFilter("datatype", "=", "er_dailyvehicle"));
                    updateFilter.and(new QFilter("number", "=", out_approval_id));
                    Map<Object, Object> updateDataOrgMappingMap = TripSyncDataMappingUtil.getDataMappingMapByFilter(updateFilter, "number", "outdataid");
                    logger.info("out_approval_id{}", out_approval_id);
                    Object o = updateDataOrgMappingMap.get(out_approval_id);
                    if (o != null) {
                        signMap.put("approval_id", o);
                        tripReqObj.put("approval_id", o);
                    }
                }

                String tripreqSignKey = DiDiServiceUtil.genSign(signMap, (String)supplierMap.get("reservedfield1"));
                tripReqObj.put("client_id", client_id);
                tripReqObj.put("company_id", company_id);
                tripReqObj.put("access_token", access_token);
                tripReqObj.put("timestamp", timestamp);
                tripReqObj.put("regulation_id", regulation_id);
                tripReqObj.put("out_approval_id", out_approval_id);
                tripReqObj.put("phone", phone);
                tripReqObj.put("approval_type", approval_type);
                tripReqObj.put("type", 1);
                if (budgetCenterId != null) {
                    tripReqObj.put("budget_center_id", budgetCenterId);
                }

                tripReqObj.put("reason", reason.trim());
                tripReqObj.put("business_trip_detail", jsonObject);
                tripReqObj.put("sign", tripreqSignKey);
                return tripReqObj;
            }
        }
    }


    private static String gbEncoding(String s) {
        StringBuilder buf = new StringBuilder();
        char[] c = s.toCharArray();
        char[] var3 = c;
        int var4 = c.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            char tmp = var3[var5];
            if (tmp > 255) {
                buf = buf.append("\\u").append(Integer.toHexString(tmp));
            } else {
                buf = buf.append(tmp);
            }
        }

        return buf.toString();
    }

    private JSONObject converTravelDetailInfo(DailyVehicleBillModel reqbill, int approval_type) {
        JSONObject travelDetailInfo = new JSONObject();
        Date startDate = reqbill.getStartdate();
        Date endDate = reqbill.getEnddate();
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTimeInMillis(endDate.getTime());
//        calendar.set(11, 23);
//        calendar.set(12, 59);
//        calendar.set(13, 59);
//        Date time = calendar.getTime();

        if (approval_type == 2) {
            travelDetailInfo.put("start_time", TripCommonUtil.date2TimeStamp(startDate, "yyyy-MM-dd HH:mm:ss"));
            travelDetailInfo.put("end_time", TripCommonUtil.date2TimeStamp(endDate, "yyyy-MM-dd HH:mm:ss"));
            travelDetailInfo.put("departure_city_id", TripCityUtil.getDiDiCityId(reqbill.getVehiclecity()).get(reqbill.getVehiclecity()));
            travelDetailInfo.put("destination_city_id", TripCityUtil.getDiDiCityId(reqbill.getVehiclecity()).get(reqbill.getVehiclecity()));
            travelDetailInfo.put("departure_city", reqbill.getVehiclecityName());
            travelDetailInfo.put("destination_city", reqbill.getVehiclecityName());
            travelDetailInfo.put("trip_times", reqbill.getVehiclenumber());
        } else if (approval_type == 3) {
//            Calendar instance = Calendar.getInstance();
//            instance.setTime(time);
//            instance.add(11, 6);
//            instance.add(13, 1);
//            Date newEndDate = instance.getTime();

            travelDetailInfo.put("start_time", TripCommonUtil.date2TimeStamp(startDate, "yyyy-MM-dd HH:mm:ss"));
            travelDetailInfo.put("end_time", TripCommonUtil.date2TimeStamp(endDate, "yyyy-MM-dd HH:mm:ss"));

            //用车城市
            JSONArray trips = new JSONArray();
            JSONObject trip = new JSONObject();

            trip.put("city_id", TripCityUtil.getDiDiCityId(reqbill.getVehiclecity()).get(reqbill.getVehiclecity()));
            trip.put("city", reqbill.getVehiclecityName());

            trips.add(trip);
            travelDetailInfo.put("trips", trips);

            //打车次数
            travelDetailInfo.put("trip_times", -1);
        }

        return travelDetailInfo;
    }
}
