package com.nmgs.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nmgs.mapper.Mapper;
import com.nmgs.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class SolveUserAndVehcleServiceImpl {
    @Autowired
    public Mapper mapperI;
    public String userSql = "select wut.OPENID FROM WEIXN_USER_TABLE wut WHERE wut.CERTIFICATION in(1,2,3) AND wut.NUMBERPIC IS NOT NULL  ";
    public String userVehcleSql = "select uvt.USERID,uvt.ACARNO,uvt.LICENSEPIC,uvt.PERMITPIC,uvt.VEHICLEPIC FROM USER_VEHICLE_TABLE uvt WHERE uvt.CERTIFICATION in(1,2,3)  ";

    /**
     * 同步附件到服务器
     *
     * @param syncType ALL 同步全部，PART 同步未同步过的数据
     * @return
     */
    public void syncFile(String syncType) throws IOException, InterruptedException {
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        String fileAddress = PathUtil.uploadPath;
        if (os.startsWith("win")) {
            fileAddress = PropertiesUtil.getValue("fileAddressWin");
            fileAddress = fileAddress.replace("/", "\\");
        } else {
            //fileAddress = PropertiesUtil.getValue("fileAddressLinux");
        }
        if (!"ALL".equals(syncType)) {
            userSql += " AND (wut.NUMBERPICNAME IS NULL OR wut.NUMBERPICNAME='')";
            userVehcleSql += "AND (uvt.LICENSEPICNAME IS NULL OR uvt.LICENSEPICNAME='')";
        }

        List selectforlist = this.mapperI.selectforlist(userSql);
        List userVehcleList = this.mapperI.selectforlist(userVehcleSql);
        Map<String, String> map = new HashMap<String, String>();
        JSONArray jsonA = new JSONArray();
        if (selectforlist != null && selectforlist.size() > 0) {
            LogUtil.WriteLog_Info("人员附件开始同步====" + PubTools.getCurrentDate() + "==={执行数据量}====" + selectforlist.size(), "SolveUserAndVehcleServiceImpl");
            for (int k = 0; k < selectforlist.size(); k++) {
                Object o = selectforlist.get(k);
                if (!PubTools.isEmpty(o)) {
                    Map<String, Object> mapObjectUser = (Map<String, Object>) o;
                    String openId = mapObjectUser.get("OPENID").toString();
                    LogUtil.WriteLog_Info("人员ID========" + openId, "SolveUserAndVehcleServiceImpl");
                    String sqlTemp = "select NUMBERPIC FROM WEIXN_USER_TABLE WHERE OPENID='" + openId + "'";
                    Map<String, Object> mapObject = this.mapperI.select(sqlTemp);
                    String numPicName = "";
                    if (!PubTools.isEmpty(mapObject.get("NUMBERPIC"))) {
                        String numberpic = PubTools.ClobToString(mapObject.get("NUMBERPIC"));
                        String fileName = openId + "NUMPIC" + ".jpg";
                        numPicName = fileName;
                        byte[] imageBytes = Base64.getDecoder().decode(numberpic);
                        // 创建文件
                        File file = new File(fileAddress, fileName); // 指定上传位置
                        //先删除附件
                        if (file.exists()) {
                            file.delete();
                        }
                        // 保存文件
                        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, imageBytes);
                        JSONObject mapParam = new JSONObject();
                        mapParam.put("fileName", fileName);
                        mapParam.put("imageBase64", numberpic);
                        jsonA.add(mapParam);
                        if (!PubTools.isNull(numPicName)) {
                            String sql = "UPDATE WEIXN_USER_TABLE set NUMBERPICNAME='" + numPicName + "'  WHERE CERTIFICATION in(1,2,3) AND OPENID='" + openId + "'";
                            this.mapperI.update(sql);
                        }
                    }
                }

                if ((k + 1) % 10 == 0) {
                    Thread.sleep(10 * 1000);
                }
            }
            LogUtil.WriteLog_Info("人员附件同步结束====" + PubTools.getCurrentDate() + "=======", "SolveUserAndVehcleServiceImpl");
        }
        if (userVehcleList != null && userVehcleList.size() > 0) {
            LogUtil.WriteLog_Info("车辆附件同步开始====" + PubTools.getCurrentDate() + "==={执行数据量}====" + userVehcleList.size(), "SolveUserAndVehcleServiceImpl");
            for (int k = 0; k < userVehcleList.size(); k++) {
                Object o = userVehcleList.get(k);
                if (!PubTools.isEmpty(o)) {
                    Map<String, Object> mapObjectVeh = (Map<String, Object>) o;
                    String vehPicName = "";
                    String perPicName = "";
                    String licPicName = "";
                    String userId = mapObjectVeh.get("USERID").toString();
                    String aCarNo = mapObjectVeh.get("ACARNO").toString();
                    String fileNamePre = userId + "-" + aCarNo + "-";
                    String fileNameAfter = ".jpg";
                    LogUtil.WriteLog_Info("人员ID========" + userId + "=====车牌号====" + aCarNo, "SolveUserAndVehcleServiceImpl");
                    String tempSql = "select uvt.LICENSEPIC,uvt.PERMITPIC,uvt.VEHICLEPIC FROM USER_VEHICLE_TABLE uvt WHERE uvt.CERTIFICATION in(1,2,3) AND uvt.USERID=" + userId + " AND uvt.ACARNO='" + aCarNo + "'";
                    List selectforlist1 = this.mapperI.selectforlist(tempSql);
                    Map<String, Object> mapObject = new HashMap<String, Object>();
                    if (selectforlist1 != null && selectforlist1.size() > 0) {
                        mapObject = (Map<String, Object>) selectforlist1.get(0);
                    }
                    if (!PubTools.isEmpty(mapObject.get("LICENSEPIC"))) {
                        String numberpic = PubTools.ClobToString(mapObject.get("LICENSEPIC"));
                        String fileName = fileNamePre + "LICPIC" + fileNameAfter;
                        licPicName = fileName;
                        byte[] imageBytes = Base64.getDecoder().decode(numberpic);
                        // 创建文件
                        File file = new File(fileAddress, fileName); // 指定上传位置
                        //先删除附件
                        if (file.exists()) {
                            file.delete();
                        }
                        // 保存文件
                        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, imageBytes);
                        Map<String, String> mapParam = new HashMap<String, String>();
                        mapParam.put("fileName", fileName);
                        mapParam.put("imageBase64", numberpic);
                        jsonA.add(mapParam);

                    }
                    if (!PubTools.isEmpty(mapObject.get("PERMITPIC"))) {
                        String numberpic = PubTools.ClobToString(mapObject.get("PERMITPIC"));
                        String fileName = fileNamePre + "PERPIC" + fileNameAfter;
                        perPicName = fileName;
                        byte[] imageBytes = Base64.getDecoder().decode(numberpic);
                        // 创建文件
                        File file = new File(fileAddress, fileName); // 指定上传位置
                        //先删除附件
                        if (file.exists()) {
                            file.delete();
                        }
                        // 保存文件
                        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, imageBytes);
                        Map<String, String> mapParam = new HashMap<String, String>();
                        mapParam.put("fileName", fileName);
                        mapParam.put("imageBase64", numberpic);
                        jsonA.add(mapParam);

                    }
                    if (!PubTools.isEmpty(mapObject.get("VEHICLEPIC"))) {
                        String numberpic = PubTools.ClobToString(mapObject.get("VEHICLEPIC"));
                        String fileName = fileNamePre + "VEHPIC" + fileNameAfter;
                        vehPicName = fileName;
                        byte[] imageBytes = Base64.getDecoder().decode(numberpic);
                        // 创建文件
                        File file = new File(fileAddress, fileName); // 指定上传位置
                        //先删除附件
                        if (file.exists()) {
                            file.delete();
                        }
                        // 保存文件
                        org.apache.commons.io.FileUtils.writeByteArrayToFile(file, imageBytes);
                        JSONObject mapParam = new JSONObject();
                        mapParam.put("fileName", fileName);
                        mapParam.put("imageBase64", numberpic);
                        jsonA.add(mapParam);
                    }
                    if (!PubTools.isNull(vehPicName) && !PubTools.isNull(perPicName) && !PubTools.isNull(licPicName)) {
                        String sql = "UPDATE USER_VEHICLE_TABLE set LICENSEPICNAME='" + licPicName + "',PERMITPICNAME='" + perPicName + "',VEHICLEPICNAME='" + vehPicName + "'  WHERE CERTIFICATION in(1,2,3) AND USERID=" + userId + " AND ACARNO='" + aCarNo + "'";
                        this.mapperI.update(sql);
                    }
                }
                if ((k + 1) % 10 == 0) {
                    Thread.sleep(10 * 1000);
                }
            }
            LogUtil.WriteLog_Info("车辆附件同步结束====" + PubTools.getCurrentDate() + "=======", "SolveUserAndVehcleServiceImpl");
        }
        if (jsonA.size() > 0) {
            map.put("jsonArray", jsonA.toJSONString());
            //保存到附件服务器上面
            String fileUploadUrl = PropertiesUtil.getValue("fileUploadUrl");
            LogUtil.WriteLog_Info("ImageUtils====附件上传接口fileUploadUrl=====" + fileUploadUrl, "FileController");
            String s = HttpClientUtil.doPost(fileUploadUrl, map);
            LogUtil.WriteLog_Info("ImageUtils====附件上传结果显示=====" + s, "FileController");
        }
    }

}
