package com.efounder.chat.item;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.db.FileEntity;
import com.efounder.chat.http.download.DownloadInfo;
import com.efounder.chat.http.download.DownloadManager;
import com.efounder.chat.http.download.State;
import com.efounder.chat.item.manager.IMessageItem;
import com.efounder.chat.utils.FileUtil;
import com.efounder.chat.utils.SPUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.util.CloudUtil;
import com.efounder.frame.ViewSize;
import com.efounder.frame.utils.Constants;
import com.efounder.message.struct.IMStruct002;
import com.efounder.tbs.DisplayFileWithTbsUtil;
import com.efounder.ui.util.DisplayUtil;
import com.efounder.util.AppContext;
import com.efounder.util.JSONUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.library.utils.OkHttpUtils;
import com.pansoft.library.utils.ReadFileUtils;
import com.tencent.smtt.sdk.TbsVideoUtils;
import com.utilcode.util.FileIntentUtils;

import net.sf.json.JSONObject;

import java.io.File;

//import com.efounder.chat.http.download.DownloadInfo;
//import com.efounder.chat.http.download.DownloadManager;
//import com.efounder.chat.http.download.State;
//import com.efounder.chat.utils.SPUtils;

/**
 * 附件item
 * Created by zhangshunyun on 2017/6/20.
 */

public class FileMessageItem extends LinearLayout implements IMessageItem, View.OnClickListener {

    private Context mContext;
    private LinearLayout messageItemLayout;
    private TextView fileDescribe;
    private TextView fileSize;
    private ImageView filePicture;
    private ProgressBar fileProgress;
    private IMStruct002 iMStruct002;
    private String path;// 文件路径
    private boolean isInUse;
    private boolean isLocalFile = false;
    private String fileName;
    private String fileType = "";
    private boolean isVideo;
    private boolean isdownLoading;
    private String path1;
    private TextView tvIsDown;
    private File desFile;
    //    private FileInfo fileInfo;
    private boolean isDone;
    private DownloadInfo downloadInfo;
    private String extraMessageID;
    private boolean downloadOnGPRS = false;
    private long curTime;
    private long lastTime;

    public FileMessageItem(Context context) {
        super(context);
//        DownloadManager.getInstance().addObserve(this);
        mContext = context;

        initView(context);
    }

    private void initView(Context context) {
        this.setPadding(12, 5, 12, 5);
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        messageItemLayout = (LinearLayout) inflate.inflate(R.layout.chat_item_message_file, this);
        tvIsDown = (TextView) messageItemLayout.findViewById(R.id.tv_file_isdown);
        tvIsDown.setVisibility(INVISIBLE);
        fileDescribe = (TextView) messageItemLayout.findViewById(R.id.tv_file_describe);
        fileSize = (TextView) messageItemLayout.findViewById(R.id.tv_file_size);
        filePicture = (ImageView) messageItemLayout.findViewById(R.id.iv_file_picture);
        fileProgress = (ProgressBar) messageItemLayout.findViewById(R.id.pb_file_progress);
        int width = DisplayUtil.getMobileWidth(mContext) * 2 / 3 - 40;
        LayoutParams lp = new LayoutParams(
                width, ViewGroup.LayoutParams.WRAP_CONTENT);
        messageItemLayout.setLayoutParams(lp);
        //设置监听
        setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        lastTime = curTime;
        curTime = System.currentTimeMillis();
        if (curTime - lastTime > 600) {
            if (path1 == "") {
                Toast.makeText(mContext, R.string.wechatview_fileid_fail_get, Toast.LENGTH_SHORT).show();
                return;
            }
            final String url = getPathOrUrl(iMStruct002);//索引位置
            if (null == url) {
                Toast.makeText(mContext, R.string.wechatview_addr_fail_get, Toast.LENGTH_SHORT).show();
                return;
            }
            if (isLocalFile) {
                //是本地文件
                if (null != iMStruct002.getExtra("progress")) {
                    if ((int) iMStruct002.getExtra("progress") != 100 && (int) iMStruct002.getExtra("progress") != 0 && fileProgress.getVisibility() == VISIBLE) {
                        OkHttpUtils.cancelAllRequest();
                    } else {
                        startOpenIntent(url);
                    }
                } else {
                    startOpenIntent(url);
                }

            } else if (desFile.exists() && isDone) {
                //是下载过的且是成功的
                startOpenIntent(desFile.getAbsolutePath());
            } else {
                //不是本地文件
                download(url);
            }
        }
    }


