package com.ywt.core.utils;

//import com.google.gson.JsonObject;
//import org.apache.commons.beanutils.BeanUtils;
import com.google.gson.JsonObject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

/**
 * @author: Walker
 * @date: 2019/1/3
 */
public final class BizUtil {
    /**
     * convert cent to yuan
     *
     * @param cent cent
     * @return value of yuan
     */
    public static double cent2Yuan(int cent) {
        BigDecimal v1 = new BigDecimal(String.valueOf(cent));
        BigDecimal v2 = new BigDecimal("100");
        BigDecimal result = v1.divide(v2, 2, RoundingMode.HALF_UP);
        return result.doubleValue();
    }

    /**
     * convert yuan to cent
     *
     * @param yuan yuan
     * @return value of cent
     */
    public static double yuan2Cent(double yuan) {
        BigDecimal v1 = new BigDecimal(String.valueOf(yuan));
        BigDecimal v2 = new BigDecimal("100");
        BigDecimal result = v1.multiply(v2);
        return result.intValue();
    }

    /**
     * 生成模板消息跳转小程序所需的参数
     *
     * @param appId    跳转的小程序appId
     * @param pagePath 页面
     * @return param string
     */
    public static String getMiniProgramParam(String appId, String pagePath) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("appid", appId);
        jsonObject.addProperty("pagepath", pagePath);
        return jsonObject.toString();
    }

    /**
     * 生成路径url
     * made by 伍永毅
     *
     * @param obj
     * @param url 调用的路径
     * @param mapper
     * @return
     */

    public static String createParentUrl(Object obj, String url, Map<String, String> mapper) {
        Map<String, String> map;
        try {
            map = BeanUtils.describe(obj);
            map.remove("class");
            if (!Checker.isNone(mapper)) {
                for (String key : mapper.keySet()) {
                    if (!Checker.isNone(key)) {
                        map.put(key, mapper.get(key));
                    }
                }
            }
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            for (String key : map.keySet()) {
//               String value = map.get(key) == null ? "" : map.get(key);
                String value = Checker.getStringValue(map.get(key));
                builder.queryParam(key, value);
            }
            UriComponents uriComponents = builder.build();
            return uriComponents.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
