package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.entity.DataCatelog;
import com.lightinit.hsdataplatform.entity.DataCatelogItem;
import com.lightinit.hsdataplatform.entity.DataCatelogWithBLOBs;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IDataCatelogService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: sunxiang
 * @Date: 2018/5/29 16:12
 * @Description: 数据目录管理
 **/
@RequestMapping("/admin/datacatelog_mgr")
@Controller
public class DataCatelogMgrController extends BaseController{

    @Autowired
    private IDataCatelogService dataCatelogService;
    @RequestMapping(value="index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/datacatelog_mgr/index");
        modelAndView.addObject("dicResourceOpenType",DicResourceOpenType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceShareType",DicResourceShareType.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value="list.action")
    public ModelAndView list(DataCatelogSearchModel inputModel, @RequestParam(defaultValue = "1")int pageNo){
        ModelAndView modelAndView = new ModelAndView("admin/datacatelog_mgr/list");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        List<DataCatelogListModel> OutputStream=dataCatelogService.getDataCatelogList(inputModel);
        pager.setTotal(dataCatelogService.getDataCatelogListCount(inputModel));
        modelAndView.addObject("list", OutputStream);
        modelAndView.addObject("pager",pager);
        return modelAndView;
    }
    /*
    *@Description  新增数据目录
    *@Param
    *@Date 2018/5/31
    *@return 转发到新增数据目录页面
    **/
    @RequestMapping(value="addDataCatelog.htm")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("forward:/pages/admin/datacatelog_mgr/addDataCatelog.jsp");
        //根据字典表的字段，从数据库中查找对应的id值
        List<InfomationResourceIdAndNameModel> InfomationResourceIdAndNameModels=dataCatelogService.queryInformationResourceTypeByDicMap(DicInformationResourceType.getInstance().getDicMap());
        modelAndView.addObject("InfomationResourceIdAndNameModels",InfomationResourceIdAndNameModels);
        modelAndView.addObject("dicUpdateCycle", DicUpdateCycle.getInstance().getDicMap().clone());
        return modelAndView;
    }

    /*
    *@Description  新增数据目录单项详细情况页面
    *@Param
    *@Date 2018/5/31
    *@return
    **/
    @RequestMapping(value="addDataCatelogItem.htm")
    public ModelAndView addDataCatelogItem(){
        ModelAndView modelAndView = new ModelAndView("admin/datacatelog_mgr/addDataCatelogItem");
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        modelAndView.addObject("dicDataCatelogItemType", DicDataCatelogItemType.getInstance().getDicMap().clone());
        return modelAndView;
    }
    
