package com.diaoyun.zion.chinafrica.service.impl;

import com.diaoyun.zion.chinafrica.constant.KeyConstant;
import com.diaoyun.zion.chinafrica.entity.ProductPageInfo;
import com.diaoyun.zion.chinafrica.service.ShopifyService;
import com.diaoyun.zion.chinafrica.vo.ShopifyConstant;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.common.RedisCache;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.util.HttpClientUtil;
import com.diaoyun.zion.master.util.ListUtil;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;


/**
 * @Auther: wudepeng
 * @Date: 2019/11/15
 * @Description:
 */
@Service("shopifyService")
public class ShopifyServiceImpl implements ShopifyService {
    private static Logger logger = LoggerFactory.getLogger(ShopifyServiceImpl.class);

    @Resource
    private RedisCache<Object> redisCache;

    /**
     * 查询商品
     *
     * @return
     */
    @Override
    public Result queryShopifyProducts() {
        List type = Arrays.asList("Christmas", "Men", "Women", "Face", "virgin hair", "Afri Home", "Children");
        Result result = new Result();
        Map<String, Object> params = new HashMap<>();
        List<String> list = new ArrayList();
        try {
            List products = (List) redisCache.get(KeyConstant.SHOPIFY_ITEMS);
            if (products != null && products.size() == type.size()) {
                JSONArray jsonArray = JSONArray.fromObject(products);
                result.setData(jsonArray);
                return result;
            }
//            List type = (List) redisCache.get(KeyConstant.SHOPIFY_TYPE);
//            if (type == null) {
//                type = getProductType();
//            }

            for (int i = 0; i < type.size(); i++) {
                params.put("product_type", type.get(i));
                params.put("limit", ShopifyConstant.SHOPIFY_LIMIT);
                String data = HttpClientUtil.createConnection(ShopifyConstant.productTypeUrl(), params, "UTF-8");
                list.add(data);
                redisCache.set(KeyConstant.SHOPIFY_ITEMS, list, 86400);
            }
            System.out.println(list);
            JSONArray jsonArr = JSONArray.fromObject(list);
            result.setData(jsonArr).setMessage("success");
        } catch (IOException e) {
            result.setCode(ResultCodeEnum.QUERY_ERROR.getCode()).setMessage(e.getMessage());
            logger.error(e.getMessage(), e);
            return result;
        }
        return result;
    }


