package com.mortals.xhx.protocol.complex.matter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.common.Rest;
import com.mortals.xhx.protocol.complex.AbstractComplexService;
import com.mortals.xhx.protocol.complex.ComplexApiRest;
import com.mortals.xhx.protocol.complex.matter.model.req.AcceptReq;
import com.mortals.xhx.protocol.complex.matter.model.req.DeviceLoginReq;
import com.mortals.xhx.protocol.complex.matter.model.req.FindHandlingReq;
import com.mortals.xhx.protocol.complex.matter.model.req.ImplementationReq;
import com.mortals.xhx.protocol.complex.matter.model.rsp.*;
import com.mortals.xhx.protocol.complex.matter.model.rsp.implement.ImplementDetailInfo;
import com.mortals.xhx.protocol.complex.matter.model.rsp.material.MaterialInfo;
import com.mortals.xhx.protocol.complex.matter.model.rsp.matter.MatterWorkInfo;
import com.mortals.xhx.protocol.complex.matter.model.rsp.work.WorkInfo;
import com.mortals.xhx.protocol.complex.matter.service.IComplexMatterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 综合窗口业务实现类
 *
 * @author: zxfei
 * @date: 2023/10/30 14:53
 */
@Service("complexMatterService")
@Slf4j
public class ComplexMatterServiceImpl extends AbstractComplexService implements IComplexMatterService {



    //token有效期 10小时
    @Override
    public Rest<LoginRspInfo> deviceLogin(DeviceLoginReq loginReq) {
        String deviceLoginApi = host + "self-device-info/login";
        log.info("deviceLoginApi url:{} req:{}", deviceLoginApi, JSON.toJSONString(loginReq));
        String rest = HttpUtil.post(deviceLoginApi, JSON.toJSONString(loginReq));
        log.info("deviceLoginApi resp:{}", rest);
        ComplexApiRest<LoginRspInfo> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<LoginRspInfo>>() {
        });
        if (complexApiRest.getSuccess()) {
            //更新token
            String deviceLoginToken = complexApiRest.getResult().getToken();
            String deviceLogo = complexApiRest.getResult().getSelfDeviceInfo().getDeviceLogo();
            //this.tokenMap.put(deviceLogo, deviceLoginToken);
            this.setToken(deviceLoginToken);
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }

    @Override
    public Rest<String> uploadFile(String deviceLogo, byte[] bytes, String fileName) {
        String uploadApi = host + "common/uploadFileToFtp?conversionImage=Y";
        HttpRequest request = HttpRequest.post(uploadApi);
        String deviceToken = checkToken(deviceLogo);
        request.form("file", bytes, fileName);
        String uploadRest = request.header("X-Access-Token", deviceToken).execute().body();
        log.info("uploadApi resp:{}", uploadRest);
        ComplexApiRest<String> complexApiRest = JSON.parseObject(uploadRest, new TypeReference<ComplexApiRest<String>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }

    @Override
    public Rest<List<AcceptRspInfo>> accept(String deviceLogo, AcceptReq acceptReq) {
        String deviceLoginApi = host + "self-device-info/acceptHandling";
        log.info("accept req==>{}", JSON.toJSONString(acceptReq));
        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createPost(deviceLoginApi)
                .header("X-Access-Token", deviceToken)
                .body(JSON.toJSONString(acceptReq))
                .execute().body();
        log.info("accept resp==>{}", rest);
        ComplexApiRest<List<AcceptRspInfo>> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<List<AcceptRspInfo>>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }


    @Override
    public Rest<MatterListInfo> findMatters(String deviceLogo, ImplementationReq implementationReq) {
        String mattersApi = host + "event-implementation/list";
        Map<String, String> paramMap = new HashMap<>();
        // 将Map中的属性值转为字符串
        for (Map.Entry<String, Object> entry : BeanUtil.beanToMap(implementationReq, false, true).entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            String stringValue = String.valueOf(value);
            paramMap.put(key, stringValue);
        }
        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createGet(mattersApi)
                .header("X-Access-Token", deviceToken)
                .formStr(paramMap)
                .execute().body();
        log.info("complexApiRest resp:{}", rest);
        ComplexApiRest<MatterListInfo> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<MatterListInfo>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }


    @Override
    public Rest<List<MaterialInfo>> getMaterialByEvent(String deviceLogo, String eventId) {
        String mattersApi = host + "material/findList";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("eventId", eventId);
        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createGet(mattersApi)
                .header("X-Access-Token", deviceToken)
                .formStr(paramMap)
                .execute().body();
        log.info("mattersApi resp:{}", rest);
        ComplexApiRest<List<MaterialInfo>> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<List<MaterialInfo>>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }

    @Override
    public Rest<List<MatterWorkInfo>> doWorkMatterSearch(String deviceLogo, String eventIds) {
        String mattersApi = host + "bus-situation-material/getSituationMaterialTreeByEventIds";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("eventIds", eventIds);
        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createGet(mattersApi)
                .header("X-Access-Token", deviceToken)
                .formStr(paramMap)
                .execute().body();
        log.info("mattersApi resp:{}", rest);
        ComplexApiRest<List<MatterWorkInfo>> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<List<MatterWorkInfo>>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());

        }
        return Rest.fail(complexApiRest.getMessage());
    }

    @Override
    public Rest<WorkInfo> getWorkMatter(String deviceLogo, List<String> eventIdList) {
        String mattersApi = host + "event-implementation/getDynamicFormByEventIds";

        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createPost(mattersApi)
                .header("X-Access-Token", deviceToken)
                .body(JSON.toJSONString(eventIdList))
                .execute().body();
        ComplexApiRest<WorkInfo> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<WorkInfo>>() {
        });
        log.info("getDynamicFormByEventIds resp:{}", rest);
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }

    @Override
    public Rest<ImplementDetailInfo> getImplement(String deviceLogo, String eventId) {
        String implementDetailApi = host + "event-implementation/get-by-id/" + eventId;

        String rest = HttpUtil.createGet(implementDetailApi)
                .execute().body();
        log.info("implementDetailApi resp:{}", rest);
        ComplexApiRest<ImplementDetailInfo> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<ImplementDetailInfo>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }

    @Override
    public Rest<List<DictInfo>> queryDict(String deviceLogo, String dict) {
        String mattersApi = host + "common/queryDict";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("dict", dict);
        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createGet(mattersApi)
                .header("X-Access-Token", deviceToken)
                .formStr(paramMap)
                .execute().body();
        log.info("dict resp:{}", rest);
        ComplexApiRest<List<DictInfo>> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<List<DictInfo>>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }

    /**
     * 查询已受理事项列表
     * @param deviceLogo
     * @param findHandlingReq
     * @return
     */
    @Override
    public Rest<HandlingRspInfoList> findHandlingPage(String deviceLogo, FindHandlingReq findHandlingReq) {
        String mattersApi = host + "handling/findPageWithPermission";
        if(findHandlingReq.getCurrent()==null){
            findHandlingReq.setCurrent(1);
        }
        if(findHandlingReq.getSize()==null){
            findHandlingReq.setSize(10);
        }
        findHandlingReq.setOrderByLimitTime("true");
//        findHandlingReq.setWaitHandlingSearch("Y");
//        findHandlingReq.setIsTongBan("N");
        Map<String, String> paramMap = new HashMap<>();
        // 将Map中的属性值转为字符串
        for (Map.Entry<String, Object> entry : BeanUtil.beanToMap(findHandlingReq, false, true).entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            String stringValue = String.valueOf(value);
            paramMap.put(key, stringValue);
        }
        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createGet(mattersApi)
                .header("X-Access-Token", deviceToken)
                .formStr(paramMap)
                .execute().body();
        log.info("findHandlingPage resp:{}", rest);
        ComplexApiRest<HandlingRspInfoList> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<HandlingRspInfoList>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }

    @Override
    public Rest<Object> downloadFileFtp(String deviceLogo, FindHandlingReq findHandlingReq) {
        String mattersApi = host + "/common/downloadFileFtp";

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("url", findHandlingReq.getUrl());
        String deviceToken = checkToken(deviceLogo);
        byte[] rest = HttpUtil.createGet(mattersApi)
                .header("X-Access-Token", deviceToken)
                .formStr(paramMap).timeout(-1)
                .executeAsync().bodyBytes();
        //log.info("downloadFileFtp resp:{}", rest);
        if(rest.length>1024){
            String base64Str = Base64.getEncoder().encodeToString(rest);
            return Rest.ok("成功",base64Str);
        }
        return Rest.fail("下载文件不存在");
    }


    @Override
    public Rest<List<MaterialInfo>> getMaterialByEventAndSituation(String deviceLogo, ImplementationReq implementationReq) {
        String mattersApi = host + "consulting-service/getMaterialByEventAndSituation";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("eventId", implementationReq.getEventId());
        jsonObject.put("itemsIds", implementationReq.getItemsIds());

        String deviceToken = checkToken(deviceLogo);
        String rest = HttpUtil.createPost(mattersApi)
                .header("X-Access-Token", deviceToken)
                .body(jsonObject.toJSONString())
                .execute().body();
        log.info("getMaterialByEventAndSituation resp==>{}", rest);
        ComplexApiRest<List<MaterialInfo>> complexApiRest = JSON.parseObject(rest, new TypeReference<ComplexApiRest<List<MaterialInfo>>>() {
        });
        if (complexApiRest.getSuccess()) {
            return Rest.ok(complexApiRest.getMessage(), complexApiRest.getResult());
        }
        return Rest.fail(complexApiRest.getMessage());
    }


    private String checkToken(String deviceLogo) {
        String deviceToken = tokenMap.getOrDefault(deviceLogo, "");
        if (ObjectUtils.isEmpty(deviceToken)) {
            deviceToken = getToken(deviceLogo);
        }
        return deviceToken;
    }

    public static void main(String[] args) {
        // Define the URL where you want to upload the file
        String uploadUrl = "http://example.com/upload";

        // Define the path of the file you want to upload
        String filePath = "/path/to/your/file.txt";

        byte[] bytes = "111".getBytes();

        // Create an HTTP request
        HttpRequest request = HttpRequest.post(uploadUrl);

        // Attach the file to the request
        request.form("file", bytes, "1.png");

        // Send the request and get the response
        HttpResponse response = request.execute();

        String body = request.execute().body();

        // Check the response status
        int status = response.getStatus();
        if (status == 200) {
            System.out.println("File uploaded successfully!");
        } else {
            System.out.println("File upload failed. Status code: " + status);
        }

    }
}
