package com.uas.platform.b2b.ps;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uas.platform.b2b.core.util.ContextUtils;
import com.uas.platform.b2b.model.Product;
import com.uas.platform.b2b.model.ProductUsers;
import com.uas.platform.b2b.support.SysConf;
import com.uas.platform.core.util.HttpUtil;
import com.uas.platform.core.util.HttpUtil.Response;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 对接公共物料服务的接口
 *
 * @author dongbw
 * 2018-01-22
 */
public class ProductUtils {

    private static final String PRODUCT_PUBLIC_SERVICE_URL = ContextUtils.getBean(SysConf.class).getProductServiceUrl();

    /**
     * 物料单次请求数据量大小
     */
    private static final int ONE_TIME_DATA_SIZE = 1000;

    /**
     * 批量更新物料
     *
     * @author dongbw
     * @param  products 要保存的物料信息
     * @return 所有更新成功的id
     * @throws Exception
     */
    public static List<Long> update(List<Product> products) throws Exception {
        String res = HttpUtil.doPost(PRODUCT_PUBLIC_SERVICE_URL + "/product/update/b2b", FlexJsonUtils.toJsonDeep(products));
        if (null != res) {
            try {
                // 保存成功物料的id
                List<Long> ids = JSON.parseArray(res, Long.class);
                if (!CollectionUtils.isEmpty(ids)) {
                    return ids;
                } else {
                    throw new RuntimeException("批量更新物料出现异常");
                }
            } catch (Exception e) {
                throw new RuntimeException("批量更新物料出现异常:" + e.getMessage());
            }
        }
        return null;
    }

    /**
     * 单个更新物料
     *
     * @author dongbw
     * @param  product 要保存的物料信息
     * @return 更新成功id
     * @throws Exception
     */
    public static Long updateOne(Product product) throws Exception {
        List<Product> products = new ArrayList<>();
        products.add(product);
        String res = HttpUtil.doPost(PRODUCT_PUBLIC_SERVICE_URL + "/product/update/b2b", FlexJsonUtils.toJsonDeep(products));
        if (null != res) {
            // 保存成功物料的id
            List<Long> ids = JSON.parseArray(res, Long.class);
            if (!CollectionUtils.isEmpty(ids)) {
                return ids.get(0);
            }
        } else {
            throw new RuntimeException("单个更新物料异常");
        }
        return null;
    }

    /**
     * 批量更新物料并加入个人物料库
     *
     * @author dongbw
     * @param  products 要保存的物料信息
     * @return 所有更新成功的id
     * @throws Exception
     */
    public static ModelMap updateProdInfoAndAddToProductUser(List<Product> products) throws Exception {
        ModelMap map = new ModelMap();
        String res = HttpUtil.doPost(PRODUCT_PUBLIC_SERVICE_URL + "/product/update/addToProductUser", FlexJsonUtils.toJsonDeep(products));
        JSONObject response = JSON.parseObject(res);
        if ("true".equals(response.get("success"))) {
            map.put("success", "true");
            // 成功增加的个人产品库数量
            map.put("result", response.get("result"));
            return map;
        } else if (!StringUtils.isEmpty(response.get("message"))){
            map.put("success", "false");
            map.put("message", response.get("message"));
        }
        return map;
    }

