package com.bohuikeji.delivery.backstage.controller.test;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.constants.payConst;
import com.bohuikeji.delivery.backstage.controller.api.courier.CourierApi;
import com.bohuikeji.delivery.backstage.controller.api.customer.CustomerV2Api;
import com.bohuikeji.delivery.backstage.controller.callback.ThirdCallBack;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.listener.order.OrderAssignListener;
import com.bohuikeji.delivery.backstage.listener.order.OrderCheckPriceListener;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.JdServer;
import com.bohuikeji.delivery.backstage.service.third.ShansongServer;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.delivery.backstage.service.third.UUServer;
import com.bohuikeji.delivery.backstage.util.QrCodeUtil;
import com.bohuikeji.delivery.backstage.util.WxUtils;
import com.bohuikeji.delivery.backstage.util.capacity.HllUtils;
import com.bohuikeji.delivery.backstage.util.capacity.KDHundredUtils;
import com.bohuikeji.delivery.backstage.util.maiyatian.maltUtils;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.component.StaticComponent;
import com.bohuikeji.frame.module.admin.config.MqConf;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.sys.SysError;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import java.util.regex.Pattern;

/**
 * 通知推送测试
 * @author 10552
 */
@Slf4j
@RestController
@Api(tags = {"数据下载"})
@RequestMapping("/third")
@RequiredArgsConstructor
public class DateTest extends ApiController{

    @Autowired
    ITCourierService courierService;
    final ThirdUtils thirdUtils;
    @Autowired
    ITCourierCardService courierCardService;
    final RabbitTemplate rabbitTemplate;
    final ITConfigService configService;
    final ITOrderService orderService;
    final CustomerV2Api customerV2Api;
    /*final IShanSongService shanSongService;*/
    final ISysConfigService sysConfigService;
    final ThirdCallBack songCallBack;
    final ITCustomerService itCustomerService;
    final UUServer uuServer;
    final ShansongServer shansongServer;
    final RedisUtil redisUtil;
    final MqConf mqConf;
    final OrderCheckPriceListener orderCheckPriceListener;
    final JdServer jdServer;
    final ISocketService socketService;
    final ITOrderArrearsService arrearsService;
    final CourierApi courierApi;
    final ITCustomerService customerService;
    final IWxUserService wxUserService;
    final ITOrderService itOrderService;
    final ITPayService payService;
    final ITFranchiseeInformationService franchiseeInformationService;
    final ITCustomerAddressService itCustomerAddressService;
    final ISysDataUrlService sysDataUrlService;
    @Autowired
    MqTool mqTool;


