package edu.neusoft.project.controller;

import com.aliyun.oss.OSSClient;
import edu.neusoft.project.model.service.IndentService;
import edu.neusoft.project.model.service.PersonService;
import edu.neusoft.project.model.service.SongService;
import edu.neusoft.project.model.vo.Person;
import edu.neusoft.project.model.vo.Song;
import edu.neusoft.project.util.OSSCtrl.OssPostObject;
import edu.neusoft.project.util.Thread.GetMusicFromNeteaseThreadAndIns;
import edu.neusoft.project.util.Thread.OssBasicUploadThread;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
//@RequestMapping(path = "/song")
public class ControlBasicAction {
    @Autowired
    private PersonService service;
    @Autowired
    private SongService songService;
    @Autowired
    private IndentService indentService;

    @ResponseBody
    @RequestMapping("addFromNetease.action")
    public int addSong(String id){
        int ret=0;
        try {
            int intid=Integer.parseInt(id);
            GetMusicFromNeteaseThreadAndIns ins=new GetMusicFromNeteaseThreadAndIns(intid);
            ret = ins.call();
            System.out.println(ret);
        } catch (NumberFormatException e) { //NumberFormatException ;
            ret = 5;
        }catch (Exception e){
            ret=0;
        }


        System.out.println("FromNetease:"+id);
        return ret;
    }


    @RequestMapping("/song/{idStr}.m")
    public String shared(@PathVariable String idStr, ModelMap model,HttpServletRequest request){
        System.out.println("url访问:id--"+idStr);
        HttpSession sessions = request.getSession();
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
//        System.out.println(searchText+"0000000000000000");
        if (idStr.equals("")||idStr==null){
            if (loginedPer!=null){
                String level = service.getLevel(loginedPer);
                List<Song> list04 = songService.likeSongs();
                model.put("list",list04);
                model.put("username",loginedPer.getUsername());
                model.put("password",loginedPer.getPassword());
                model.put("personCode",loginedPer.getPersonCode());
                model.put("noSharp",loginedPer.getPersonCode().substring(1));
                model.put("personLevel",level);
                model.put("personListened",loginedPer.getPersonListened());
                System.out.println();

                return "logined";
            }
            return "Homepage";
        }
        Song song;
        song = songService.selectByIdPrecise(idStr);
//        if (song==null){
//            return "error";
//        }
        System.out.println("idStr:"+idStr);
        System.out.println(song);
        //likes
        List<Song> list = songService.likeSongs();
        //putModel
        if (song!=null){
            model.put("searchedSong", song);
        }else {
            model.put("searchedSong", "");
            model.put("searchedSongid","");
        }
        model.put("list",list);
        if(loginedPer!=null){
            String level = service.getLevel(loginedPer);
            songService.addListened(loginedPer);
            model.put("username",loginedPer.getUsername());
            model.put("password",loginedPer.getPassword());
            model.put("personCode",loginedPer.getPersonCode());
            model.put("noSharp",loginedPer.getPersonCode().substring(1));
            model.put("personLevel",level);
            model.put("personListened",loginedPer.getPersonListened());
            System.out.println("loginedPer---------"+loginedPer);
            if (song==null){
                return "error";
            }
            return "logined";
        }
        if (song==null){
            return "ErrorUnLogined";
        }
        return "searchedButNotLogined";
    }

    @RequestMapping("/uploadTeatPage.action")
    public String test(){
        return "ossuploadtest";
    }

    @RequestMapping("/perPictUploadFile.action")
    public @ResponseBody int perPictUploadFile(HttpServletResponse response, HttpServletRequest request,HttpSession sessions){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        int ret = 0;
        //文件上传相关的类
        Person loginedPer= new Person();
        loginedPer= (Person) sessions.getAttribute("loginedPer");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload( factory );
        //设置文件编码
        upload.setHeaderEncoding( "UTF-8" );
        //文件列表
        List fileList = null;
        try {
            //获取文件
            fileList = upload.parseRequest( request );
            System.out.println(fileList+"**************fileList ");
//            System.out.println(fileList);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator<FileItem> iterator = fileList.iterator();
        while (iterator.hasNext()){
            FileItem item = iterator.next();
            // 判断某项是否是普通的表单类型
            if(!item.isFormField()){
                //字段名称
                String fieldName = item.getFieldName(); //文件对应字段名称，就是input中name的值
                //文件 XXX.doc
                String fileName = item.getName();
                //获取文件后缀名
                String suffix = fileName.substring( fileName.lastIndexOf( '.' ) ); //.doc

                //上传后的文件名 in OSS
                String ossFileName = loginedPer.getPersonCode();


                //获取时间戳，防止文件重复
                long id = new Date().getTime();
                //获取保存路径
                String savePath = request.getServletContext().getRealPath( "img" );
                //设置文件路径
                String fileUrl = String.format( "%s/%d%s",savePath,id,suffix);
                File file = new File( fileUrl );
                try {
                    //将文件上传到目标文件夹
                    System.out.println(file+"****************File");
                    item.write( file );
//                    System.out.println(item);
                    fileUrl=fileUrl.replaceAll("\\\\","/");
                    OssBasicUploadThread ossThread = new OssBasicUploadThread(fileUrl,ossFileName,"music-ol");
                    ret=ossThread.call();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }


        }
        return ret;



    }

}