    /**
     * 查询分类商品
     *
     * @param product_type
     * @return
     */
    @Override
    public Result queryProductsByType(String product_type, String page_info) {
        Result result = new Result();
        String url = ShopifyConstant.productTypeUrl() + "?limit=" + ShopifyConstant.SHOPIFY_PAGE_SIZE;
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotBlank(product_type)) {
            params.put("product_type", product_type);
            url = url + "&product_type=" + product_type;
        }
        params.put("limit", ShopifyConstant.SHOPIFY_PAGE_SIZE);
        try {
            if (StringUtils.isNotBlank(page_info)) {
                params.remove("product_type");
                params.put("page_info", page_info);
                url = url.substring(0, url.lastIndexOf("&")) + "&page_info=" + page_info;
            }
            List<String> headers = HttpClientUtil.getHeaders(url);
            ProductPageInfo pageInfo = new ProductPageInfo();
            String flag = headers.get(headers.size() - 1);
            if ("first".equals(flag)) {
                pageInfo.setNext(headers.get(0));
            } else if ("middle".equals(flag)) {
                pageInfo.setPrevious(headers.get(0));
                pageInfo.setNext(headers.get(1));
            } else {
                pageInfo.setPrevious(headers.get(0));
            }
            String data = HttpClientUtil.createConnection(ShopifyConstant.productTypeUrl(), params, "UTF-8");
            List<String> list = new ArrayList<>();
            list.add(data);
            pageInfo.setProductInfo(list);
            JSONObject jsonObject = JSONObject.fromObject(pageInfo);
            result.setData(jsonObject).setMessage(ResultCodeEnum.SUCCESS.getDesc());
        } catch (Exception e) {
            result.setCode(ResultCodeEnum.QUERY_ERROR.getCode()).setMessage(e.getMessage());
            logger.error(e.getMessage(), e);
            return result;
        }
        return result;
    }

    /**
     * 查看商品详情
     *
     * @param product_id
     * @return
     */
    @Override
    public Result queryProductsDetails(String product_id) {
        Result result = new Result();
        JSONObject jsonProduct = null;
        try {
            String product = (String) redisCache.get(KeyConstant.SHOPIFY_ITEM + product_id);
            if (product != null) {
                jsonProduct = JSONObject.fromObject(product);
            } else {
                Map<String, Object> params = new HashMap<>();
                params.put("ids", product_id);
                String data = HttpClientUtil.createConnection(ShopifyConstant.productTypeUrl(), params, "UTF-8");
                jsonProduct = JSONObject.fromObject(data);
                redisCache.set(KeyConstant.SHOPIFY_ITEM + product_id, data, 86400);
            }
            result.setData(jsonProduct);
        } catch (IOException e) {
            result.setCode(ResultCodeEnum.QUERY_ERROR.getCode()).setMessage(e.getMessage());
            logger.error(e.getMessage(), e);
            return result;
        }
        return result;
    }

    /**
     * 查询所有商品
     *
     * @param product_id
     * @return
     */
    public Result queryAllProducts(String product_id) {
        Result result = new Result();
        try {
            JSONObject jsonObject = null;
            String allProducts = (String) redisCache.get(KeyConstant.SHOPIFY_ITEMS_ALL + product_id);
            if (allProducts != null) {
                jsonObject = JSONObject.fromObject(allProducts);
                result.setData(jsonObject);
                return result;
            }
            Map<String, Object> params = new HashMap<>();
            //params.put("limit", ShopifyConstant.SHOPIFY_PAGE_SIZE);
            params.put("since_id", product_id);
            String data = HttpClientUtil.createConnection(ShopifyConstant.productTypeUrl(), params, "UTF-8");
            redisCache.set(KeyConstant.SHOPIFY_ITEMS_ALL + product_id, data);
            jsonObject = JSONObject.fromObject(data);

            result.setData(jsonObject);
        } catch (Exception e) {
            result.setCode(ResultCodeEnum.QUERY_ERROR.getCode()).setMessage(e.getMessage());
            logger.error(e.getMessage(), e);
            return result;
        }
        return result;
    }

    /**
     * 查询所有商品分类
     *
     * @return
     * @throws IOException
     */
    public List getProductType() throws IOException {
        Map<String, Object> params = new HashMap<>();
        params.put("fields", "product_type");
        String connection = HttpClientUtil.createConnection(ShopifyConstant.productTypeUrl(), params, "UTF-8");
        List list = new ArrayList();
        JSONArray products = JSONObject.fromObject(connection).getJSONArray("products");
        for (int i = 0; i < products.size(); i++) {
            String product_type = products.getJSONObject(i).getString("product_type");
            if (!"".equals(product_type) && !list.contains(product_type)) {
                list.add(product_type);
            }
        }
        //将商品类型放到缓存中
        redisCache.set(KeyConstant.SHOPIFY_TYPE, list);
        return list;
    }

    /**
     * 根据商品标题搜索
     *
     * @param title
     * @return
     */
    public Result searchProductByTitle(String title) {
        Result result = new Result();
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("title", title);
            String data = HttpClientUtil.createConnection(ShopifyConstant.productTypeUrl(), params, "UTF-8");
            JSONObject jsonObject = JSONObject.fromObject(data);
            result.setData(jsonObject);
        } catch (Exception e) {
            result.setCode(ResultCodeEnum.QUERY_ERROR.getCode()).setMessage(e.getMessage());
            logger.error(e.getMessage(), e);
            return result;
        }
        return result;

    }

}