    /**
     * 上传文件
     * D:\文件数据\mino01\本地
     * E:\文件数据\mino01\硬盘
     * 10.173.34.204
     * 10.173.34.205
     * 10.173.34.206
     * 10.173.34.207
     * @return
     */
    @ApiOperation("数据库的资源文件下载与上传")
    @PostMapping("/upload/dow")
    public APIEntity uploadFiles(Integer curIds) throws IOException {
        List<TCourier> couriers = courierService.list(new QueryWrapper<TCourier>().isNotNull("courier_card_url"));
        for(TCourier tCourier : couriers){
            String[] urls = tCourier.getCourierCardUrl().split(";");
            for (String surl : urls) {
                // 在此处处理每个元素
                String saveDir = "E:\\文件数据\\minio02\\";
                String remoteUrl = surl.replace("https://oss.bhynm.com","http://10.173.34.205:20000");
                System.out.println("当前执行的骑手id：" + tCourier.getCourierId()+",时间："+LocalDateTime.now());
                System.out.println("文件下载服务器路径：" + remoteUrl);
                try {
                    URL url = new URL(remoteUrl);
                    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                    httpConn.setRequestMethod("GET");
                    int responseCode = httpConn.getResponseCode();
                    System.out.println("responseCode：" + responseCode);
                    // 检查连接是否正常
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        // 打开输入流
                        InputStream inputStream = httpConn.getInputStream();
                        // 获取文件名
                        String fileName  = surl.substring(surl.lastIndexOf("/") + 1, surl.length());
                        // 构造本地文件路径
                        System.out.println("文件下载保存路径2222：" + fileName);
                        String filePath = saveDir + fileName;
                        // 打开输出流
                        FileOutputStream outputStream = new FileOutputStream(filePath);
                        // 读取输入流并写入输出流
                        byte[] buffer = new byte[4096];
                        int bytesRead = -1;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        // 关闭输入流和输出流
                        outputStream.close();
                        inputStream.close();
                        System.out.println("文件下载完成：" + filePath);
                    } else {
                        System.out.println("文件下载失败，错误码：" + responseCode);
                    }
                } catch (IOException e) {
                    SysError.saveError("文件下载失败，骑手id：{0}，{1}",tCourier.getCourierId(),tCourier.getCourierName());
                    System.out.println("错误：" + e.getMessage());
                }
            }
        }
        return APIEntity.success();
    }


    /**
     * 上传文件
     * D:\文件数据\mino01\本地
     * E:\文件数据\mino01\硬盘
     * 10.173.34.204
     * 10.173.34.205
     * 10.173.34.206
     * 10.173.34.207
     * @return
     */
    @ApiOperation("零散文件资源的下载与上传")
    @PostMapping("/upload/scattered/dow")
    public APIEntity scatteredUploadFiles() throws IOException {
        List<SysDataUrl> dataUrls = sysDataUrlService.list(new QueryWrapper<SysDataUrl>().isNotNull("data_url"));
        for(SysDataUrl sysDataUrl : dataUrls){
            String[] urls = sysDataUrl.getDataUrl().split(";");
            for (String surl : urls) {
                // 在此处处理每个元素
                String saveDir = "D:\\文件数据\\minio02\\";
                String remoteUrl = surl.replace("https://oss.bhynm.com","http://10.173.34.204:20000");
                System.out.println("当前执行的骑手id：" + sysDataUrl.getDataId()+",时间："+LocalDateTime.now());
                System.out.println("文件下载服务器路径：" + remoteUrl);
                try {
                    URL url = new URL(remoteUrl);
                    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                    httpConn.setRequestMethod("GET");
                    int responseCode = httpConn.getResponseCode();
                    System.out.println("responseCode：" + responseCode);
                    // 检查连接是否正常
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        // 打开输入流
                        InputStream inputStream = httpConn.getInputStream();
                        // 获取文件名
                        String fileName  = surl.substring(surl.lastIndexOf("/") + 1, surl.length());
                        // 构造本地文件路径
                        System.out.println("文件下载保存路径2222：" + fileName);
                        String filePath = saveDir + fileName;
                        // 打开输出流
                        FileOutputStream outputStream = new FileOutputStream(filePath);
                        // 读取输入流并写入输出流
                        byte[] buffer = new byte[4096];
                        int bytesRead = -1;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        // 关闭输入流和输出流
                        outputStream.close();
                        inputStream.close();
                        System.out.println("文件下载完成：" + filePath);
                    } else {
                        System.out.println("文件下载失败，错误码：" + responseCode);
                    }
                } catch (IOException e) {
                    SysError.saveError("文件下载失败，骑手id：{0}",sysDataUrl.getDataId());
                    System.out.println("错误：" + e.getMessage());
                }
            }
        }
        return APIEntity.success();
    }

    /**
     * 上传文件
     * 10.173.34.204
     * 10.173.34.205
     * 10.173.34.206
     * 10.173.34.207
     * @return
     */
    @ApiOperation("匹配新的文件路径")
    @PostMapping("/update/date")
    public APIEntity uploadFiles(String httpUrl) throws IOException {
        List<TCourier> couriers = courierService.list(new QueryWrapper<TCourier>().isNotNull("courier_card_url"));
        for(TCourier tCourier : couriers){
            String[] urls = tCourier.getCourierCardUrl().split(";");
            StringJoiner joiner=new StringJoiner(";");
            for (String surl : urls) {
                // 在此处处理每个元素
                String fileName = surl.substring(surl.lastIndexOf("/") + 1, surl.length());
                joiner.add(httpUrl+fileName);
            }
            courierService.updateById(tCourier.setCourierCardUrl(joiner.toString()));
            System.out.println("骑手ID:"+tCourier.getCourierId()+"新的文件路径：" + joiner);
        }
        return APIEntity.success(couriers);
    }

    /**
     * 上传文件
     * 10.173.34.204
     * 10.173.34.205
     * 10.173.34.206
     * 10.173.34.207
     * @return
     */
    @ApiOperation("独立文件下载上传")
    @PostMapping("/upload/file/url")
    public APIEntity filesUrl(String surl) throws IOException {
        // 在此处处理每个元素
        String pst = surl.substring(37,surl.lastIndexOf("/")+1);
        System.out.println("文件下载保存路径111：" + pst);
        String saveDir = "D:\\文件数据\\mino01\\delivery\\upload"+pst.replace("/","\\");
        File file2 = new File(saveDir);
        boolean newjavaTest = file2.mkdirs();
        System.out.println("文件下载创建文件夹：" + newjavaTest);
        String remoteUrl = surl.replace("https://oss.bhynm.com","http://10.173.34.204:20000");
        System.out.println("文件下载服务器路径：" + remoteUrl);
        try {
            URL url = new URL(remoteUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            int responseCode = httpConn.getResponseCode();
            // 检查连接是否正常
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 打开输入流
                InputStream inputStream = httpConn.getInputStream();
                // 获取文件名
                String fileName = "";
                String disposition = httpConn.getHeaderField("Content-Disposition");
                if (disposition != null) {
                    int index = disposition.indexOf("filename=");
                    if (index > 0) {
                        fileName = disposition.substring(index + 10, disposition.length() - 1);
                    }
                } else {
                    // 如果Content-Disposition头字段不存在，则从URL获取文件名
                    fileName = surl.substring(surl.lastIndexOf("/") + 1, surl.length());
                }
                // 构造本地文件路径
                System.out.println("文件下载保存路径2222：" + fileName);
                String filePath = saveDir + fileName;
                // 打开输出流
                FileOutputStream outputStream = new FileOutputStream(filePath);
                // 读取输入流并写入输出流
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                // 关闭输入流和输出流
                outputStream.close();
                inputStream.close();
                System.out.println("文件下载完成：" + filePath);
                //MinioUtil.uploadFiles(filePath);
            } else {
                System.out.println("文件下载失败，错误码：" + responseCode);
            }
        } catch (IOException e) {
            System.out.println("错误：" + e.getMessage());
        }
        return APIEntity.success();
    }


    /**
     * 上传文件
     * 10.173.34.204
     * 10.173.34.205
     * 10.173.34.206
     * 10.173.34.207
     * @return
     */
    @ApiOperation("独立文件下载上传")
    @PostMapping("/upload/io")
    public APIEntity filesUrlUpload(String surl) throws IOException {
        // 在此处处理每个元素
        String pst = surl.substring(37,surl.lastIndexOf("/")+1);
        System.out.println("文件下载保存路径111：" + pst);
        String saveDir = "D:\\文件数据\\mino01\\delivery\\upload"+pst.replace("/","\\");
        File file2 = new File(saveDir);
        boolean newjavaTest = file2.mkdirs();
        System.out.println("文件下载创建文件夹：" + newjavaTest);
        String remoteUrl = surl.replace("https://oss.bhynm.com","http://10.173.34.204:20000");
        System.out.println("文件下载服务器路径：" + remoteUrl);
        try {
            URL url = new URL(remoteUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            int responseCode = httpConn.getResponseCode();
            // 检查连接是否正常
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 打开输入流
                InputStream inputStream = httpConn.getInputStream();
                // 获取文件名
                String fileName = surl.substring(surl.lastIndexOf("/") + 1, surl.length());
                // 构造本地文件路径
                System.out.println("文件下载保存路径2222：" + fileName);
                String filePath = saveDir + fileName;
                // 打开输出流
                FileOutputStream outputStream = new FileOutputStream(filePath);
                // 读取输入流并写入输出流
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                // 关闭输入流和输出流
                outputStream.close();
                inputStream.close();
                System.out.println("文件下载完成：" + filePath);
                //MinioUtil.uploadFileC(inputStream,".jpg",fileName);
            } else {
                System.out.println("文件下载失败，错误码：" + responseCode);
            }
        } catch (IOException e) {
            System.out.println("错误：" + e.getMessage());
        }
        return APIEntity.success();
    }

    /**
     * 内部方法
     * 上传文件
     * @param muFile
     * @return
     */
   /* private static String uploadMultipartFile(MultipartFile muFile){
        File file = new File("test.png");
        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                MediaType.ALL_VALUE, true, file.getName());

        try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        MultipartFile multi = new CommonsMultipartFile(fileItem);
        return OSS_URL_READ+BUCKET_NAME+fileName;
    }*/
}
