package cn.pluss.platform.ys.settle;

import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.settle.ChannelMakeMoneyService;
import cn.pluss.platform.util.FileUtil;
import cn.pluss.platform.util.MapUtils;
import cn.pluss.platform.util.RSAUtils;
import cn.pluss.platform.util.SignUtils;
import cn.pluss.platform.ys.YsConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 银盛通道，对账功能服务类
 * @author djh
 */
@Slf4j
@Service("ysMakeMoneyService")
public class YsMakeMoneyServiceImpl implements ChannelMakeMoneyService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private YsConfig ysConfig;

    /**
     * 对账接口名称
     */
    public static final String MAKE_MONEY_METHOD = "ysepay.online.bill.downloadurl.get";

    /**
     * @param params    参数，非统一参数，用map接收
     *
     * @return
     */
    @Override
    public File getFile(Map<String, Object> params) {
        val sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        val bizContent = new JSONObject();
        bizContent.put("account_date", params.get("account_date"));
        val reqData = new JSONObject();
        reqData.put("biz_content", bizContent.toJSONString());
        reqData.put("method", MAKE_MONEY_METHOD);
        reqData.put("partner_id", ysConfig.getSrcMerchantNo());
        reqData.put("timestamp", sdf.format(new Date()));
        reqData.put("charset", "utf-8");
        reqData.put("sign_type", "RSA");
        reqData.put("version", "3.0");

        val signContent = SignUtils.getYSSignContent(reqData);
        try {
            val sign = RSAUtils.sign(ysConfig.getPriKey(), signContent);
            reqData.put("sign", sign);
        } catch (Exception e) {
            log.info("======【银盛对账方法】签名异常");
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

        val multiValueMap = MapUtils.map2MultiValueMap(reqData);

        HttpEntity<MultiValueMap<String, Object>> reqEntity = new HttpEntity<>(multiValueMap, headers);
        JSONObject responseJson = restTemplate.postForObject(ysConfig.getSettleDomain(), reqEntity, JSONObject.class);

        if (responseJson == null) {
            throw new MsgException("银盛对账接口异常");
        }

        log.info("返回报文：{}", responseJson.toJSONString());

        val bizResult = responseJson.getJSONObject("ysepay_online_bill_downloadurl_get_response");

        val downloadUrl = bizResult.getString("bill_download_url");

        log.info("文件下载链接: {}", downloadUrl);

        val fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));

        ResponseEntity<byte[]> response = restTemplate.exchange(downloadUrl, HttpMethod.GET, null, byte[].class);

        InputStream inputStream = new ByteArrayInputStream(response.getBody());

        File file = new File("C:\\Users\\nb2020\\syb\\resources\\ysExcel");
        if (!file.exists()) {
            file.mkdirs();
        }

        File excelFile = new File(file, fileName + ".zip");


        OutputStream os = null;
        try {
            if (!excelFile.createNewFile()) {
                throw new MsgException("=======【银盛对账】创建文件失败");
            }

            log.info("文件路径：{}", excelFile.getAbsolutePath());
            val bytes = FileUtil.readInputStream(inputStream);
            os = new FileOutputStream(excelFile);
            os.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.info("=======读取文件流异常");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("=======写入文件异常");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.info("=======文件流关闭异常");
                }
            }
        }

        return excelFile;
    }

    @Override
    public List<Map<String, Object>> readData(File file) {
        return null;
    }

    @Override
    public void insertData(List<Map<String, Object>> readData) {

    }
}
