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.entity.BaseExample;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IDataService;
import com.lightinit.hsdataportal.service.IMyDataService;
import com.lightinit.hsdataportal.service.IResourceCatelogService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
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.RequestParam;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: sunxiang
 * @Date: 2018/6/9 16:47
 * @Description:
 **/
@Controller
@RequestMapping(value = "/share/data")
public class DataShareController {

    @Autowired
    private IDataService dataService;
    @Autowired
    private IResourceCatelogService resourceCatelogService;
    @Autowired
    private IMyDataService myDataService;
    /*
    *@Description 查询共享平台某一个数据的详细情况
    *@Param
    *@Date 2018/6/9
    *@return 
    **/
    @RequestMapping(value="detail.htm/{id}")
    public ModelAndView getDataDetail(@PathVariable Long id,HttpSession session,HttpServletRequest req,HttpServletResponse resp){
        ModelAndView modelAndView = new ModelAndView("share/data/detail");
        String paramType=(String)req.getAttribute("paramType");//是否已经申请标识符
        String toPayed=(String)req.getAttribute("toPayed");//支付标志符
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        Long userId=null;
        if(loginUser !=null){
            userId=loginUser.getId();
        }
        DataDetailModel dataDetailModel=dataService.getDataDetail(id,userId,2);//2：共享平台的标识符
        //取出图片映射路径
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        if(dataDetailModel!=null){
            dataDetailModel.setResourceImg(imageContextPath+dataDetailModel.getResourceImg());
            if(dataDetailModel.getDataFile()!=null){
                dataDetailModel.setDataFileName(StringUtils.substringAfterLast(dataDetailModel.getDataFile(),File.separator));
            }
            if(dataDetailModel.getDemoFile()!=null){
                dataDetailModel.setDemoFileName(StringUtils.substringAfterLast(dataDetailModel.getDemoFile(),File.separator));
            }
        }
        modelAndView.addObject("paramType",paramType);//是否已经申请标识符
        modelAndView.addObject("toPayed",toPayed);//支付标志符
        modelAndView.addObject("outputModel",dataDetailModel);
        return modelAndView;
    }

    /*
     *@Description 查询共享平台查看首页
     *@Param
     *@Date 2018/6/9
     *@return
     **/
    @RequestMapping(value="index.htm")
    public ModelAndView getDataIndex(DataSearchModel inputModel,@RequestParam(defaultValue = "1") int pageNo){
        ModelAndView modelAndView = new ModelAndView("share/data/index");
        inputModel.setNotShareType(DicResourceShareType.NOT_SHARE);
        inputModel.setPublishState(DicPublishApiState.PUBLISH);
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        inputModel.setSortCategory(DicSortCategory.DEFAULT_SORT);
        List<DataListModel> list=dataService.getDataIndex(inputModel, 2);//2：共享平台的标识符
        //取出图片映射路径
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        for (DataListModel dataListModel : list) {
            dataListModel.setResourceImg(imageContextPath+dataListModel.getResourceImg());
        }
        pager.setTotal(dataService.getIndexCount(inputModel,2));
        modelAndView.addObject("outputModel",list);
        modelAndView.addObject("pager",pager);
        modelAndView.addObject("searchModel", inputModel);
        modelAndView.addObject("themes",resourceCatelogService.getResourceCatelogNameByType(DicResourceCatelogType.THEME, DicResourceType.DATA,DicPlatformType.SHARE)) ;
        modelAndView.addObject("sectors",resourceCatelogService.getSectorNameList()) ;
      //   modelAndView.addObject("apiCount", apiService.queryShareCount(apiShareSearchModel)) ; 待做
        return modelAndView;
    }