    //打开intent
    public void startOpenIntent(String url) {
        try {
//            Intent intent = FileUtil.openFile(url);
////            mContext.startActivity(intent);


            FileIntentUtils.openFileByPath(mContext,url);

            //使用tbs播放
//            if (!DisplayFileWithTbsUtil.previewLocalFile(mContext, url)) {
//                FileIntentUtils.openFileByPath(mContext, url);
//            }

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToast(AppContext.getInstance(), R.string.wechatview_not_search_app);
        }
    }

    /**
     * 下载
     *
     * @param url
     */
    private void download(String url) {
        File fileDir = new File(FileUtil.filePath + "/" + path1);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        desFile = new File(fileDir + "/" + getFileName(iMStruct002));
        DownloadManager.getInstance().handleClick(extraMessageID, mContext, url, fileName, desFile.getAbsolutePath(), CloudUtil.CLOUD_BASE_URL
                , iMStruct002);
    }

    public void clickItem() {
        onClick(this);
    }

    public boolean getIsLocalFile() {
        return isLocalFile;
    }

    public File getDesFile() {
        return desFile;
    }

    public boolean getIsDone() {
        return isDone;
    }

    private String getPathOrUrl(IMStruct002 imStruct002) {
        String path1;
        if (iMStruct002.getMessage().contains("Fileid")) {
            path1 = JSONUtil.parseJson(iMStruct002.getMessage()).get("Fileid").getAsString();
        } else if (iMStruct002.getMessage().contains("FileId")) {
            path1 = JSONUtil.parseJson(iMStruct002.getMessage()).get("FileId").getAsString();
        } else {
            return null;
        }
        if (imStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {//发送的消息
            String path = JSONUtil.parseJson(imStruct002.getMessage()).get("FileLocalPath").getAsString();
            if (new File(path).exists()) {//发送的消息本地文件是否存在（多设备登录，某设备会没有本地文件）
                return path;
            } else {//本地文件不存在，返回url
                //判断文件是否已经下载过了
                String localPath = FileUtil.filePath + path1 + "/" + getFileName(iMStruct002);
                if (new File(localPath).exists()) {
                    return localPath;
                }
                isLocalFile = false;
                return CloudUtil.CLOUD_BASE_URL + "files/" + path1 + "/download";
//                return "http://www.pangcloud.cn:9123/panserver/" + "files/" + path1 + "/download";
            }
        } else {
            return CloudUtil.CLOUD_BASE_URL + "files/" + path1 + "/download";
//            return "http://www.pangcloud.cn:9123/panserver/" + "files/" + path1 + "/download";
        }
    }

    @Override
    public void setIMStruct002(IMStruct002 message) {
        this.iMStruct002 = message;
        try {
            dataChanged(message);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.showToast(mContext, R.string.wechatview_operation_error);
        }
    }

    private void dataChanged(IMStruct002 iMStruct002) {

        if (iMStruct002.getMessage().contains("Fileid")) {
            path1 = JSONUtil.parseJson(iMStruct002.getMessage()).get("Fileid").getAsString();
        } else if (iMStruct002.getMessage().contains("FileId")) {
            path1 = JSONUtil.parseJson(iMStruct002.getMessage()).get("FileId").getAsString();
        } else {
            path1 = "";
        }
        //判断是否是发送的文件,如果是,则加载本地文件路径
        if (iMStruct002.getFromUserId() == Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID))) {
            if (iMStruct002.getMessage().contains("FileLocalPath")) {
                path = JSONUtil.parseJson(iMStruct002.getMessage()).get("FileLocalPath").getAsString();
            } else if (iMStruct002.getMessage().contains("path")) {
                path = JSONUtil.parseJson(iMStruct002.getMessage()).get("path").getAsString();
            } else {
                path = "";
            }
            if (!new File(path).exists()) {
                //判断文件是否已经下载过了
                String localPath = FileUtil.filePath + path1 + "/" + getFileName(iMStruct002);
                if (new File(localPath).exists()) {
                    isLocalFile = true;

                } else {
                    isLocalFile = false;
                }
                path = CloudUtil.CLOUD_BASE_URL + "files/" + path1 + "/download";
                fileProgress.setVisibility(View.GONE);
                setFileIcon(iMStruct002);
            } else {
                path = "file://" + path;
                //之前版本IMStruct无progress,则使用以前的方法加载
                if (iMStruct002.getExtra("progress") == null) {
                    setFileIcon(iMStruct002);
                } else {
                    setFileIcon(iMStruct002);
                    if ((int) iMStruct002.getExtra("progress") == -1) {
                        fileProgress.setVisibility(View.GONE);
                    } else {
                        fileProgress.setVisibility(View.VISIBLE);
                        fileProgress.setProgress((int) iMStruct002.getExtra("progress"));
                        if ((int) iMStruct002.getExtra("progress") == 100) {
                            fileProgress.setVisibility(View.GONE);
                        }
                    }
                }
                isLocalFile = true;
            }
        } else {
            fileProgress.setVisibility(View.GONE);
            isLocalFile = false;
            tvIsDown.setVisibility(VISIBLE);
            downloadInfo = DownloadManager.DOWNLOAD_INFO_HASHMAP.get(extraMessageID);
        }
        extraMessageID = JSONUtil.parseJson(iMStruct002.getMessage()).get("extraMessageID").getAsString();
        String path;
        if (iMStruct002.getMessage().contains("Fileid")) {
            path = JSONUtil.parseJson(iMStruct002.getMessage()).get("Fileid").getAsString();
        } else if (iMStruct002.getMessage().contains("FileId")) {
            path = JSONUtil.parseJson(iMStruct002.getMessage()).get("FileId").getAsString();
        } else {
            path = "";
        }


