package com.bohuikeji.delivery.backstage.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.FileItem;
import com.alipay.api.domain.AlipayOpenAppMiniTemplatemessageSendModel;
import com.alipay.api.request.AlipayMerchantItemFileUploadRequest;
import com.alipay.api.request.AlipayMerchantOrderSyncRequest;
import com.alipay.api.request.AlipayOpenAppMiniTemplatemessageSendRequest;
import com.alipay.api.response.AlipayMerchantItemFileUploadResponse;
import com.alipay.api.response.AlipayMerchantOrderSyncResponse;
import com.alipay.api.response.AlipayOpenAppMiniTemplatemessageSendResponse;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.pay.AliPayV2;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;


@Slf4j
public class AliUtils {

    /**
     * 商品文件上传接口
     * D:/workSpace/tcjs-bankend/upload/log.jpg
     * @return
     */
    public static JSONObject uploadFile () {
        AlipayMerchantItemFileUploadRequest request = new AlipayMerchantItemFileUploadRequest();
        request.setScene("SYNC_ORDER");
        FileItem FileContent = new FileItem("D:/private/cert/tcjs/alipay/log.jpg");
        log.info("文件字节流FileContent：{}",FileContent);
        request.setFileContent(FileContent);
        JSONObject orderStr = null;
        AlipayMerchantItemFileUploadResponse response = null;
        try {
            response = AliPay.aliClient.alipayBycodeClient.certificateExecute(request);
            log.info("文件上传接口响应示例1：{}",response);
            orderStr = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_merchant_item_file_upload_response");
            log.info("文件上传接口响应示例2：{}",orderStr);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return orderStr;
    }

    /**
     * 订单数据同步接口
     * @return
     */
    public static JSONObject orderCcenter (Map<String,Object> params,String channelType) {
        //String bizContent = "{\"amount\":${price},\"order_modified_time\":\"${modTime}\",\"order_create_time\":\"${createTime}\",\"item_order_list\":[{\"quantity\":1,\"item_name\":\"${itemName}\",\"unit_price\":\"${unitPrice}\",\"ext_info\":[{\"ext_key\":\"image_material_id\",\"ext_value\":\"${materialId}\"}]}],\"ext_info\":[{\"ext_key\":\"business_info\",\"ext_value\":\"{\\\"distribution_end_time\\\":\\\"\\\",\\\"rider_position\\\":\\\"\\\",\\\"delivery_start_time\\\":\\\"\\\",\\\"take_out_mode\\\":\\\"no_rider_mode\\\",\\\"delivery_end_time\\\":\\\"\\\",\\\"take_out_order_type\\\":\\\"${orderType}\\\",\\\"distributor_information\\\":\\\"同城急送\\\",\\\"distribution_start_time\\\":\\\"\\\",\\\"delivery_clerk\\\":\\\"\\\"}\"},{\"ext_key\":\"merchant_biz_type\",\"ext_value\":\"${bizType}\"},{\"ext_key\":\"merchant_order_status\",\"ext_value\":\"${orderStatus}\"},{\"ext_key\":\"merchant_order_link_page\",\"ext_value\":\"/pages/index/index\"},{\"ext_key\":\"tiny_app_id\",\"ext_value\":\"${appId}\"}],\"out_biz_no\":\"${bizNo}\",\"buyer_id\":\"${uid}\",\"order_type\":\"SERVICE_ORDER\"}";
        String bizContent = "{\"amount\":${price},\"order_modified_time\":\"${modTime}\",\"order_create_time\":\"${createTime}\",\"item_order_list\":[{\"quantity\":1,\"item_name\":\"${itemName}\",\"unit_price\":\"${unitPrice}\",\"ext_info\":[{\"ext_key\":\"image_material_id\",\"ext_value\":\"${materialId}\"}]}],\"ext_info\":[{\"ext_key\":\"business_info\",\"ext_value\":\"{\\\"distribution_end_time\\\":\\\"\\\",\\\"rider_position\\\":\\\"\\\",\\\"delivery_start_time\\\":\\\"\\\",\\\"take_out_mode\\\":\\\"no_rider_mode\\\",\\\"delivery_end_time\\\":\\\"\\\",\\\"take_out_order_type\\\":\\\"${orderType}\\\",\\\"distributor_information\\\":\\\"同城急送\\\",\\\"distribution_start_time\\\":\\\"\\\",\\\"delivery_clerk\\\":\\\"\\\"}\"},{\"ext_key\":\"merchant_biz_type\",\"ext_value\":\"${bizType}\"},{\"ext_key\":\"merchant_order_status\",\"ext_value\":\"${orderStatus}\"},{\"ext_key\":\"merchant_order_link_page\",\"ext_value\":\"/pages/index/index\"},{\"ext_key\":\"tiny_app_id\",\"ext_value\":\"${appId}\"}],\"out_biz_no\":\"${bizNo}\",\"buyer_id\":\"${uid}\",\"order_type\":\"SERVICE_ORDER\"}";
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            bizContent = bizContent.replace("${" + k + "}", v.toString());
        }
        AlipayMerchantOrderSyncRequest request = new AlipayMerchantOrderSyncRequest();
        request.setBizContent(bizContent);
        JSONObject orderStr = null;
        AlipayMerchantOrderSyncResponse response = null;
        try {
            if("同城急送".equals(channelType)){
                response = AliPayV2.aliClientTcjsicial.alipayBycodeClient.certificateExecute(request);
            }
            if("客户端小程序（支付宝）".equals(channelType)){
                response = AliPay.aliClient.alipayBycodeClient.certificateExecute(request);
            }
            orderStr = JSONObject.parseObject(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("订单数据同步返回参数：[{}]",orderStr);
        return orderStr;
    }


    /**
     * 订阅消息模板
     * 订单下单模板
     * @param params
     * @return
     */
    public static JSONObject orderPlace(Map<String,Object> params) {
        String date = "{\"keyword1\":{\"value\":\"${price}\"},\"keyword2\":{\"value\":\"${address}\"},\"keyword3\":{\"value\":\"${placeTime}\"},\"keyword4\":{\"value\":\"${orderNum}\"},\"keyword5\":{\"value\":\"${corName}\"}}";
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            date = date.replace("${" + k + "}", v.toString());
        }
        AlipayOpenAppMiniTemplatemessageSendRequest request = new AlipayOpenAppMiniTemplatemessageSendRequest();
        AlipayOpenAppMiniTemplatemessageSendModel model = new AlipayOpenAppMiniTemplatemessageSendModel();
        model.setFormId(params.get("fromId").toString());
        model.setData(date);
        model.setPage("pages/index/index");
        model.setUserTemplateId("216ed8e65ded4540bdc4e50a80f26f2d");
        model.setToUserId(params.get("uid").toString());
        request.setBizModel(model);
        JSONObject orderStr = null;
        AlipayOpenAppMiniTemplatemessageSendResponse response = null;
        try {
            response = AliPay.aliClient.alipayBycodeClient.certificateExecute(request);
            orderStr = JSONObject.parseObject(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("订单下单订阅消息：[{}]",orderStr);
        return orderStr;
    }

    /**
     * 订阅消息模板
     * 订单取消模板
     * @param params
     * @return
     */
    public static JSONObject orderCancel(Map<String,Object> params) {
        String date = "{\"keyword1\":{\"value\":\"${mailingName}\"},\"keyword2\":{\"value\":\"${receiptName}\"},\"keyword3\":{\"value\":\"${price}\"},\"keyword4\":{\"value\":\"${orderNum}\"},\"keyword5\":{\"value\":\"${cancelTime}\"}}";
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            date = date.replace("${" + k + "}", v.toString());
        }
        AlipayOpenAppMiniTemplatemessageSendRequest request = new AlipayOpenAppMiniTemplatemessageSendRequest();
        AlipayOpenAppMiniTemplatemessageSendModel model = new AlipayOpenAppMiniTemplatemessageSendModel();
        model.setFormId(params.get("fromId").toString());
        model.setData(date);
        model.setPage("pages/index/index");
        model.setUserTemplateId("2b29d6f5a04d4c5e9b26b21699803a98");
        model.setToUserId(params.get("uid").toString());
        request.setBizModel(model);
        JSONObject orderStr = null;
        AlipayOpenAppMiniTemplatemessageSendResponse response = null;
        try {
            response = AliPay.aliClient.alipayBycodeClient.certificateExecute(request);
            orderStr = JSONObject.parseObject(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("订单取消订阅消息：[{}]",orderStr);
        return orderStr;
    }

    /**
     * 订阅消息模板
     * 订单取消模板
     * @param params
     * @return
     */
    /*public static JSONObject orderStatus(Map<String,Object> params) {
        String date = "{\"keyword1\":{\"value\":\"${mailingName}\"},\"keyword2\":{\"value\":\"${receiptName}\"},\"keyword3\":{\"value\":\"${price}\"},\"keyword4\":{\"value\":\"${orderNum}\"},\"keyword5\":{\"value\":\"${cancelTime}\"}}";
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String k = entry.getKey();
            Object v = entry.getValue();
            date = date.replace("${" + k + "}", v.toString());
        }
        AlipayOpenAppMiniTemplatemessageSendRequest request = new AlipayOpenAppMiniTemplatemessageSendRequest();
        AlipayOpenAppMiniTemplatemessageSendModel model = new AlipayOpenAppMiniTemplatemessageSendModel();
        model.setFormId(params.get("fromId").toString());
        model.setData(date);
        model.setPage("pages/index/index");
        model.setUserTemplateId("2b29d6f5a04d4c5e9b26b21699803a98");
        model.setToUserId(params.get("uid").toString());
        request.setBizModel(model);
        JSONObject orderStr = null;
        AlipayOpenAppMiniTemplatemessageSendResponse response = null;
        try {
            response = AliPayV2.aliClientTcjsicial.alipayBycodeClient.certificateExecute(request);
            orderStr = JSONObject.parseObject(response.getBody());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("订单取消订阅消息：[{}]",orderStr);
        return orderStr;
    }*/

    /**
     * 业务、优惠支付生成预支付订单参数处理
     * @return
     */
    public static String getOrderStatus(String status) {
        String orderState;
        switch (status){
            case "待接单":
                orderState="PENDING";break;
            case "待取件":
                orderState="ORDER_TAKEN";break;
            case "待派送":
                orderState="TO_BE_DELIVERED";break;
            case "派送中":
                orderState="IN_DELIVERY";break;
            case "已完成":
                orderState="DELIVERED";break;
            case "已取消":
            case "已退款":
                orderState="CLOSED";break;
            default:
                return null;
        }
        return orderState;
    }
    public static String getBizContent(String orderState){
        String bizContent;
        if("PAID".equals(orderState) || "TAKEN_THE_ORDER".equals(orderState)){
            bizContent = "{\n" +
                    " \"amount\":${price},\n" +
                    " \"order_modified_time\":\"${modTime}\",\n" +
                    " \"discount_amount\":\"0.00\",\n" +
                    " \"pay_amount\":${payAmount},\n" +
                    " \"ext_info\":[\n" +
                    " {\n" +
                    " \"ext_key\":\"business_info\",\n" +
                    " \"ext_value\":\"{\\\"pick_up_code\\\":\\\"\\\",\\\"send_code\\\":\\\"\\\",\\\"is_send_code\\\":\\\"false\\\",\\\"is_code\\\":\\\"false\\\",\\\"brand_name\\\":\\\"同城急送\\\",\\\"delivery_time\\\":\\\"\\\",\\\"pick_up_time\\\":\\\"\\\",\\\"rider_phone\\\":\\\"\\\"}\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"merchant_biz_type\",\n" +
                    " \"ext_value\":\"CITY_EXPRESS\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"merchant_order_status\",\n" +
                    " \"ext_value\":\"${orderStatus}\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"merchant_order_link_page\",\n" +
                    " \"ext_value\":\"/pages/index/index\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"tiny_app_id\",\n" +
                    " \"ext_value\":\"${appId}\"\n" +
                    " }\n" +
                    " ],\n" +
                    " \"out_biz_no\":\"${bizNo}\",\n" +
                    " \"buyer_id\":\"${uid}\",\n" +
                    " \"order_create_time\":\"${createTime}\",\n" +
                    " \"item_order_list\":[\n" +
                    " {\n" +
                    " \"item_name\":\"${itemName}\",\n" +
                    " \"ext_info\":[\n" +
                    " {\n" +
                    " \"ext_key\":\"image_material_id\",\n" +
                    " \"ext_value\":\"${materialId}\"\n" +
                    " }\n" +
                    " ]\n" +
                    " }\n" +
                    " ],\n" +
                    " \"source_app\":\"Alipay\",\n" +
                    " \"service_code\":\"\",\n" +
                    " \"trade_no\":\"${tradeNo}\",\n" +
                    " \"order_type\":\"SERVICE_ORDER\"\n" +
                    "}";

        }else {
            bizContent = "{\n" +
                    " \"order_modified_time\":\"${modTime}\",\n" +
                    " \"order_create_time\":\"${createTime}\",\n" +
                    " \"item_order_list\":[\n" +
                    " {\n" +
                    " \"item_name\":\"${itemName}\",\n" +
                    " \"ext_info\":[\n" +
                    " {\n" +
                    " \"ext_key\":\"image_material_id\",\n" +
                    " \"ext_value\":\"${materialId}\"\n" +
                    " }\n" +
                    " ]\n" +
                    " }\n" +
                    " ],\n" +
                    " \"source_app\":\"Alipay\",\n" +
                    " \"ext_info\":[\n" +
                    " {\n" +
                    " \"ext_key\":\"business_info\",\n" +
                    " \"ext_value\":\"{\\\"pick_up_code\\\":\\\"1024\\\",\\\"send_code\\\":\\\"\\\",\\\"is_send_code\\\":\\\"true\\\",\\\"is_code\\\":\\\"false\\\",\\\"brand_name\\\":\\\"同城急送\\\",\\\"delivery_time\\\":\\\"${deliveryTime}\\\",\\\"pick_up_time\\\":\\\"${pickUpTime}\\\",\\\"rider_phone\\\":\\\"${riderphone}\\\"}\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"merchant_biz_type\",\n" +
                    " \"ext_value\":\"CITY_EXPRESS\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"merchant_order_status\",\n" +
                    " \"ext_value\":\"${orderStatus}\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"merchant_order_link_page\",\n" +
                    " \"ext_value\":\"/pages/index/index\"\n" +
                    " },\n" +
                    " {\n" +
                    " \"ext_key\":\"tiny_app_id\",\n" +
                    " \"ext_value\":\"${appId}\"\n" +
                    " }\n" +
                    " ],\n" +
                    " \"out_biz_no\":\"${bizNo}\",\n" +
                    " \"buyer_id\":\"${uid}\",\n" +
                    " \"order_type\":\"SERVICE_ORDER\"\n" +
                    "}";
        }
        return bizContent;
    }
}