    /*
    *@Description  新增数据目录动作
    *@Param
    *@Date 2018/5/30
    *@return 在页面判断是否成功添加
    **/
    @RequestMapping(value="addDataCatalog.action")
    @ResponseBody
    public ResultState  addDataCatalog(HttpSession session, @Valid DataCatelogAddModel dataCatelogAddModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(dataCatelogAddModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        dataCatelogAddModel.setCreatedBy(loginUser.getId());
        ResultState<Long> resultState = dataCatelogService.addDataCatalog(dataCatelogAddModel);
        return resultState;
    }

    /*
    *@Description 删除选择项
    *@Param
    *@Date 2018/5/31
    *@return
    **/
    @RequestMapping(value = "delete.action/{id}")
    @ResponseBody
    public ResultState<Long> delete(@PathVariable Long id){
        return dataCatelogService.delete(id);
    }

    @RequestMapping(value="edit.htm/{id}")
    public ModelAndView edit(@PathVariable Long id ){
        ModelAndView modelAndView = new ModelAndView("forward:/pages/admin/datacatelog_mgr/edit.jsp");
        DataCatelogAddModel dataCatelogAddModel = dataCatelogService.queryOne(id);
        //根据字典表的字段，从数据库中查找对应的id值
        List<InfomationResourceIdAndNameModel> InfomationResourceIdAndNameModels=dataCatelogService.queryInformationResourceTypeByDicMap(DicInformationResourceType.getInstance().getDicMap());
        //查找"信息资源格式分类"下的对应"信息资源格式类型"
       /* List<InfomationResourceIdAndNameModel> list=null;
        for (InfomationResourceIdAndNameModel infomationResourceIdAndNameModel : InfomationResourceIdAndNameModels) {
            if(infomationResourceIdAndNameModel.getGroupName().equals(dataCatelogAddModel.getDataSourceType())){
                list = queryInfoStyle(infomationResourceIdAndNameModel.getId());
            }
        }*/
        modelAndView.addObject("InfomationResourceIdAndNameModels",InfomationResourceIdAndNameModels);
        if(StringUtils.isNotEmpty(dataCatelogAddModel.getDataSourceType())) {
            modelAndView.addObject("list", queryInfoStyle(Long.parseLong(dataCatelogAddModel.getDataSourceType())));
        }
//        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
//        modelAndView.addObject("dicDataCatelogItemType", DicDataCatelogItemType.getInstance().getDicMap().clone());
//        modelAndView.addObject("dicDataSharePatternType", DicDataSharePatternType.getInstacne().getDicMap().clone());
        modelAndView.addObject("dicUpdateCycle", DicUpdateCycle.getInstance().getDicMap().clone());
        modelAndView.addObject("busiModel",dataCatelogAddModel);
        return modelAndView;
    }

    @RequestMapping(value="detail.htm/{id}")
    public ModelAndView detail(@PathVariable Long id ){
        ModelAndView modelAndView = new ModelAndView("forward:/pages/admin/datacatelog_mgr/detail.jsp");
        DataCatelogAddModel dataCatelogAddModel = dataCatelogService.queryOne(id);
        List<InfomationResourceIdAndNameModel> InfomationResourceIdAndNameModels=dataCatelogService.queryInformationResourceTypeByDicMap(DicInformationResourceType.getInstance().getDicMap());
        modelAndView.addObject("InfomationResourceIdAndNameModels",InfomationResourceIdAndNameModels);
        if(StringUtils.isNotEmpty(dataCatelogAddModel.getDataSourceType())){
            modelAndView.addObject("list",queryInfoStyle(Long.parseLong(dataCatelogAddModel.getDataSourceType())));
        }
        modelAndView.addObject("dicUpdateCycle", DicUpdateCycle.getInstance().getDicMap().clone());
        modelAndView.addObject("busiModel",dataCatelogAddModel);
        return modelAndView;
    }

    @RequestMapping(value="updateDataCatalog.action")
    @ResponseBody
    public ResultState updateDataCatalog(@Valid DataCatelogAddModel inputModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        ResultState<Long> resultState=dataCatelogService.updateDataCatalog(inputModel);
        return resultState;
    }

    /*
    *@Description 在点击修改页面时，dataCatelogItem修改操作。只作为将数据在页面显示，不走后台。
    *@Param
    *@Date 2018/6/1
    *@return
    **/
    @RequestMapping(value = "dataCatelogItemEdit.htm",method=RequestMethod.POST)
    public ModelAndView dataCatelogItemEdit(@RequestBody DataCatelogItem dataCatelogItem){
        ModelAndView modelAndView = new ModelAndView("admin/datacatelog_mgr/addDataCatelogItem");
        modelAndView.addObject("busiModel",dataCatelogItem);
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        modelAndView.addObject("dicDataCatelogItemType", DicDataCatelogItemType.getInstance().getDicMap().clone());
        modelAndView.addObject("dicDataSharePatternType", DicDataSharePatternType.getInstacne().getDicMap().clone());
        return modelAndView;
    }

    /*
    *@Description 查找信息资源格式类型
    *@Param
    *@Date 2018/6/8
    *@return
    **/
    @RequestMapping(value="queryInfoStyle.action")
    @ResponseBody
    public List<InfomationResourceIdAndNameModel> queryInfoStyle(Long id){
        List<InfomationResourceIdAndNameModel> list=dataCatelogService.queryInfoStyle(id);
        return list;
    }



    ////////////////////////////新增视图效果
    @RequestMapping(value="imageIndex.htm")
    public String imageIndex() {
        return "admin/datacatelog_view/imageView";
    }

    @RequestMapping(value="allDataToView.action")
    @ResponseBody
    public ResultState getAllDataToView() {
          return dataCatelogService.getAllDataToView();
    }

    @RequestMapping(value="detailView.htm")
    public ModelAndView  getTheme(String theme) {
        ModelAndView modelAndView = new ModelAndView("admin/datacatelog_view/detailView");
        modelAndView.addObject("theme",theme);
        return modelAndView;
    }

    @RequestMapping(value="getDataById.action")
    @ResponseBody
    public ResultState getDataById(Long id) {
          return dataCatelogService.getDataById(id);
    }

    @RequestMapping(value="getlist.action")
    public ModelAndView getlist(DataCatelogSearchModel inputModel, @RequestParam(defaultValue = "1")int pageNo){
        ModelAndView modelAndView = new ModelAndView("admin/datacatelog_view/list");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        List<DataCatelogListModel> OutputStream=dataCatelogService.getDataCatelogList(inputModel);
        pager.setTotal(dataCatelogService.getDataCatelogListCount(inputModel));
        modelAndView.addObject("list", OutputStream);
        modelAndView.addObject("pager",pager);
        return modelAndView;
    }


   @RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
   @ResponseBody
   public ResultState uploadExcel(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
       InputStream inputStream = file.getInputStream();
        BufferedInputStream br=new BufferedInputStream(inputStream);
        XSSFWorkbook workbook = new XSSFWorkbook(br);
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        return dataCatelogService.parseExcel(sheetAt);
    }


}
