package com.lightinit.hsdataportal.controller.share;

import com.lightinit.hsdataportal.common.ConfigUtils;
import com.lightinit.hsdataportal.common.SysContants;
import com.lightinit.hsdataportal.dictionary.*;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IDataService;
import com.lightinit.hsdataportal.service.IMyDataService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;


/**
 * @Author: sunxiang
 * @Date: 2018/6/15 9:58
 * @Description:
 **/
@Controller
@RequestMapping(value = "/share/mydata")
public class MyDataShareController {

    @Autowired
    private IMyDataService myDataService;
    @Autowired
    private IDataService dataService;
    /*
    *@Description 我的数据-共享平台页面
    *@Param 
    *@Date 2018/6/15
    *@return 
    **/
    @RequiresAuthentication
    @RequestMapping(value="index.htm/{tab}")/*分页待加入*/
    public ModelAndView getIndex(@PathVariable Integer tab,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ModelAndView modelAndView = new ModelAndView("share/my_data/index");
        List<MyDataShareListModel> list=myDataService.getIndex(null,loginUser.getId(), DicPlatformType.SHARE);/*loginUser.getId()*/
        modelAndView.addObject("outputModel",list);
        modelAndView.addObject("tab",tab);

        /*待分离的“关注的数据”*/
        List<FollowDataListModel> followDataList=myDataService.getFollowDateList(loginUser.getId(),DicPlatformType.SHARE);/*loginUser.getId()*/
        modelAndView.addObject("followDataList",followDataList);
        /**/
        return modelAndView;
    }

    /*
    *@Description 下载
    *@Param
    *@Date 2018/6/15
    *@return
    **/
    @RequiresAuthentication
    @RequestMapping(value="download.action/{id}")
    public String  download(@PathVariable Long id, HttpSession session, HttpServletRequest req, HttpServletResponse resp){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        MyDataShareListModel myDataShareListModel=myDataService.selectResourceAuth(loginUser.getId(),id,DicPlatformType.SHARE);/*开放验证后*/
        ResultState resultState = new ResultState();
        if(myDataShareListModel==null){
            //申请页面
            return "redirect:/open/data/detail.htm/"+id;
        }else if(DicOrderState.PAY_SUCCESS.equals(myDataShareListModel.getOrderState())){
        BufferedInputStream bis = null;
        try {
            String demoFile = myDataShareListModel.getDataFile();//数据文件下载
            String filename = StringUtils.substringAfterLast(demoFile, File.separator);
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
            String urlPath= ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.UPLOAD_FILE_ROOT_DIR);
            File file =new File(urlPath+demoFile);
            resp.reset();
            resp.setContentType("application/octet-stream");
            resp.setCharacterEncoding("utf-8");
            resp.setContentLength((int) file.length());
            resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
            byte[] buff = new byte[1024];
            OutputStream os = null;
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
            return null;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //req.setAttribute("paramType","4");//下载失败,未完成
            return "forward:/open/mydata/index.htm/1";
       }else{
            return "redirect:/open/mydata/index.htm/1";
        }
    }

    /*
    *@Description “授权成功”后申请
    *@Param
    *@Date 2018/6/15
    *@return
    **/
    /*@RequestMapping(value="apply.action/{id}")
    @ResponseBody
    public ResultState  apply(@PathVariable Long id, HttpSession session){
        *//*LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
         inputModel.setApplier(loginUser.getId());     开放验证后，待打开*//*
        MyDataShareListModel myDataShareListModel=myDataService.selectResourceAuth(2l,id,DicPlatformType.SHARE);
        ResultState resultState = new ResultState();
        if(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS.equals(myDataShareListModel.getAuthState())){
            resultState=dataService.insertDataApply(myDataShareListModel,DicPublishSettingChargeMethod.FREE,1);
        }
        return resultState;
    }*/

    @RequiresAuthentication
    @RequestMapping(value="follow.htm")
    @ResponseBody
    public List<MyDataShareListModel>  getFollowIndex(HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
       // List<MyDataShareListModel> list=myDataService.getIndex(loginUser.getId(), DicPlatformType.SHARE);
        //return list;
        return null;
    }

    /*
     *@Description 取消关注
     *@Param
     *@Date 2018/6/25
     *@return
     **/
    @RequiresAuthentication
    @RequestMapping(value="delFollow.action/{tabNum}/{id}")
    public String delFollow(@PathVariable Integer tabNum ,@PathVariable Long id,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResultState  resultState = dataService.delfollow(id, loginUser.getId());
        return "redirect:/open/mydata/index.htm/2";//2:tab,表示页面显示“关注的数据”
    }
}
