package com.zcloud.primeport.plan.mjDevice;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.zcloud.gbscommon.dahuaDevice.DaHuaDeviceCommon;
import com.zcloud.gbscommon.dahuaDevice.DhuaConfig;
import com.zcloud.gbscommon.utils.DateUtil;
import com.zcloud.primeport.persistence.dataobject.XgfApplyPersonDO;
import com.zcloud.primeport.persistence.repository.XgfApplyPersonRepository;
import jodd.util.Base64;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 一级人员门禁对接  前缀
 *
 */
@Component
public class OnePersonUtil {
    @Resource
    private XgfApplyPersonRepository xgfApplyPersonRepository;
    //    @Value("${kmmj.dockflag}")
//    private Integer dockFlag;
//    @Value("${oneLevelPerson.prefix}")
//    private String prefix;
    private static Integer dockFlag = 0;
    private static String prefix = "https://skqhdg.porthebei.com:9008/yjkmRy/";
    private static String username = "shuangkong";
    private static String password = "qinan@202604";
    private static String clientId = "mkmj_management";
    private static String clientSecret = "5ef82f7c-9926-46a3-8d07-136fd054849c";

    /*
     * 刷入当日门禁权限有效期
     * */


    /**
     * 跟据身份证号码进行长期用户对接
     */
    public void dockLongTermUserByUserCardAndFaceImg(String userCard, String userUid, String username, String userFaceImages, String visitStartTime, String visitEndTime) throws Exception {
        if (!dockFlag.equals(1)) return ;
        DaHuaDeviceCommon daHuaDeviceCommon = getDaHuaDeviceCommon();
        JSONObject userByUserCard = daHuaDeviceCommon.getUserByUserCard(userCard).getJSONObject("data");
        if (userByUserCard.isEmpty()) {
            // 这个人不存在  保存用户
            Long generateId = daHuaDeviceCommon.getGenerateId();
            JSONObject userInfo = new JSONObject();
            JSONObject fileInfo = new JSONObject();
            List<JSONObject> dataList = new ArrayList();
            fileInfo.set("type", 3);
            fileInfo.set("index", 1);
            fileInfo.set("path", userFaceImages);
            dataList.add(fileInfo);
            userInfo.set("id", generateId);
            userInfo.set("personBiosignatures", dataList);
            userInfo.set("validStartTime", visitStartTime);
            userInfo.set("validEndTime", visitEndTime);
            userInfo.set("code", userUid);
            userInfo.set("name", username);
            userInfo.set("paperType", 111);
            userInfo.set("paperNumber", userCard);
            userInfo.set("departmentId", 1L);
            userInfo.set("personType", 0);
            daHuaDeviceCommon.saveUser(userInfo);
        }else {
            // 这个人存在  更新用户
            expirationDateRefreshedUserCard(userCard, visitStartTime, visitEndTime);
        }
    }

    /**
     * 批量新增用户
     */
    public void batchSaveUser(List<JSONObject> userList) throws Exception {
        if (!dockFlag.equals(1)) return ;
        DaHuaDeviceCommon daHuaDeviceCommon = getDaHuaDeviceCommon();
        JSONArray batchGenerateId = daHuaDeviceCommon.getBatchGenerateId(userList.size());
        for (int i = 0; i < batchGenerateId.size(); i++) {
            JSONObject entries = userList.get(i);
            entries.set("id", batchGenerateId.getInt(i));
        }
        daHuaDeviceCommon.batchSaveUser(userList);
    }

    /**
     * 跟据身份证号码进行用户门禁有效期刷新
     */
    public void expirationDateRefreshedUserCard(String userCard, String visitStartTime, String visitEndTime) throws Exception {
        if (!dockFlag.equals(1)) return ;
        JSONObject entries = new JSONObject();
        entries.set("userCard", userCard);
        entries.set("visitStartTime", visitStartTime);
        entries.set("visitEndTime", visitEndTime);
        expirationDateRefreshedUserCard(Arrays.asList(entries));
    }

    /**
     * 批量跟据身份证号码进行用户门禁有效期刷新
     *
     */
    public void expirationDateRefreshedUserCard(List<JSONObject> userList) throws Exception {
        if (!dockFlag.equals(1)) return ;
        DaHuaDeviceCommon daHuaDeviceCommon = getDaHuaDeviceCommon();
        List<String> userCard = userList.stream().map(item -> item.getStr("userCard")).collect(Collectors.toList());
        Map<String, JSONObject> userCardMap = userList.stream().collect(Collectors.toMap(item -> item.getStr("userCard"), item -> item, (existing, replacement) -> replacement));
        JSONArray userListByUserCardList = daHuaDeviceCommon.getUserListByUserCard(userCard).getJSONObject("data").getJSONArray("pageData");
        List<JSONObject> userDataList = new ArrayList<>();
        for (int i = 0; i < userListByUserCardList.size(); i++) {
            JSONObject item = userListByUserCardList.getJSONObject(i);
            JSONObject entries = new JSONObject();
            entries.set("id", item.get("id", Long.class));
            JSONObject userCardJsonObj = userCardMap.get(item.getStr("paperNumber"));
            entries.set("visitStartTime", userCardJsonObj.getStr("visitStartTime"));
            entries.set("visitEndTime", userCardJsonObj.getStr("visitEndTime"));
            userDataList.add(entries);
        }
        if (!userDataList.isEmpty()) {
            expirationDateBatchRefreshedUserCardList(userDataList);
        }
    }

    /**
     * 跟据身份证号码进行用户门禁有效期刷新
     */
    private void expirationDateBatchRefreshedUserCardList(List<JSONObject> dataList) throws Exception {
        if (!dockFlag.equals(1)) return ;
        DaHuaDeviceCommon daHuaDeviceCommon = getDaHuaDeviceCommon();
        daHuaDeviceCommon.updatePersonValidity(dataList);
    }

