package com.njzscloud.supervisory.hsoa.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.core.tuple.Tuple2;
import com.njzscloud.common.core.utils.ImgUtil;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.oss.util.AliOSS;
import com.njzscloud.supervisory.hsoa.Hsoa;
import com.njzscloud.supervisory.hsoa.constant.PushType;
import com.njzscloud.supervisory.hsoa.mapper.HsoaMapper;
import com.njzscloud.supervisory.hsoa.pojo.entity.HsoaRecode;
import com.njzscloud.supervisory.hsoa.pojo.param.PushProvincialSaveParam;
import com.njzscloud.supervisory.hsoa.pojo.param.PushProvincialUploadParam;
import com.njzscloud.supervisory.hsoa.pojo.result.HsoaResult;
import com.njzscloud.supervisory.hsoa.pojo.result.UploadResult;
import com.njzscloud.supervisory.order.pojo.result.OrderPagingResult;
import com.njzscloud.supervisory.order.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.njzscloud.supervisory.hsoa.pojo.param.PushProvincialUploadParam.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class HsoaService extends ServiceImpl<HsoaMapper, HsoaRecode> implements IService<HsoaRecode> {

    public HsoaResult<?> pushProvincialSave(OrderPagingResult detail) {
        log.info("上传数据：{}", Jackson.toJsonStr(detail));

        List<String> route = detail.getRoute();
        PushProvincialSaveParam param = new PushProvincialSaveParam()
                .setHandleInfo(new PushProvincialSaveParam.HandleInfo()
                        .setApproveDate(detail.getOutTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setApproveUserName(detail.getCheckerName())
                        // .setCreateTime(detail.getCreateTime())
                        // .setCreaterName(detail.getContacts())
                        // .setDisposalSiteCode("")
                        .setDisposalSiteName(detail.getStationName())
                        // .setHandleCraft("")
                        // .setHandleLicenseName("")
                        // .setHandleLicenseNum("")
                        .setHandleMethod("资源化利用")
                        .setLongitude(detail.getStationLng().toString())
                        .setLatitude(detail.getStationLat().toString())
                        // .setHANDLE_LICENSE_FILE("")
                        // .setLicenseValidStartDate("")
                        // .setLicenseValidEndDate("")
                        .setLinkPhone(detail.getCheckerPhone())
                        // .setSuperviseUnitName("")
                        // .setUpdateTime("")
                        // .setUpdaterName("")
                        .setHandleVoucherFile(upload(detail.getCheckPhoto(), HANDLE_VOUCHER_FILE))
                        .setWeight(new BigDecimal(detail.getSettleWeight()).divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP).toPlainString())
                )
                .setReviewInfo(new PushProvincialSaveParam.ReviewInfo()
                                .setCgAreaName(detail.getProvinceName() + detail.getCityName() + detail.getAreaName())
                                .setCgReviewOpinion(StrUtil.isBlank(detail.getShiAuditMemo()) ? "同意" : detail.getShiAuditMemo())
                                .setCgReviewTime(detail.getShiAuditTime())
                                // .setCgUnitCode("")
                                .setCgUnitName(detail.getAreaName() + "城管")
                                .setCgUserId(detail.getQuAuditUserId() == null ? (detail.getShiAuditUserId() == null ? null : detail.getShiAuditUserId().toString()) : detail.getQuAuditUserId().toString())
                                // .setCgUserName(detail.getQuAuditUserName() == null ? (detail.getShiAuditUserName() == null ? null : detail.getShiAuditUserName()) : detail.getQuAuditUserName())
                                .setCgUserName(detail.getAreaName().contains("琅琊") ? "陶明莉" : (detail.getAreaName().contains("南谯") ? "刘浩" : (detail.getQuAuditUserName() == null ? (detail.getShiAuditUserName() == null ? null : detail.getShiAuditUserName()) : detail.getQuAuditUserName())))
                        // .setCreateTime(detail.getCreateTime())
                        // .setCreaterName(detail.getContacts())
                        // .setCG_REVIEW_FILE("")
                )
                .setTransportOrder(new PushProvincialSaveParam.TransportOrder()
                        .setAddress(detail.getAddress())
                        .setAppointmentStartDate(detail.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setAppointmentStartTime(detail.getCreateTime().format(DateTimeFormatter.ofPattern("HH:mm")))
                        .setAreaCode(detail.getArea())
                        .setAreaName(detail.getAreaName())
                        .setCityCode(detail.getCity())
                        .setCityName(detail.getCityName())
                        .setConstructionUnitCreditCode(detail.getUscc())
                        .setConstructionUnitName(detail.getCompanyName())
                        .setConstructionUnitDirector(detail.getContacts())
                        .setConstructionUnitPhone(detail.getPhone())
                        .setEmissionSource(detail.getCompanyName() == null ? detail.getContacts() : detail.getCompanyName())
                        .setEstimateWeight(detail.getEstimatedQuantity())
                        .setGarbageSceneFile(upload(detail.getSitePhotos(), GARBAGE_SCENE_FILE))
                        .setEnterpriseHead(detail.getTransContacts())
                        .setHeadContact(detail.getTransPhone())
                        .setLatitude(detail.getLat() == null ? null : detail.getLat().toString())
                        .setLongitude(detail.getLng() == null ? null : detail.getLng().toString())
                        // .setOrderNumber(detail.getArea() + detail.getSn())
                        .setOrderStatus(90)
                        .setOrderType(detail.getCompanyName() == null ? 1 : 4)
                        .setProjectName(detail.getProjectName())
                        .setRegisterAddress(detail.getTransAddress())
                        .setSceneLinkName(detail.getContacts())
                        .setSceneLinkPhone(detail.getPhone())
                        .setStreetCode(detail.getTown())
                        .setStreetName(detail.getTownName())
                        .setTransportationEnterpriseId(detail.getTransCompanyId() == null ? null : detail.getTransCompanyId().toString())
                        .setTransportationEnterpriseName(detail.getTransCompanyName())
                        .setWasteTypeCode(detail.getGoodsName().contains("拆除") ? "4" :
                                (detail.getGoodsName().contains("装修") ? "5" :
                                        (detail.getGoodsName().contains("建筑") ? "3" : (detail.getGoodsName().contains("园林") ? "3" : (detail.getGoodsName().contains("拆迁") ? "4" : null)))
                                ))
                        .setWasteTypeName(detail.getGoodsName())
                        .setWorkUnitCreditCode(detail.getUscc())
                        .setWorkUnitDirector(detail.getContacts())
                        .setWorkUnitPhone(detail.getPhone())
                        .setWorkUnitName(detail.getCompanyName())
                )
                .setTransportOrderRecord(new PushProvincialSaveParam.TransportOrderRecord()
                        .setAbsorptionUnitName(detail.getStationCompanyName())
                        .setAuditStatus(3)
                        .setCarNo(detail.getLicensePlate())
                        .setAbsorptionUnitType("1")
                        .setAbsorptionUnitCode(detail.getStationUscc())
                        .setDriverLicense(detail.getDrivingLicenceNo())
                        .setEnterpriseHead(detail.getDriverName())
                        .setHeadContact(detail.getDriverPhone())
                        // .setEnterpriseTransportLicenseName("")
                        .setEnterpriseTransportLicenseNum(detail.getCertificateSn())
                        .setEstimateWeight(detail.getEstimatedQuantity())
                        .setHaulageStartTimeStr(detail.getTransTime())
                        .setHaulageEndTimeStr(detail.getOutTime())
                        // .setTRANS_LICENSE_FILE("")
                        .setGarbageLoadBeforeFile(upload(detail.getCargoPhoto(), GARBAGE_LOAD_BEFORE_FILE))
                        .setGarbageLoadAfterFile(upload(detail.getCargoPhoto(), GARBAGE_LOAD_AFTER_FILE))
                        .setLicenseValidityPeriodDateRange(detail.getShiAuditTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "-" + detail.getShiAuditTime().plusHours(24).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setLicenseValidityPeriodStartDate(detail.getShiAuditTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setLicenseValidityPeriodEndDate(detail.getShiAuditTime().plusHours(24).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setRoute(CollUtil.isEmpty(route) ? "" : String.join("-", route))
                        .setSuperviseUnitName(detail.getAreaName())
                        .setTransportDateRange(detail.getTransTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "-" + detail.getOutTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setTransportStartDate(detail.getTransTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setTransportEndDate(detail.getOutTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                        .setTransportationEnterpriseId(detail.getTransCompanyId() == null ? null : detail.getTransCompanyId().toString())
                        .setTransportationEnterpriseName(detail.getTransCompanyName())
                );
        // log.info(Jackson.toJsonStr(param));
        return Hsoa.pushProvincial(param);
        // return null;
    }

    private String upload(List<String> urls, String uploadPath) {
        if (CollUtil.isEmpty(urls)) return null;
        String url = urls.get(0);
        if (StrUtil.isBlank(url)) return null;
        url = url.substring(1);
        String[] split = url.split("/");
        if (split.length < 2) return null;
        Tuple2<InputStream, String> tuple2 = AliOSS.obtainFile(split[0], split[1]);
        InputStream in = tuple2.get_0();
        try {
            ByteArrayOutputStream out = ImgUtil.compress(in, 0.5, FileUtil.extName(split[1]), 1024 * 1024);
            byte[] bytes = out.toByteArray();
            UploadResult upload = Hsoa.upload(new PushProvincialUploadParam()
                    .setFile(new ByteArrayInputStream(bytes))
                    .setUploadPath(uploadPath)
            );
            if (upload.isSuccess()) {
                return upload.getUrl();
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("上传失败", e);
            return null;
        } finally {
            IoUtil.close(in);
        }
    }

    public PageResult<HsoaRecode> paging(PageParam pageParam, String orderSn, String licensePlate, PushType pushType, Boolean success, LocalDateTime startTime, LocalDateTime endTime) {
        Page<HsoaRecode> page = pageParam.toPage();
        page.addOrder(OrderItem.desc("create_time"), OrderItem.desc("id"));
        return PageResult.of(this.page(page, Wrappers.<HsoaRecode>lambdaQuery()
                .eq(StrUtil.isNotBlank(orderSn), HsoaRecode::getOrderSn, orderSn)
                .eq(StrUtil.isNotBlank(licensePlate), HsoaRecode::getLicensePlate, licensePlate)
                .eq(pushType != null, HsoaRecode::getPushType, pushType)
                .eq(success != null, HsoaRecode::getSuccess, success)
                .ge(startTime != null, HsoaRecode::getCreateTime, startTime)
                .le(endTime != null, HsoaRecode::getCreateTime, endTime)
        ));
    }
}