    /**
     * 分页批量更新物料并添加到个人产品库
     *
     * @author dongbw
     * @param  products 要保存的物料信息
     * @return map结果
     * @throws Exception
     */
    public static ModelMap paginationUpdateAndAddToProductUser(List<Product> products) throws Exception {
        ModelMap map = new ModelMap();
        int result = 0;
        if (!CollectionUtils.isEmpty(products)) {
            if (products.size() <= ONE_TIME_DATA_SIZE) {
                map = updateProdInfoAndAddToProductUser(products);
                result = (int) map.get("result");
            } else {
                List<Product> pageContent = new ArrayList<>();
                int i = 1;
                for (Product product : products) {
                    pageContent.add(product);
                    if (i++ % ONE_TIME_DATA_SIZE == 0) {
                        ModelMap modelMap = updateProdInfoAndAddToProductUser(pageContent);
                        if ("false".equals(modelMap.get("success")) && null != modelMap.get("message")) {
                            map.put("success", "false");
                            map.put("message", modelMap.get("message"));
                        }
                        result += (int) (null != modelMap.get("result") ? modelMap.get("result") : 0);
                        pageContent = new ArrayList<>();
                    }
                }
                if (!pageContent.isEmpty()) {
                    ModelMap modelMap = updateProdInfoAndAddToProductUser(pageContent);
                    if ("false".equals(modelMap.get("success")) && null != modelMap.get("message")) {
                        map.put("success", "false");
                        map.put("message", modelMap.get("message"));
                    }
                    result += (int) (null != modelMap.get("result") ? modelMap.get("result") : 0);
                }
            }
        }
        if (!"false".equals(map.get("success"))) {
            map.put("success", "true");
        }
        map.put("result", result);
        return map;
    }

    /**
     * 单个更新个人物料
     *
     * @author dongbw
     * @param  productUser 要保存的个人物料信息
     * @return
     * @throws Exception
     */
    public static Long updateProductUsersOne(ProductUsers productUser) throws Exception {
        List<ProductUsers> productUsers = new ArrayList<>();
        productUsers.add(productUser);
        String res = HttpUtil.doPost(PRODUCT_PUBLIC_SERVICE_URL + "/productuser/save", FlexJsonUtils.toJsonDeep(productUsers));
        if (null == res) {
            throw new RuntimeException("保存个人物料失败");
        }
        return null;
    }

    /**
     * 单个删除个人物料
     *
     * @author dongbw
     * @param  id 要删除的个人物料id
     * @return
     * @throws Exception
     */
    public static ModelMap deleteProductUser(Long id) throws Exception {
        HashMap<String, Object> params = new HashMap<>();
        params.put("id", id);
        Response res = HttpUtil.sendPostRequest(PRODUCT_PUBLIC_SERVICE_URL + "/productuser/edit/delete", params);
        if (HttpStatus.OK.value() == res.getStatusCode()) {
            return new ModelMap("success", "删除个人物料成功");
        } else {
            throw new RuntimeException("删除个人物料失败");
        }
    }

    /**
     * 批量删除个人物料
     *
     * @author dongbw
     * @param  idList 要删除的个人物料idList
     * @return
     * @throws Exception
     */
    public static void deleteProductUserByBatch(List<Long> idList) throws Exception {
        HashMap<String, Object> params = new HashMap<>();
        params.put("ids", FlexJsonUtils.toJsonDeep(idList));
        Response res = HttpUtil.sendPostRequest(PRODUCT_PUBLIC_SERVICE_URL + "/productuser/edit/deleteByBatch", params);
        if (HttpStatus.OK.value()!= res.getStatusCode()) {
            throw new RuntimeException("删除个人物料失败");
        }
    }

    /**
     * 个人物料批量转入个人物料库
     * @param ids 转入的物料ids
     * @param enUU  企业UU
     * @param userUU 用户UU
     * @return
     */
    public static Integer coverToUserProd(List<Long> ids, Long enUU, Long userUU) throws Exception {
        HashMap<String, Object> params = new HashMap<>();
        ModelMap data = new ModelMap();
        data.put("ids",  ids.toString());
        data.put("enUU", enUU);
        data.put("userUU", userUU);
        params.put("data", data);
        Response res = HttpUtil.sendPostRequest(PRODUCT_PUBLIC_SERVICE_URL + "/productuser/coverToUserByIds", params);
        if (HttpStatus.OK.value() == res.getStatusCode()) {
            return Integer.valueOf(res.getResponseText());
        } else {
            throw new RuntimeException("批量转入个人物料库失败");
        }
    }
}
