function endecodeFileCtrl($scope, UploadFile) {
    function option(){
        this.baseUrl = `http://${window.location.host}`
        this.chunkSize = 5 * 1024 * 1024
        this.fileSize = 0
        this.file = null
        this.hasUploaded = 0
        this.chunks = 0
    }
    let opt;
    $scope.uploadFile = function(files) {
        opt = new option();
        opt.file = files[0];
        opt.fileSize = files[0].size;
        console.log(opt)
        responseChange(opt.file);
    }

    // 0.响应点击
    async function responseChange(file) {
        // 第一步：按照 修改时间+文件名称+最后修改时间-->MD5
        // 显示文件校验进度
        console.log("----1--")
        $("#process1").slideDown(200)
        // 开始校验
        let fileMd5Value = await md5File(file)
        // 第二步：校验文件的MD5
        let result = await checkFileMD5(file.name, fileMd5Value)
        // 如果文件已存在, 就秒传
        if (result.file) {
            alert('文件已秒传')
            return
        }
        // let exit = false
        // 显示文件上传进度
        $("#process2").slideDown(200)
        // 第三步：检查并上传MD5
        await checkAndUploadChunk(fileMd5Value, result.chunkList)
        // 第四步: 通知服务器所有分片已上传完成
        notifyServer(fileMd5Value)
    }

    // 1.修改时间+文件名称+最后修改时间-->MD5
    function md5File(file) {
        return new Promise((resolve, reject) => {
            var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
                currentChunk = 0,
                spark = new SparkMD5.ArrayBuffer(),
                fileReader = new FileReader();
            //chunkSize = 2097152, // Read in chunks of 2MB
            var chunkSize = file.size / 100
            //chunks = Math.ceil(file.size / chunkSize),
            var chunks = 100
            fileReader.onload = function (e) {
                console.log('read chunk nr', currentChunk + 1, 'of', chunks);
                spark.append(e.target.result); // Append array buffer
                currentChunk++;

                if (currentChunk < chunks) {
                    loadNext();
                } else {
                    let cur = +(new Date())
                    console.log('finished loading');
                    // alert(spark.end() + '---' + (cur - pre)); // Compute hash
                    let result = spark.end()
                    resolve(result)
                }
            };

            fileReader.onerror = function () {
                console.warn('oops, something went wrong.');
            };

            function loadNext() {
                var start = currentChunk * chunkSize,
                    end = ((start + opt.chunkSize) >= file.size) ? file.size : start + chunkSize;

                fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
                $("#checkProcessStyle").css({
                    width: (currentChunk + 1) + '%'
                })
                $("#checkProcessValue").html((currentChunk + 1) + '%')
                // $("#tip").html(currentChunk)
            }

            loadNext();
        })


        // let name = file.name;
        // let size = file.size;
        // let lastModified = file.lastModified;
        // return md5(name + "-" + size + "-" + lastModified);
    }
    // 2.校验文件的MD5
    function checkFileMD5(fileName, fileMd5Value) {
        return new Promise((resolve, reject) => {
            let url = opt.baseUrl + '/endecode/file/check_file?fileName=' + fileName + "&fileMd5Value=" + fileMd5Value
            $.getJSON(url, function (data) {
                resolve(data)
            })
        })
    }
    // 3.上传chunk
    async function checkAndUploadChunk(fileMd5Value, chunkList) {
        opt.chunks = Math.ceil(opt.fileSize / opt.chunkSize)
        opt.hasUploaded = chunkList.length
        for (let i = 0; i < opt.chunks; i++) {
            let exit = chunkList.indexOf(i + "") > -1
            // 如果已经存在, 则不用再上传当前块
            if (!exit) {
                let index = await upload(i, fileMd5Value, opt.chunks)
                opt.hasUploaded++
                let radio = Math.floor((opt.hasUploaded / opt.chunks) * 100)
                $("#uploadProcessStyle").css({
                    width: radio + '%'
                })
                $("#uploadProcessValue").html(radio + '%')
            }
        }
    }

    // 3-2. 上传chunk
    function upload(i, fileMd5Value, chunks) {
        return new Promise((resolve, reject) => {
            //构造一个表单，FormData是HTML5新增的
            let end = (i + 1) * opt.chunkSize >= opt.file.size ? opt.file.size : (i + 1) * opt.chunkSize
            let form = new FormData()
            form.append("data", opt.file.slice(i * opt.chunkSize, end)) //file对象的slice方法用于切出文件的一部分
            form.append("total", chunks) //总片数
            form.append("index", i) //当前是第几片     
            form.append("fileMd5Value", fileMd5Value)
            $.ajax({
                url: opt.baseUrl + "/endecode/file/upload",
                type: "POST",
                data: form, //刚刚构建的form数据对象
                async: true, //异步
                processData: false, //很重要，告诉jquery不要对form进行处理
                contentType: false, //很重要，指定为false才能形成正确的Content-Type
                success: function (data) {
                    resolve(data.desc)
                }
            })
        })

    }

    // 第四步: 通知服务器所有分片已上传完成
    function notifyServer(fileMd5Value) {
        let url = opt.baseUrl + '/endecode/file/merge?md5=' + fileMd5Value + "&fileName=" + opt.file.name + "&size=" + opt.file.size
        $.getJSON(url, function (data) {
            addLog('上传成功' + data)
        })
    }

    function addLog(log) {
        let current = $("#tip").html()
        current += getDate()
        current += '-----'
        current += log
        current += '<br/>'
        $("#tip").html(current)
    }

    function getDate() {
        let d = new Date()
        return d.getMinutes() + ':' + d.getSeconds() + ' ' + d.getMilliseconds()
    }
    function getFileList(){
        UploadFile.getFileList({},function(res){
            $scope.$emit("getFileList",res.list);
            $scope.current_file.children.length = 0;
            res.list.forEach(function(element) {
                $scope.current_file.children.push(new fide().init($scope.current_file,element,false,$scope.current_file.deep+1))
            }, this);
        })
    }
    

    var fide_id = 0;
    var fide = function () {
		this.title = "";
		this.isDir = false;
		this.isOpen = false;
		this.deep = 0;
		this.children = [];
		this.parent = null;
		this.id = fide_id++;
		return this
	}
	fide.prototype = {
		init: function (parent, title, isDir, deep) {
			this.title = title;
			this.isDir = isDir;
			this.deep = deep;
			this.parent = parent;
			return this
		},
		close: function () {
			this.isOpen = false;
			this.children.length = 0;
			return this
		},
		open: function () {
			this.isOpen = true;
			return this
		}
	}
    let root_fide = new fide().init(null, "Libs", true, 1, null);
    $scope.treeNode = [root_fide];
    $scope.current_file = $scope.treeNode[0];
    getFileList();
    let dblclick = 0;
    $scope.targetClick = function(){
        // $scope.current_fide = fide;
        // if (fide.isOpen) {
		// 	if (fide.isDir) {
		// 		fide.close();
		// 	} else {
        //         getFileList();
		// 	}
		// } else {
		// 	if (fide.isDir) {
		// 		//获取Function，templates
		// 		getFileList();
		// 		$scope.current_fide.open();
		// 	} else {
		// 		dblclick++;
		// 		if (dblclick == 1) {
		// 			//
		// 			// setEditorValue(fide)
		// 			timer = setTimeout(function () {
		// 				dblclick = 0;
		// 			}, 200);
		// 		} else {
        //             // openPage();
        //             $scope.current_fide.open();
		// 			clearTimeout(timer);
		// 		}
		// 	}
		// }
    }
    $scope.rightTargetClick = function(){

    }
    $scope.uploadButtonClick=function(){
        $('#fileUpLoadInput').click()
    }
}   
endecodeFileCtrl.$inject = ["$scope","UploadFile"];
BP.controller("endecodeFileCtrl", endecodeFileCtrl);
