package com.wd.workoffice.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.load.ImageHeaderParser;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wd.workoffice.R;
import com.wd.workoffice.app.Config;
import com.wd.workoffice.app.WorkApp;
import com.wd.workoffice.bean.event.RefreshTokenEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.bean.workEnum.PermissionType;
import com.wd.workoffice.retrofit.ApiService;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.ui.adapter.StarAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import flexible.xd.android_base.network.rtfhttp.RtfHelper;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class WorkUtils {

    /**
     * 将map数据转换为 普通的 json RequestBody
     *
     * @param map 以前的请求参数
     * @return
     */
    public static RequestBody convertMapToBody(Map<?, ?> map) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(map));
    }

    public static Map<String, Object> simpleParam() {
        Map<String, Object> param = new HashMap<>();
        return param;
    }

    public static Map<String, Object> pageKey() {
        Map<String, Object> param = new HashMap<>();
        param.put("size", Config.SIZE);
        return param;
    }

    public static Map<String, Object> pageMesKey() {
        Map<String, Object> param = new HashMap<>();
        param.put("length", Config.SIZE);
        param.put("paramMap", new HashMap<>());
        return param;
    }

    /**
     * code： SUPPLIER-供应商 CUSTOMER-客户 TRANSPORTERS-运输商
     *
     * @param code
     * @return
     */
    public static String getClientType(String code) {
        if (TextUtils.equals("SUPPLIER", code)) {
            return "供应商";
        } else if (TextUtils.equals("CUSTOMER", code)) {
            return "客户";
        } else {
            return "运输商";
        }
    }

    /**
     * code： 1：生产部门 2：销售部门 3：业务部门
     *
     * @param code
     * @return
     */
    public static String getDepType(Integer code) {
        String name = "";
        switch (code) {
            case 1:
                name = "生产部门";
                break;
            case 2:
                name = "销售部门";
                break;
            case 3:
                name = "业务部门";
                break;
        }
        return name;
    }

    /**
     * code： IN：厂内库 OUT：场外库
     *
     * @param code
     * @return
     */
    public static String getStockType(String code) {
        if (TextUtils.equals("IN", code)) {
            return "厂内库";
        } else if (TextUtils.equals("OUT", code)) {
            return "场外库";
        } else {
            return "场外库";
        }
    }

    /**
     * code： "1"：中转入库
     * "2"：直接入库
     *
     * @param code
     * @return
     */
    public static String getEnterStockType(String code) {
        if (TextUtils.equals("1", code)) {
            return "中转入库";
        } else if (TextUtils.equals("2", code)) {
            return "直接入库";
        } else {
            return "";
        }
    }

    /**
     * name：订单code
     *
     * @param name
     * @return
     */
    public static String getOrderCode(String name) {
        String code = "";
        for (OrderType value : OrderType.values()) {
            if (TextUtils.equals(value.getName(), name)) {
                code = value.getCode();
            }
        }
        return code;
    }

    /**
     * name：订单code
     *
     * @param code
     * @return
     */
    public static String getOrderName(String code) {
        String name = "";
        for (OrderType value : OrderType.values()) {
            if (TextUtils.equals(value.getCode(), code)) {
                name = value.getName();
            }
        }
        return name;
    }

    /**
     * name：流程code
     *
     * @param code
     * @return
     */
    public static String getPermissionName(String code) {
        String name = "";
        for (PermissionType value : PermissionType.values()) {
            if (TextUtils.equals(value.getCode(), code)) {
                name = value.getName();
            }
        }
        return name;
    }

    /**
     * name：订单来源
     * ：PDS-拆分生产订单 TRS-库存已有转单
     *
     * @param code
     * @return
     */
    public static String getOrderFrom(String code) {
        String name = "";
        if (TextUtils.equals(code, "PDS")) {
            name = "拆分生产订单";
        } else if (TextUtils.equals(code, "TRS")) {
            name = "库存已有转单";
        }
        return name;
    }

    /**
     * 财务状态
     * 0未审核      1已通过      2不通过
     *
     * @param code
     * @return
     */
    public static String getFinancialStatus(Integer code) {
        String name = "";
        switch (code) {
            case 0:
                name = "待审核";
                break;
            case 1:
                name = "已通过";
                break;
            case 2:
                name = "已驳回";
                break;
        }
        return name;
    }

    /**
     * 财务状态
     * 10未审核 11 12 13 14已通过 21 22 23 24不通过(尾号1部门管理员 2业务部 3财务部 4集团，首数字1：通过，2:驳回)
     *
     * @param code
     * @return
     */
    public static String getReturnStatus(Integer code) {
        String name = "";
        if (code == 10) {
            name = "未审核";
        } else if (code.toString().startsWith("1")) {
            name = "已通过";
        } else if (code.toString().startsWith("2")) {
            name = "已驳回";
        }
        return name;
    }

    // 0草稿、1已提交、2执行中、3已总结、4已评价
    public static String getTicketStatus(Integer code) {
        String name = "";
        switch (code) {
            case 0:
                name = "草稿";
                break;
            case 1:
                name = "已提交";
                break;
            case 2:
                name = "执行中";
                break;
            case 3:
                name = "已总结";
                break;
            case 4:
                name = "已评价";
                break;
        }
        return name;
    }

    /**
     * 刷新token
     *
     * @return
     */
    public static void refreshToken() {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("client_id", "android");
        param.put("client_secret", "android");
        param.put("refresh_token", UserKeeper.getInstance().getRefreshToken());
        RtfUtils.getRtf().refreshToken(param).enqueue(new Callback<JSONObject>() {
            @Override
            public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
                if (response.isSuccessful()) {
                    JSONObject data = response.body();
                    UserKeeper.getInstance().keepLoginInfo(data.toJSONString());
                }
                EventBus.getDefault().post(new RefreshTokenEvent());
            }

            @Override
            public void onFailure(Call<JSONObject> call, Throwable t) {
                EventBus.getDefault().post(new RefreshTokenEvent());
            }
        });
    }

    /**
     * 判断是否拥有权限
     *
     * @return
     */
    public static boolean hasPermission(String permission) {
        List<String> userPermission = UserKeeper.getInstance().getUserPermission();
        if (userPermission == null) {
            return true;
        }
        boolean hasPermission = false;
        for (String s : userPermission) {
            if (TextUtils.equals(permission, s)) {
                hasPermission = true;
                break;
            }
        }
        return hasPermission;
    }

    public static void addPermissionRule(View view) {
        List<View> list = getAllChildViews(view);
        for (View child : list) {
            if (child.getTag() != null) {
                if (!hasPermission(child.getTag().toString())) {
                    child.setVisibility(View.GONE);
                }
            }
        }
    }

    private static List<View> getAllChildViews(View view) {
        List<View> allChildren = new ArrayList<>();
        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewchild = vp.getChildAt(i);
                allChildren.add(viewchild);
                //再次 调用本身（递归）
                allChildren.addAll(getAllChildViews(viewchild));
            }
        }
        return allChildren;
    }

    /**
     * 是否是图片
     *
     * @return
     */
    public static boolean isImg(String type) {
        return TextUtils.equals("jpeg", type) || TextUtils.equals("gif", type) || TextUtils.equals("webp", type) ||
                TextUtils.equals("png", type) || TextUtils.equals("bmp", type) || TextUtils.equals("JPEG", type) || TextUtils.equals("GIF", type) || TextUtils.equals("WEBP", type) ||
                TextUtils.equals("PNG", type) || TextUtils.equals("BMP", type);
    }

    /**
     * 小星星布局
     *
     * @return
     */
    public static StarAdapter starView(RecyclerView rvData, Context context) {
        rvData.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
        List<String> dataList = Arrays.asList("", "", "", "", "");
        StarAdapter starAdapter = new StarAdapter(R.layout.item_star, dataList);
        starAdapter.bindToRecyclerView(rvData);
        return starAdapter;
    }

    public static File uriToFile(Uri uri, Context context) {
        String path = null;
        if ("file".equals(uri.getScheme())) {
            path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = context.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA}, buff.toString(), null, null);
                int index = 0;
                int dataIdx = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    index = cur.getInt(index);
                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cur.getString(dataIdx);
                }
                cur.close();
                if (index == 0) {
                } else {
                    Uri u = Uri.parse("content://media/external/images/media/" + index);
                    System.out.println("temp uri is :" + u);
                }
            }
            if (path != null) {
                return new File(path);
            }
        } else if ("content".equals(uri.getScheme())) {
            // 4.2.2以后
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(path);
        } else {
            //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
        }
        return null;
    }

    public static String replacePhone(String phone) {
        if (phone.length() > 7) {
            return phone.substring(0, 3) + " **** " + phone.substring(7, phone.length());
        } else if (phone.length() > 4) {
            return phone.substring(0, 3) + " ****";
        } else {
            return phone;
        }
    }

    /**
     * 倒计时
     *
     * @param txtTime
     * @param AllTime
     * @param JianGe
     */
    public static <T extends TextView> CountDownTimer timerSeckill(final T txtTime, long AllTime, final int JianGe, final int code) {
        if (code == 0) {
            txtTime.setClickable(false);
        }
        CountDownTimer timer = new CountDownTimer(AllTime, JianGe) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (code == 0) {
                    txtTime.setText("( " + String.valueOf(millisUntilFinished / JianGe) + " )");
                    txtTime.setTextColor(WorkApp.getApp().getResources().getColor(R.color.flexible_text_gray));
                } else {
                    txtTime.setText("跳过  " + String.valueOf(millisUntilFinished / JianGe) + "s");
                }
            }

            @Override
            public void onFinish() {
                if (code == 0) {
                    txtTime.setText("重新获取");
                    txtTime.setClickable(true);
                    txtTime.setTextColor(WorkApp.getApp().getResources().getColor(R.color.mainColor));
                } else {
                    txtTime.setText("跳过  0s");
                }
            }
        };
        return timer.start();
    }
}
