package com.yihu.jw.base.service.equipment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.util.http.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by wangzhinan on 2021/9/17.
 */
@Service
public class JuMiAiService {
    private Logger logger = LoggerFactory.getLogger(JuMiAiService.class);

    private static final String baseUrl = "https://open.jumiai.cn";
    private static final String ClientId = "AC3124C182B542839D37AF227C5ECAC9";
    private static final String ClientSecret= "6038602CD01B446AA5526450700940B367145BC1502946E5806AABA0968E0E3E";
    private static final String MerchantNo ="999260";//商户号

    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    StringRedisTemplate redisTemplate;


    /**
     * 获取token
     * @return
     */
    public synchronized String getToken(){
        try {
            String key = "AccessToken:jumi";
            if (redisTemplate.hasKey(key)){
                String jsonStr = redisTemplate.opsForValue().get(key);
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                long add_timestamp = jsonObject.getLong("add_timestamp");
                long expires_in = jsonObject.getLong("expires_in");
                String token = jsonObject.getString("access_token");
                String token_type = jsonObject.getString("token_type");
                if ((System.currentTimeMillis() - add_timestamp) < (expires_in * 1000)) {
                    return token_type+" "+token;
                } else {
                    redisTemplate.delete(key);
                }
            }

            String url = baseUrl + "/oauth/token";
            String authorization = Base64Utils.encodeToString((ClientId+":"+ClientSecret).getBytes());
            String res = httpClientUtil.postBodyAuthorization(url,authorization);
            //{"access_token":"1dd8e41effc4442f82fd04ad855ca3dc","token_type":"bearer","expires_in":43199,"refresh_token":"d48161d20bec4b20b72264aebebc28ef"}
            JSONObject json = JSON.parseObject(res);
            if(json.containsKey("access_token")){
                Long expires_in = json.getLong("expires_in");
                String token = json.getString("access_token");
                String token_type = json.getString("token_type");
                String response = token_type + " " + token;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("access_token",token);
                jsonObject.put("add_timestamp",System.currentTimeMillis());
                jsonObject.put("expires_in",expires_in);
                jsonObject.put("token_type",token_type);
                redisTemplate.opsForValue().set(key,jsonObject.toString());
                return response;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重置token
     */
    public void resetToken(){
        String key = "AccessToken:jumi";
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
    }

    /**
     * 巨米请求方式带token
     * @param url
     * @param token
     * @param param
     * @return
     */
    public static String postBodyAuthorization(String url, String token,String param) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", token);
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Accept",MediaType.ALL_VALUE);
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(param, headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }


    /**
     * 获取设备列表
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public String getEquipmentList(Integer pageIndex,Integer pageSize){
        String url = baseUrl + "/oservice/device/list";
        JSONObject json = new JSONObject();
        json.put("page_index",pageIndex);
        json.put("page_size",pageSize);
        json.put("user_id",MerchantNo);
        String res = postBodyAuthorization(url,getToken(),json.toJSONString());
        return res;
    }

    /**
     * 获取设备详情
     * @param deviceNo
     * @return
     */
    public String getEquipmentInfo(String deviceNo){
        String url = baseUrl + "/oservice/device/details";
        JSONObject json = new JSONObject();
        json.put("device_no",deviceNo);
        json.put("user_id",MerchantNo);
        String res = postBodyAuthorization(url,getToken(),json.toJSONString());
        return res;
    }














    public static void main(String[] args) throws Exception{

//        String url = baseUrl + "/oauth/token";
//        String url2 = baseUrl + "/oservice/goods/drug_list";
//        String authorization = Base64Utils.encode((ClientId+":"+ClientSecret).getBytes());
//        System.out.println("authorization="+authorization);
//        JSONObject json = new JSONObject();
//        json.put("page_index",1);
//        json.put("page_size",10);
//        json.put("user_id","999260");
//{"code":0,"message":"","data":{"rows":[{"small_unit":"","smunit_count":0.00,"goods_name":"感冒灵","goods_id":"88A24A7A8B8F4937B45ED6BB94D8B477","goods_sku":"559811C30371494A9D58AEC698430190","goods_self_code":"(选填如：xde125)","goods_category":"4BAE84D3C92D4CA9BB6D026138AD0BA8","goods_category_name":"","goods_code":"1234567123","price":12.9000,"dev_price":0.0,"ec_price":12.9000,"stock":0.0000,"sale_num":0.0000,"specification":"9袋/盒","pic":"","type":"otc甲类","iscfy":0,"indication":"(选填如:用于感冒引起的头痛、发热、鼻塞、鼻涕、咽痛)","approval_number":"国药准字Z44021940","formulation":"冲剂"},{"small_unit":"","smunit_count":0.00,"goods_name":"石黄抗菌片","goods_id":"A4FC6ADB1B4D445FAC3AEB35D72F9D16","goods_sku":"FA515A89FE0F419C8DEB6F6EC24844E9","goods_self_code":"qwerqwe","goods_category":"7F1D1ACD052A4C69AB6B2372E21176C9","goods_category_name":"","goods_code":"9992601000001","price":0.1000,"dev_price":0.0,"ec_price":0.1000,"stock":0.0000,"sale_num":0.0000,"specification":"","pic":"/Content/999260/0/UpLoadImages/2021/8/10/zg_2108101008049633264.png","type":"非处方","iscfy":0,"indication":"","approval_number":"11","formulation":"片剂"}],"total_count":2,"page_count":1}}



//        System.out.println(postBodyAuthorization(url2,"bearer 7d722e44d6f84bbc987ff872180db980",json.toJSONString()));
//        System.out.println(httpClientUtil.postBodyAuthorization2(url,authorization));
        //{"access_token":"1dd8e41effc4442f82fd04ad855ca3dc","token_type":"bearer","expires_in":43199,"refresh_token":"d48161d20bec4b20b72264aebebc28ef"}

        String res = "{\"order_no\":\"D2021081516133580000188\",\"goods_items\":[{\"goods_sku\":\"559811C30371494A9D58AEC698430190\",\"goods_status\":\"02\",\"ack_error\":\"\",\"ir_err\":\"-1\",\"motor_err\":\"-1\",\"remark\":\"[\\\"串口响应超时\\\"]\",\"islast\":0},{\"goods_sku\":\"559811C30371494A9D58AEC698430190\",\"goods_status\":\"02\",\"ack_error\":\"\",\"ir_err\":\"-1\",\"motor_err\":\"-1\",\"remark\":\"[\\\"已存在一个任务\\\"]\",\"islast\":0},{\"goods_sku\":\"559811C30371494A9D58AEC698430190\",\"goods_status\":\"02\",\"ack_error\":\"\",\"ir_err\":\"-1\",\"motor_err\":\"-1\",\"remark\":\"[\\\"已存在一个任务\\\"]\",\"islast\":1}],\"notify_time\":1629015953935,\"notify_type\":\"01\",\"notify_id\":\"54a476d74c9146c0b6064436eadd7418\",\"client_id\":\"AC3124C182B542839D37AF227C5ECAC9\",\"sign\":\"57eecb830dd1d2f76f03d1730003b6d647f6caf4202fb2f8b0b42a946279c50b\"}";
        JSONObject object = JSONObject.parseObject(res);
        JSONArray array = object.getJSONArray("goods_items");
        if (array.size() > 0){
            for (int i=0;i<array.size();i++){
                if (array.getJSONObject(i).getInteger("goods_status") == 2){
                    System.out.println("出药失败");
                }
            }
        }

    }


}