    /**
     * 跟据身份证号码进行用户门禁开启与关闭
     * 1：解冻 2：冻结
     * (1:有 2：无)
     */
    public void freezeByUserCard(String userCard, Integer mkmjPermission) throws Exception {
        if (!dockFlag.equals(1)) return ;
        DaHuaDeviceCommon daHuaDeviceCommon = getDaHuaDeviceCommon();
        JSONObject userByUserCard = daHuaDeviceCommon.getUserByUserCard(userCard).getJSONObject("data");
        daHuaDeviceCommon.updatePersonStatus(userByUserCard.getLong("id"), mkmjPermission);
    }

    /**
     * 跟据身份证号码查询用户信息
     */
    public JSONArray getMkmjUserInfoByUserCard(List<String> userCards) throws Exception {
        if (!dockFlag.equals(1)) return new JSONArray();
        DaHuaDeviceCommon daHuaDeviceCommon = getDaHuaDeviceCommon();
        return daHuaDeviceCommon.getUserListByUserCard(userCards).getJSONObject("data").getJSONArray("pageData");
    }

    protected DaHuaDeviceCommon getDaHuaDeviceCommon() {
        return new DaHuaDeviceCommon(new DhuaConfig(dockFlag, prefix, username, password, clientId, clientSecret));
    }

    public static void main(String[] args) throws Exception {
        OnePersonUtil onePersonUtil = new OnePersonUtil();
        System.out.println(onePersonUtil.getDaHuaDeviceCommon().getToken());
        String requestStr = "{\n" +
                "\n" +
                "    \"param\": {\n" +
                "\n" +
                "        \"monitors\": [\n" +
                "\n" +
                "            {\n" +
                "\n" +
                "                \"monitor\": \"http://192.168.192.201:8971/qa-prevention-gwj-tongbu/mkmjPerson/swipeCardRecordReceiving\",\n" +
                "\n" +
                "                \"monitorType\": \"url\",\n" +
                "\n" +
                "                \"events\": [\n" +
                "\n" +
                "                    {\n" +
                "\n" +
                "                        \"category\": \"alarm\",\n" +
                "\n" +
                "                        \"subscribeAll\": 1,\n" +
                "\n" +
                "                        \"domainSubscribe\": 2,\n" +
                "\n" +
                "                        \"authorities\": [\n" +
                "\n" +
                "                            {\n" +
                "\n" +
                "                                \"types\": [\n" +
                "\n" +
                "                                    \"51\",\n" +
                "\n" +
                "                                     \"61\"\n" +
                "\n" +
                "                                ]\n" +
                "\n" +
                "                            }\n" +
                "\n" +
                "                        ]\n" +
                "\n" +
                "                    }\n" +
                "\n" +
                "                ]\n" +
                "\n" +
                "            }\n" +
                "\n" +
                "        ],\n" +
                "\n" +
                "        \"subsystem\": {\n" +
                "\n" +
                "            \"subsystemType\": 0,\n" +
                "\n" +
                "            \"name\":\"192.168.192.201_8971\",\n" +
                "\n" +
                "            \"magic\":\"192.168.192.201_8971\"\n" +
                "\n" +
                "        }\n" +
                "\n" +
                "    }\n" +
                "\n" +
                "}";
        JSONObject x = new JSONObject(requestStr);
//        JSONArray userListByUserCard = onePersonUtil.getDaHuaDeviceCommon().getUserListByUserCard(Arrays.asList("61010519900320002X", "130324199407282116")).getJSONObject("data").getJSONArray("pageData");
//
//        System.out.println();
//        String base64 = imageToBase64("C:\\Users\\Administrator\\Desktop\\myface.jpg");
//        String dataUrl = "data:image/jpeg;base64," + base64;
//        System.out.println(dataUrl);
    }
    public static String imageToBase64(String imagePath) throws IOException {
        File file = new File(imagePath);
        byte[] imageBytes = new byte[(int) file.length()];

        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(imageBytes);
        }

        return java.util.Base64.getEncoder().encodeToString(imageBytes);
    }
    public void execute() {
     if (!dockFlag.equals(1)) return;
       List<XgfApplyPersonDO> dataList =  xgfApplyPersonRepository.listTodayHasPort();
       if (!dataList.isEmpty()) {
           HashMap<String,JSONObject> userCardHashSet = new HashMap<>();
           ArrayList<JSONObject> jsonObjects = new ArrayList<>();
           dataList.forEach(item -> {
               JSONObject entries = new JSONObject();
               entries.set("userCard", Base64.decodeToString(item.getUserCard()));
               entries.set("validStartTime", DateUtil.date2Str(new Date(),"yyyy-MM-dd") + " 00:00:00");
               entries.set("validEndTime", DateUtil.date2Str(new Date(),"yyyy-MM-dd") + " 23:59:59");
               userCardHashSet.put(Base64.decodeToString(item.getUserCard()), entries);
               jsonObjects.add(entries);
           });
           JSONArray mkmjUserInfoByUserCard = null;
           try {
               mkmjUserInfoByUserCard = getMkmjUserInfoByUserCard(new ArrayList<>(userCardHashSet.keySet()));
               for (int i = 0; i < mkmjUserInfoByUserCard.size(); i++) {
                   JSONObject jsonObject = mkmjUserInfoByUserCard.getJSONObject(i);
                   userCardHashSet.get(jsonObject.getStr("paperNumber")).set("id", jsonObject.getLong("id"));
               }
               expirationDateBatchRefreshedUserCardList(new ArrayList<>(userCardHashSet.values()));
           } catch (Exception e) {
               throw new RuntimeException(e);
           }

       }

    }
}
