package com.tofly.ghrq_route.module.emergencyHandle.ui.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gaoyuan.weixinrecord.example.Record;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.module.emergencyHandle.domain.EmergencyHandleData;
import com.tofly.ghrq_route.module.trouble.domain.AuditFileBean;
import com.tofly.ghrq_route.common.ui.activity.UiCheckAddr;
import com.tofly.ghrq_route.common.util.Location.LocationUtil_xu;
import com.tofly.ghrq_route.common.util.app.AppUtil;
import com.tofly.ghrq_route.common.util.file.FileUtil;
import com.tofly.ghrq_route.common.util.file.FileViewUtil;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Amu on 2017/2/21.
 */

@SuppressLint("NonConstantResourceId")
public class EmergencyReportInfoModuleLayout extends LinearLayout {
    @BindView(R.id.text_addr)
    TextView textAddr;
    @BindView(R.id.layout_device)
    LinearLayout layoutDevice;
    @BindView(R.id.text_reporter)
    TextView textReporter;
    @BindView(R.id.text_report_time)
    TextView textReportTime;
    @BindView(R.id.text_contact_phone)
    TextView textContactPhone;
    @BindView(R.id.text_first_type)
    TextView textFirstType;
    @BindView(R.id.text_second_type)
    TextView textSecondType;
    @BindView(R.id.text_user)
    TextView textUser;
    @BindView(R.id.text_emergency_info)
    TextView textEmergencyInfo;
    @BindView(R.id.layout_emergency_info)
    LinearLayout layoutEmergencyInfo;
    @BindView(R.id.addition_gallery)
    LinearLayout additionGallery;
    @BindView(R.id.layout_addition_area)
    LinearLayout layoutAdditionArea;

    private final Context mContext;

    private PermissionHelper permissionHelper;

    private final FileViewUtil fileViewUtil;

    private EmergencyHandleData mEmergencyHandleData;

    private final List<Record> mRecords;

    public EmergencyReportInfoModuleLayout(Context context) {
        this(context, null);
    }

    public EmergencyReportInfoModuleLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EmergencyReportInfoModuleLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;
        fileViewUtil = new FileViewUtil(context);
        permissionHelper = new PermissionHelper(context);
        mRecords = new ArrayList<>();