        downloadInfo = DownloadManager.DOWNLOAD_INFO_HASHMAP.get(extraMessageID);
        desFile = new File(FileUtil.filePath + "/" + path + "/" + getFileName(iMStruct002));
        if (null != downloadInfo) {
            String messageID = downloadInfo.messageID;
            String fileEntity = (String) SPUtils.get(mContext, messageID + "", "");
            if (fileEntity == "") {
            } else {
                String[] split = fileEntity.split(",");
                downloadInfo.state = Integer.parseInt(split[4]);
            }
            //如果杀死了应用
            if ((downloadInfo.state == State.DOWNLOADING || downloadInfo.state == State.DOWNLOAD_STOP) && JSONUtil.parseJson(iMStruct002.getMessage()).get("extraDownloadSize").getAsInt() == 0) {
                ReadFileUtils.deleteFile(desFile.getAbsolutePath());
                downloadInfo.state = State.DOWNLOAD_NOT;
            }
        }

        setFileIcon(iMStruct002);
        //21
        if (fileName.length() > 21) {

        }
        fileDescribe.setText(fileName);
        fileSize.setText(getFileSize());
        if (isLocalFile) {
            if (fileProgress.getVisibility() == VISIBLE) {
                if ((int) iMStruct002.getExtra("progress") == 0) {
                    tvIsDown.setText(R.string.wechatview_processing);
                } else {
                    tvIsDown.setText(R.string.wechatview_cancle_upload);
                }
                tvIsDown.setVisibility(VISIBLE);
            } else {
                tvIsDown.setText("");
            }
        } else if (desFile.exists()) {
//            String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(desFile.getAbsolutePath());
//            String fileSize = getFileSize();
            String downloadState = FileEntity.getDownloadState(downloadInfo.messageID, mContext);
            if ("done".equals(downloadState)) {
                isDone = true;
                tvIsDown.setText(R.string.Have_downloaded);
                fileProgress.setVisibility(GONE);
            } else {
                isDone = false;
                if (downloadInfo != null) {
                    if (downloadInfo.state == State.DOWNLOAD_STOP) {
                        fileProgress.setVisibility(VISIBLE);
                        tvIsDown.setText(R.string.wechatview_time_out);
                    } else if (downloadInfo.state == State.DOWNLOADING) {
                        tvIsDown.setText(R.string.wechatview_downloading);
                        fileProgress.setVisibility(VISIBLE);
                    } else if (downloadInfo.state == State.DOWNLOAD_WAIT) {
                        fileProgress.setVisibility(GONE);
                        tvIsDown.setText(R.string.wechatview_wait);
                    } else {
                        fileProgress.setVisibility(GONE);
                        tvIsDown.setText(R.string.wechatview_again);
//                        desFile.delete();
//                        FileEntity.
                    }
                } else { //应用被杀死或者推出了ChatActivity
                    fileProgress.setVisibility(VISIBLE);
                    tvIsDown.setText(R.string.wechatview_time_out);
                }
                try {
                    fileProgress.setProgress(downloadInfo.progress);
                } catch (Exception e) {
                    fileProgress.setVisibility(GONE);
                }

            }
        } else if (null != downloadInfo && downloadInfo.state == State.DOWNLOAD_WAIT) {
            fileProgress.setVisibility(GONE);
            tvIsDown.setText(R.string.wechatview_wait);
        } else {
            fileProgress.setVisibility(GONE);
            tvIsDown.setText(R.string.Did_not_download);
        }
//        init(downloadInfo);
    }

    private String getFileSize() {
        String fileSize;
        String message = iMStruct002.getMessage();
        JSONObject jsonObject = JSONObject.fromObject(message);
        fileSize = "" + jsonObject.get("FileSize");
        if (fileSize.equals("null")) {
            return "0.00B";
        }
        return fileSize;
    }

    /**
     * 从文件消息中获取文件名
     *
     * @param imStruct002
     * @return
     */
    public static String getFileName(IMStruct002 imStruct002) {
        String fileName;
        try {
            fileName = JSONUtil.parseJson(imStruct002.getMessage()).get("FileName").getAsString();
        } catch (Exception e) {
            fileName = "";
        }
        return fileName;
    }

    public void init(DownloadInfo downloadInfo) {
        // 检查是否存在下载记录
        String messageID = downloadInfo.messageID;
        String fileEntity = (String) SPUtils.get(mContext, messageID + "", "");
        if (fileEntity == "") {

        } else {
            String[] split = fileEntity.split(",");
            downloadInfo.state = Integer.parseInt(split[4]);
            downloadInfo.downloadSize = Long.parseLong(split[3]);
        }
        if (downloadInfo.state == State.DOWNLOADING) {
            boolean delete = desFile.delete();
//            Toast.makeText(mContext, delete+"", Toast.LENGTH_SHORT).show();
            downloadInfo.state = State.DOWNLOAD_ERROR;
        }
        // 依据状态设置按钮显示
        changeUI(downloadInfo);
    }

    private void changeUI(DownloadInfo downLoadInfo) {
        isdownLoading = true;
        fileProgress.setVisibility(View.VISIBLE);
        String text = "";
        long downloadSize = 0;
        switch (downLoadInfo.state) {
            case State.DOWNLOAD_COMPLETED:
                // 已经下载完成
                downloadSize = downLoadInfo.size;
                text = ResStringUtil.getString(R.string.Have_downloaded);
                isDone = true;
                fileProgress.setVisibility(View.GONE);
                tvIsDown.setVisibility(VISIBLE);
                Toast.makeText(mContext, ResStringUtil.getString(R.string.wechatview_file_save_in) + desFile.getAbsolutePath() + ResStringUtil.getString(R.string.wechatview_addr_down), Toast.LENGTH_LONG).show();
                break;
            case State.DOWNLOAD_NOT:
                // 未添加到队列中
                downloadSize = 0;
                text = ResStringUtil.getString(R.string.wechatview_down);
                break;
            case State.DOWNLOAD_WAIT:
                // 线程池已满
                downloadSize = downLoadInfo.downloadSize;
                text = ResStringUtil.getString(R.string.wechatview_wait);
                break;
            case State.DOWNLOAD_ERROR:
                // 出错，重试
                downloadSize = downLoadInfo.downloadSize;
                text = ResStringUtil.getString(R.string.wechatview_again);
                break;
            case State.DOWNLOADING:
                // 下载中
                downloadSize = downLoadInfo.downloadSize;
                text = ResStringUtil.getString(R.string.wechatview_downloading);
                break;
            case State.DOWNLOAD_STOP:
                // 暂停
                downloadSize = downLoadInfo.downloadSize;
                text = ResStringUtil.getString(R.string.wechatview_carry_on);
                break;
        }
        if (downLoadInfo.size == 0) {
            fileProgress.setProgress(0);
        } else {
            fileProgress.setProgress((int) (downloadSize * 100 / downLoadInfo.size));
        }
        if (!TextUtils.isEmpty(text)) {
            tvIsDown.setText(text);
        }
    }

    @Override
    public View messageView() {
        return this;
    }

    @Override
    public ViewSize messageViewSize() {
        return null;
    }

    @Override
    public boolean getIsInUse() {
        return this.isShown();
    }

    @Override
    public void setIsInUse(boolean isInUse) {
        this.isInUse = isInUse;
    }

    @Override
    public void prepareForReuse() {
        fileProgress.setVisibility(View.GONE);
        filePicture.setImageResource(R.drawable.loading_image_background);
    }

    private void setFileIcon(IMStruct002 iMStruct002) {
        fileName = getFileName(iMStruct002);

        if (null != fileName && fileName.contains(".")) {
            if (null != fileName && fileName.contains(".")) {
                fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            } else {
                fileType = "";
            }
            switch (fileType) {
                case "apk":
                    filePicture.setImageResource(R.drawable.apk);
                    break;
                case "pdf":
                    filePicture.setImageResource(R.drawable.pdf);
                    break;
                case "exe":
                    filePicture.setImageResource(R.drawable.exe);
                    break;
                case "txt":
                    filePicture.setImageResource(R.drawable.txt);
                    break;
                case "html":
                    filePicture.setImageResource(R.drawable.html);
                    break;
                case "xml":
                    filePicture.setImageResource(R.drawable.xml);
                    break;
                case "rar":
                case "zip":
                case "7-zip":
                    filePicture.setImageResource(R.drawable.rar);
                    break;
                case "doc":
                case "docx":
                case "dot":
                case "dotx":
                case "docm":
                case "dotm":
                    filePicture.setImageResource(R.drawable.word);
                    break;
                case "xls":
                case "xlsx":
                case "xlsb":
                case "xlsm":
                case "xlst":
                    filePicture.setImageResource(R.drawable.excel);
                    break;
                case "ppt":
                case "pot":
                case "pps":
                case "pptx":
                case "potm":
                case "potx":
                case "pptm":
                case "ppsx":
                case "ppsm":
                    filePicture.setImageResource(R.drawable.ppt);
                    break;
                case "m4a":
                case "cd":
                case "ogg":
                case "mp3":
                case "asf":
                case "wma":
                case "wav":
                case "mp3pro":
                case "rm":
                case "real":
                case "ape":
                case "module":
                case "midi":
                case "mid":
                case "vqf":
                case "xmf":
                    filePicture.setImageResource(R.drawable.audio);
                    break;
                case "avi":
                case "wmv":
                case "rmvb":
                case "flash":
                case "mp4":
                case "3gp":
                case "mpeg":
                case "mpg":
                case "dat":
                    isVideo = true;
                    filePicture.setImageResource(R.drawable.video);
                    break;
                case "png":
                case "bmp":
                case "gif":
                case "jpeg":
                case "jpg":
                case "swf":
                case "webp":
                    filePicture.setImageResource(R.drawable.picture);
                    break;
                default:
                    filePicture.setImageResource(R.drawable.unknow);
            }
        } else {
            //未知文件
            filePicture.setImageResource(R.drawable.unknow);
        }
    }
}