    /*
     *@Description 共享数据申请，从数据库中判断是否可以立即加载/需申请
     *@Param    applyReason：申请理由
     *@Date 2018/6/10
     *@return  无条件：直接下载；有条件：需申请
     **/
    @RequiresAuthentication
    @RequestMapping(value="apply.action")
    @ResponseBody
    public ResultState<Long>  getDataShareType(MyDataShareListModel inputModel, HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        //判断是否已经申请过
        Long resourceAuthId= myDataService.getResourceAuthId(inputModel.getPublishSettingId(),loginUser.getId(), DicPlatformType.SHARE);
        if(resourceAuthId !=null){
            ResultState resultState = new ResultState();
            resultState.setMsg("已经申请过了，请前往用户中心下载");
            return resultState;
        }

        DataApplyPriceModel dataApplyPriceModel=dataService.getDateShareType(inputModel.getPublishSettingId());
        if(dataApplyPriceModel !=null){
            BeanUtils.copyProperties(dataApplyPriceModel,inputModel);
            inputModel.setPlatformType(DicPlatformType.SHARE);
            inputModel.setUserORAdminId(loginUser.getId());/*loginUser.getId()*/
        }
        ResultState<Long> resultState=new ResultState<>();
        if(DicResourceShareType.UNCONDITIONAL.equals(dataApplyPriceModel ==null?null:dataApplyPriceModel.getShareType())){
            resultState=dataService.insertDataApply(inputModel,null,1);//1：直接下载
        } else if(DicResourceShareType.CONDITIONAL.equals(dataApplyPriceModel ==null?null:dataApplyPriceModel.getShareType())){
            resultState=dataService.insertDataApply(inputModel,null,2);//2：申请
        }else{
            resultState.setMsg("操作失败");
        }
        return resultState;
    }


    /*
     *@Description 关注
     *@Param
     *@Date 2018/6/14
     *@return
     **/
    @RequiresAuthentication
    @RequestMapping(value="follow.action/{id}")
    @ResponseBody
    public ResultState<Long> follow(@PathVariable Long id,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        return dataService.follow(DicPlatformType.SHARE,id,loginUser.getId());/*loginUser.getId() 修改*/
    }

    /**
     *取消关注
     * 关注表id
     * @param
     * @param id
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "delfollow.action/{id}")
    @ResponseBody
    public ResultState delfollow(@PathVariable long id,HttpSession session) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResultState  resultState = dataService.delfollow(id,loginUser.getId());
        return resultState;
    }

    /*
     *@Description 数据视图
     *@Param
     *@Date 2018/7/1
     *@return
     **/
    @RequestMapping(value="dataview.htm")
    public ModelAndView  getDateView(@RequestParam(defaultValue = "1") int pageNo){
        ModelAndView modelAndView = new ModelAndView("share/data/view");
        List<DataViewListModel> dataViewList=dataService.getDataViewList(DicPlatformType.SHARE);
        List<DataStructListModel> dataStructModel=dataService.getDataStructreList(DicPlatformType.SHARE);
        //取出图片映射路径
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        for (DataViewListModel dataListModel : dataViewList) {
            dataListModel.setCatelogImg(imageContextPath+dataListModel.getCatelogImg());
        }
        Long sectorTotal=dataService.getSectorTotal(DicPlatformType.SHARE);
        Long sectorDataTotal=dataService.getSectorDataTotal(DicPlatformType.SHARE);
        modelAndView.addObject("dataViewList",dataViewList);//结构视图
        modelAndView.addObject("dataStructModel",dataStructModel);//结构视图
        modelAndView.addObject("sectorTotal",sectorTotal);//部门总数
        modelAndView.addObject("sectorDataTotal",sectorDataTotal);//所有部门的数据总数
        return modelAndView;
    }

    /*
     *@Description 文件下载
     *@Param Id:publishSettingId     type:示例/数据类型
     *@Date 2018/7/9
     *@return
     **/
    @RequiresAuthentication
    @RequestMapping(value="download.action/{type}/{id}")
    public String  download(@PathVariable int type, @PathVariable Long id, HttpSession session, HttpServletRequest req, HttpServletResponse resp) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        Long resourceAuthId= myDataService.getResourceAuthId(id,loginUser.getId(), DicPlatformType.SHARE);
        if(resourceAuthId ==null){
            //申请页面
            req.setAttribute("paramType","1");//未申请标识符
            return "forward:/share/data/detail.htm/"+id;
        }
        MyDataShareListModel myDataShareListModel = myDataService.selectResourceAuth(loginUser.getId(), resourceAuthId, DicPlatformType.SHARE);
        if(myDataShareListModel ==null){
            //申请页面
            req.setAttribute("paramType","1");//未申请标识符
            return "forward:/share/data/detail.htm/"+id;
        }else if(DicOrderState.PAY_SUCCESS.equals(myDataShareListModel.getOrderState())){
            BufferedInputStream bis = null;
            try {
                String demoFile="";
                if (type == 1) {
                    demoFile =  myDataShareListModel.getDemoFile();//示例文件下载
                }
                if (type == 2) {
                    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();
                }
            }
            return "forward:/share/data/detail.htm/"+id;
        }else{
            req.setAttribute("paramType","2");//已经申请，等待审核
            return "forward:/share/data/detail.htm/"+id;
        }
    }
}