        initView();
        initListener();
    }

    private void initView() {
        inflate(mContext, R.layout.layout_emergency_report_info_module, this);
        ButterKnife.bind(this);
    }

    private void initListener() {

    }

    public void initEmergencyInfo(EmergencyHandleData emergencyData) {
        if (emergencyData != null) {
            mEmergencyHandleData = emergencyData;
            setViewContent(emergencyData);
        }
    }

    private void setViewContent(EmergencyHandleData emergencyData) {
        /*地址*/
        textAddr.setText(emergencyData.getAddress());
        layoutDevice.setVisibility(GONE);
        double lng = emergencyData.getX();
        double lat = emergencyData.getY();
        if (!Double.isNaN(lng) && lng != 0 && !Double.isNaN(lat) && lat != 0) {
            layoutDevice.setVisibility(VISIBLE);
        }

        double signX = emergencyData.getSignX();
        double signY = emergencyData.getSignY();
        if (!Double.isNaN(signX) && signX != 0 && !Double.isNaN(signY) && signY != 0) {
            layoutDevice.setVisibility(VISIBLE);
        }

        /*上报人*/
        String alarmName = emergencyData.getAlarmPeopleName();
        textReporter.setText(alarmName);

        /*上报时间*/
        String createTime = emergencyData.getCreateTime();
        textReportTime.setText(createTime);

        /*联系电话*/
        String contactPhone = emergencyData.getContactPhone();
        textContactPhone.setText(contactPhone);

        /*一级分类*/
        String firstType = emergencyData.getTypeMainName();
        textFirstType.setText(firstType);

        /*二级分类*/
        String secondType = emergencyData.getTypeName();
        textSecondType.setText(secondType);

        /*责任人*/
        String dispatchUserName = emergencyData.getDispatchUserName();
        textUser.setText(dispatchUserName);

        /*详细描述*/
        String description = emergencyData.getDescription();
        if (description != null && !description.isEmpty()) {
            layoutEmergencyInfo.setVisibility(VISIBLE);
            textEmergencyInfo.setText(description);
        }else {
            layoutEmergencyInfo.setVisibility(GONE);
        }

        /*附件*/
        String emergencyId = emergencyData.getId() + "";
        String fileNote = "附件";

        additionGallery.removeAllViews();
        List<AuditFileBean> takeOrderFiles = emergencyData.getTakeOrderFile();  ///附件
        int fileCount = 0;
        if (takeOrderFiles != null) {
            fileCount = takeOrderFiles.size();
            for (AuditFileBean auditFileBean : takeOrderFiles) {
                getSchemeFiles(emergencyId, auditFileBean, fileNote, additionGallery);
            }
        }

        if (fileCount > 0) {
            layoutAdditionArea.setVisibility(View.VISIBLE);
        } else {
            layoutAdditionArea.setVisibility(View.GONE);
        }
    }

    private void getSchemeFiles(String schemeId, AuditFileBean fileBean, String fileNote, final ViewGroup rootView) {
        if (fileBean != null) {
            FileViewUtil.GetViewCallback getViewCallback = (isSuccess, view) -> {
                if (isSuccess && view != null) {
                    rootView.addView(view);
                }
            };

            String fileName = fileBean.getFileName();
            String filePath = fileBean.getPath();
            if (FileUtil.isFileTypeImage(fileName)) {
                fileViewUtil.getImageFileView(filePath, getViewCallback);
            } else if (FileUtil.isFileTypeAudio(fileName)) {
                fileViewUtil.getAudioFileView(schemeId, filePath, 1, fileNote, mRecords, null, getViewCallback);
            } else {
                fileViewUtil.getFileView(schemeId, filePath, fileName, fileNote, getViewCallback);
            }
        }
    }

    @OnClick({R.id.layout_device, R.id.text_contact_phone})
    void onClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_device:
                LocationUtil_xu.CoordinateClass coordinate = null;
                if (mEmergencyHandleData != null) {
                    double lng = mEmergencyHandleData.getX();
                    double lat = mEmergencyHandleData.getY();
                    double signX = mEmergencyHandleData.getSignX();
                    double signY = mEmergencyHandleData.getSignY();
                    if (!Double.isNaN(signX) && signX != 0 && !Double.isNaN(signY) && signY != 0) {
                        coordinate = new LocationUtil_xu.CoordinateClass(signX, signY, mEmergencyHandleData.getAddress());
                    } else if (!Double.isNaN(lng) && lng != 0 && !Double.isNaN(lat) && lat != 0) {
                        coordinate = new LocationUtil_xu.CoordinateClass(lng, lat, mEmergencyHandleData.getAddress());
                    }
                }
                Activity activity = (Activity) mContext;
                UiCheckAddr.startActivityForResult(activity,
                        UiCheckAddr.SELECT_MODE.TROUBLE_SELECT_ADDR_CHECK, coordinate);
                break;
            case R.id.text_contact_phone:
                checkCallPermission();
                break;
        }
    }

    private void checkCallPermission() {
        String callPermission = Manifest.permission.CALL_PHONE;
        permissionHelper.requestPermissions("请授予[拨号]权限，否则无法进行拨号", new PermissionHelper.PermissionListener() {
            @Override
            public void doAfterGrand(String... permission) {
                startUserCall();
            }

            @Override
            public void doAfterDenied(String... permission) {
                String errstr = "获取授权失败,无法拨打电话";
                ToastUtil.showToast(mContext, errstr);
            }
        }, callPermission);
    }

    private void startUserCall() {
        String mobile = textContactPhone.getText().toString();
        AppUtil.startPhoneCall(mContext, mobile);
    }
}
