package com.yfd.platform.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author liwt date 2022/6/2212:11
 * @title: SystemUtils
 */
public class SystemUtils {

	public static HttpServletRequest getRequest()
	{
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}

	public static HttpServletResponse getResponse()
	{
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		return response;
	}

	public static Page setPage(Map<String, Object> json)
	{
		Page page = new Page();
		page.setSize(json.get("size") == null ? 0 : Integer.parseInt(json.get("size").toString()));
		page.setCurrent(json.get("current") == null ? 1 : Integer.parseInt(json.get("current").toString()));
		return page;
	}

	public static Page setPage(Page page)
	{
		HttpServletRequest request = getRequest();

		String pageSize = request.getParameter("pageSize");
		if(StringUtils.isNotEmpty(pageSize)){
			page.setSize(Long.parseLong(pageSize));
		}
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isNotEmpty(pageNo)){
			page.setCurrent(Long.parseLong(pageNo));
		}

		return page;
	}
	public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) throws Exception
	{
		T bean = clazz.newInstance();
		BeanMap beanMap = BeanMap.create(bean);
		beanMap.putAll(map);
		return bean;
	}



	public static void setRollbackOnly()
	{
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	}


    /**
     *
     * @param a 有值得类，向b复制
     * @param b 一般来说是空的类
     */
    public static void copyProperties(Object a,Object b){
        BeanUtils.copyProperties(a,b );
    }



    private static SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat simpleDateTimeFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    public static  String getDateByDateTime(String dateTime) {
        if(StringUtils.isEmpty(dateTime)){
            return "";
        }
        String format;
        try {
            format = simpleDateFormat.format(simpleDateFormat.parse(dateTime));
        }catch (Exception e){
            return "";
        }
        return format;
    }

    public static String getDateByDateTime(Date dateTime){
        if(dateTime==null){
            return "";
        }
        String format = simpleDateFormat.format(dateTime);
        return format;
    }


    /**
     * 补0
     * @param data 数据
     * @param dataLength 最终长度
     * @return
     */
    public static String getZeroFill(Object data,Integer dataLength){
        return String.format("%0" + dataLength + "d", Integer.parseInt(data.toString()));
    }

    /**
     * 将时间格式转换为string格式 yyyy-MM-dd HH:mm:ss
     * @param o
     * @return
     */
    public static String getStringDateTimeByObject(Date o){
        return simpleDateTimeFormat.format(o);
    }

    /**
     * 将时间格式转换为string格式 yyyy-MM-dd
     * @param o
     * @return
     */
    public static String getStringDateByObject(Date o){

       return simpleDateFormat.format(o);
    }



	public static String getNowDate(Calendar calendar){
		if(calendar==null){
			calendar=Calendar.getInstance();
		}
		// 获取当前年
		int year = calendar.get(Calendar.YEAR);
// 获取当前月
		int month = calendar.get(Calendar.MONTH) + 1;
// 获取当前日
		int day = calendar.get(Calendar.DATE);
// 获取当前小时
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
// 获取当前分钟
		int minute = calendar.get(Calendar.MINUTE);
// 获取当前秒
		int second = calendar.get(Calendar.SECOND);
// 获取当前是本周第几天
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
// 获取当前是本月第几天
		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
// 获取当前是本年第几天
		int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);


		String thisVersion=year+getZeroFill(month,2)+getZeroFill(day,2)+getZeroFill(hour,2)+getZeroFill(minute,2);
		return thisVersion;
	}



	public static String getUUID(){
		String string = UUID.randomUUID().toString();
		string=string.replace("-","");
		return string;
	}

	public static <T> void setPageOrder(Page page,T obj){
		Object sortName = null;
		Object sortOrder = null;

		if(obj!=null){
			String jsonString = JSONObject.toJSONString(obj);
			HashMap hashMap = JSONObject.parseObject(jsonString, HashMap.class);
			sortName = hashMap.get("sortName");
			sortOrder = hashMap.get("sortOrder");
		}else{
			HttpServletRequest request = SystemUtils.getRequest();
			sortName = request.getParameter("sortName");
			sortOrder = request.getParameter("sortOrder");
		}


		if(sortName!=null&&StringUtils.isNotEmpty(sortName.toString())){
			List<OrderItem> list=new ArrayList<>();

			OrderItem orderItem = new OrderItem();
			orderItem.setColumn(sortName.toString());
			orderItem.setAsc(true);
			if(sortOrder!=null&&StringUtils.isNotEmpty(sortOrder.toString())){
				String sortOrderStr = sortOrder.toString();
				if("asc".equals(sortOrderStr)){
					orderItem.setAsc(true);
				}else{
					orderItem.setAsc(false);
				}
			}
			list.add(orderItem);
			page.setOrders(list);
		}





	}


	public static Map<String,Object> objectToMap(Object o){
		JSONObject jsonObject=(JSONObject) JSON.toJSON(o);
		Map<String,Object> javaObject = jsonObject.toJavaObject(Map.class);
		return javaObject;
	}


	public static <T> T mapToObject(Map<String,Object> map, Class<T> classObj ){
		String jsonString = JSON.toJSONString(map);
		T t = JSON.parseObject(jsonString, classObj);
		return t;
	}
	public static <T> T  objectToEntity(Object o,Class<T> classObj ){
		String jsonString = JSON.toJSONString(o);
		T t = JSON.parseObject(jsonString, classObj);
		return t;
	}


	public static String getError(Exception e){
		String msg=e.getMessage();
		if(StringUtils.isNotEmpty(msg)){
			return msg;
		}

		msg=e.getCause().getMessage();
		if(StringUtils.isNotEmpty(msg)){
			return msg;
		}
		msg=JSON.toJSONString(e);
		if(StringUtils.isNotEmpty(msg)){
			return msg;
		}
		return "err还是null";
	}

	public static LocalDate getLocalDateByDate(Date date){
		Instant instant = date.toInstant();
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
		LocalDate localDate = localDateTime.toLocalDate();
		return localDate;
	}

	public static LocalDateTime getLocalTimeDateByDate(Date date){
		Instant instant = date.toInstant();
		LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
		return localDateTime;
	}

	public static BigDecimal getBigDecimalByString(String str){
		Double l = Double.parseDouble(str);

		BigDecimal bigDecimal = BigDecimal.valueOf(l);

		return bigDecimal;

	}


	public static <T> T objectToObject(Object o,Class<T> tClass){
		String jsonString = JSON.toJSONString(o);
		T javaObject = JSON.parseObject(jsonString,tClass);
		return javaObject;
	}

}
