package com.wd.workoffice.util;

import android.annotation.SuppressLint;
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.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.BaseMesBean;
import com.wd.workoffice.app.Config;
import com.wd.workoffice.app.WorkApp;
import com.wd.workoffice.bean.event.CheckFeedbackEvent;
import com.wd.workoffice.bean.event.RefreshTokenEvent;
import com.wd.workoffice.bean.mesBean.MenuBean;
import com.wd.workoffice.bean.workEnum.BatLoginType;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.bean.workEnum.PermissionType;
import com.wd.workoffice.retrofit.ApiService;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
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 cn.jpush.android.api.JPushInterface;
import flexible.xd.android_base.network.rtfhttp.RtfHelper;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.LogUtils;
import io.reactivex.disposables.Disposable;
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 {
    /**
     * 处理项目请求地址
     *
     * @return
     */
    public static String getDomain() {
        String domain = Config.DEBUG ? "http://zwang.bat100.net.cn:8000/%s/" : "http://zwang.bat100.net.cn:8000/%s/";
        String loginType = TextUtils.isEmpty(DataKeeper.getInstance().getBatLoginType()) ? BatLoginType.GK.getCode() : DataKeeper.getInstance().getBatLoginType();
        return String.format(domain, loginType);
//        return "http://zwang.bat100.net.cn:8000/gt/";
    }


    /**
     * 将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;
            case 3:
                name = "待重审";
                break;
            case 9:
                name = "已作废";
                break;
        }
        return name;
    }


    /**
     * 0-待审核,1-审核正常,2-审核数据有误
     *
     * @param status
     * @return
     */
    public static String getFinancialTypeStatus(String status) {
        String name = "";
        switch (Integer.valueOf(status)) {
            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 && code < 14) {
            name = "待审核";
        } else if (code == 14) {
            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;
    }

    // 订单状态 100-已下单 200-审核通过 220-审核驳回 300-已接单 500-已入库（已完成）
    public static String getDeviceStatus(Integer code) {
        String name = "";
        switch (code) {
            case 100:
                name = "待审核";
                break;
            case 200:
                name = "待接单";
                break;
            case 300:
                name = "已接单";
                break;
            case 500:
                name = "已完成";
                break;
        }
        return name;
    }

    //    case 0:
//            return @"正常";
//                break;
//            case 1:
//                    return @"维修";
//                break;
//            case 2:
//                    return @"停用";
//                break;
//            case 3:
//                    return @"报废";
    public static String getDeviceListStatus(Integer code) {
        String name = "";
        switch (code) {
            case 0:
                name = "正常";
                break;
            case 1:
                name = "维修";
                break;
            case 2:
                name = "停用";
                break;
            case 3:
                name = "报废";
                break;
        }
        return name;
    }

    public static String getClazzType(String code) {
        String name = "";
        switch (code) {
            case "0":
                name = "塞棒";
                break;
            case "1":
                name = "浸入式水口";
                break;
            case "2":
                name = "长水口";
                break;
            case "3":
                name = "其他";
                break;
        }
        return name;
    }

    /**
     * 判断是否有审核权限
     *
     * @param type   依照界面顺序
     * @param deptId
     * @return
     */
    public static Boolean orderCheckPermission(int type, int deptId) {
        switch (type) {
            case 1:
                if (!hasPermission(PagePermissionType.SALE_ORDER_AUDIT.getPermission())) {
                    return false;
                }
                break;
            case 2:
                if (!hasPermission(PagePermissionType.PO_PURCHASE_AUDIT.getPermission())) {
                    return false;
                }
                break;
            case 3:
                if (!hasPermission(PagePermissionType.FO_SUPPLIER_AUDIT.getPermission())) {
                    return false;
                }
                break;
            case 4:
                if (!hasPermission(PagePermissionType.CO_CRUCIBLE_AUDIT.getPermission())) {
                    return false;
                }
                break;
            case 5:
                if (!hasPermission(PagePermissionType.AO_PACKAGE_APPLY_AUDIT.getPermission())) {
                    return false;
                }
                break;
            case 6:
                if (!hasPermission(PagePermissionType.IO_INSIDE_AUDIT.getPermission())) {
                    return false;
                }
                break;

        }
        if (!TextUtils.equals(UserKeeper.getInstance().getUserDepId(), deptId + "")) {
            return false;
        }
        if (!TextUtils.equals(UserKeeper.getInstance().getUserDepRuler(), "1")) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否有审核权限
     *
     * @param type   依照界面顺序
     * @param deptId
     * @return
     */
    public static Boolean orderReceivePermission(int type, int deptId) {
        switch (type) {
            case 1:
                if (!hasPermission(PagePermissionType.SALE_ORDER_APPLY.getPermission())) {
                    return false;
                }
                break;
            case 2:
                if (!hasPermission(PagePermissionType.PO_PURCHASE_APPLY.getPermission())) {
                    return false;
                }
                break;
            case 3:
                if (!hasPermission(PagePermissionType.FO_SUPPLIER_APPLY.getPermission())) {
                    return false;
                }
                break;
            case 4:
                if (!hasPermission(PagePermissionType.IO_INSIDE_APPLY.getPermission())) {
                    return false;
                }
                break;
            case 5:
//                if (!hasPermission(PagePermissionType.AO_PACKAGE_APPLY_AUDIT.getPermission())) {
//                    return false;
//                }
                break;
            case 6:
                if (!hasPermission(PagePermissionType.CO_CRUCIBLE_APPLY.getPermission())) {
                    return false;
                }
                break;

        }
        if (!TextUtils.equals(UserKeeper.getInstance().getUserDepId(), deptId + "")) {
            return false;
        }
        if (!TextUtils.equals(UserKeeper.getInstance().getUserDepRuler(), "1")) {
            return false;
        }
        return true;
    }

    /**
     * 刷新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());
            }
        });
    }

    /**
     * mes权限
     *
     * @return
     */
    public static void getMesMenu() {
        RtfUtils.getMesRtf().feedbackMenu().compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                if (!data.isSuccess()) {
                    return;
                }
//                List<MenuBean> menuList = JSON.parseArray(data.getData().toString(), MenuBean.class);
                DataKeeper.getInstance().keepMenu(data.getData().toString());
//                for (MenuBean menuBean : menuList) {
//                    if (TextUtils.equals("市场服务",menuBean.getText())){
//                        for (MenuBean.NodesBean node : menuBean.getNodes()) {
//                            if (TextUtils.equals("质量反馈",node.getText())){
//                                DataKeeper.getInstance().keepMenuId(node.getId());
//                            }
//                        }
//                    }
//                }

            }
        });
    }

    /**
     * 根据名称获取菜单id
     *
     * @return
     */
    public static Boolean hasMesMenuPermission(JSONArray permissionList, String buttonName) {
        if (permissionList == null || permissionList.size() == 0) {
            return false;
        }
        for (int i = 0; i < permissionList.size(); i++) {
            if (TextUtils.equals(buttonName, permissionList.getJSONObject(i).getString("name"))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据名称获取菜单id
     *
     * @return
     */
    public static String getMesMenuId(String oneName, String nextName) {
        if (TextUtils.isEmpty((DataKeeper.getInstance().getMenu()))) {
            return "";
        }
        List<MenuBean> menuList = JSON.parseArray(DataKeeper.getInstance().getMenu(), MenuBean.class);
        for (MenuBean menuBean : menuList) {
            if (TextUtils.equals(oneName, menuBean.getText())) {
                for (MenuBean.NodesBean node : menuBean.getNodes()) {
                    if (TextUtils.equals(nextName, node.getText())) {
                        return node.getId();
                    }
                }
            }
        }
        return "";
    }

    /**
     * 判断是否拥有权限
     *
     * @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 hasOrderDeptPermission(String permission) {
        List<String> userPermission = UserKeeper.getInstance().getOrderDeptPermission();
        if (userPermission == null) {
            return true;
        }
        boolean hasPermission = false;
        for (String s : userPermission) {
            if (TextUtils.equals(permission, s)) {
                hasPermission = true;
                break;
            }
        }
        return hasPermission;
    }

    /**
     * 是否是图片
     *
     * @return
     */
    public static boolean isImg(String type) {
        return TextUtils.equals("jpg", type) || 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();
    }

    /*** 小数点后的位数 */
    private static final int POINTER_LENGTH = 3;

    private static final String POINTER = ".";

    private static final String ZERO = "0";

    private static int curSelection;

    /***
     * 保留小数
     * @param editText
     */
    @SuppressLint("SetTextI18n")
    public static void keepDecimals(EditText editText) {
        String number = editText.getText().toString();
        //第一位不能输入小点
        if (number.length() == 1 && TextUtils.equals(number.substring(0, 1), POINTER)) {
            editText.setText("");
            return;
        }

        //第一位0时，后续不能输入其他数字
        if (number.length() > 1 && TextUtils.equals(number.substring(0, 1), ZERO) &&
                !TextUtils.equals(number.substring(1, 2), POINTER)) {
            editText.setText(number.substring(1));
            editText.setSelection(editText.length());
            return;
        }

        String[] numbers = number.split("\\.");
        //已经输入小数点的情况下
        if (numbers.length == 2) {
            //小数处理
            int decimalsLength = numbers[1].length();
            if (decimalsLength > POINTER_LENGTH) {
//                curSelection = editText.getSelectionEnd();
                editText.setText(number.substring(0, numbers[0].length() + 1 + POINTER_LENGTH));
                editText.setSelection(editText.length());
            }
        }
    }


    /***
     * 保留小数监听
     * @param editText
     */
    public static void addDecimalsListener(EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keepDecimals(editText);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /***
     * 140监听
     * @param editText
     */
    public static void addNumListener(EditText editText, TextView textView) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 140) {
                    editText.setText(s.toString().substring(0, 140));
                    editText.setSelection(140);
                } else {
                    textView.setText(s.length() + "/140");
                }
            }
        });
    }

    /**
     * 监听
     *
     * @param sequence
     * @param type     0 ,get 1,delete  2,set
     */
    public static void handleAlias(int sequence, int type) {
        switch (type) {
            case 0:
                JPushInterface.getAlias(WorkApp.getAppContext(), sequence);
                break;
            case 1:
                JPushInterface.deleteAlias(WorkApp.getAppContext(), sequence);
                break;
            case 2:
                JPushInterface.setAlias(WorkApp.getAppContext(), sequence, sequence + "_" + DataKeeper.getInstance().getBatLoginType().toUpperCase());
                break;
            default:
                return;
        }
    }
}
