package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.common.ConfigUtils;
import com.lightinit.hsdataplatform.common.GuidGenerator;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;
import com.lightinit.hsdataplatform.dictionary.DicDataPublishState;
import com.lightinit.hsdataplatform.dictionary.DicResourceOpenType;
import com.lightinit.hsdataplatform.dictionary.DicResourceShareType;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IDataPublishMgrService;
import com.lightinit.hsdataplatform.service.admin.IResourceDataRegisterService;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @Author: sunxiang
 * @Date: 2018/6/3 11:07
 * @Description:数据发布管理controller
 **/
@Controller
@RequestMapping(value="/admin/datapublish_mgr/")
public class DataPublishMgrController extends BaseController{

    @Autowired
    private IResourceDataRegisterService resourceDataRegisterService;
    @Autowired
    private IDataPublishMgrService dataPublishMgrService;
    /*
    *@Description 首页
    *@Param
    *@Date 2018/6/20
    *@return
    **/
    @RequestMapping(value="index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/datapublish_mgr/index");
        modelAndView.addObject("dicDataPublishState",DicDataPublishState.getInstance().getDicMap());
        return modelAndView;
    }

    /*
    *@Description 列出已发布的数据项列表
    *@Param
    *@Date 2018/6/4
    *@return
    **/
    @RequestMapping(value = "list.htm")
    public ModelAndView list(DataPublishSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo, HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setUserId(loginUser.getId());
        ModelAndView modelAndView = new ModelAndView("admin/datapublish_mgr/list");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        if(DicDataPublishState.PUBLISHED.equals(inputModel.getDicDataPublishState())){
            inputModel.setDicDataPublishState(DicDataPublishState.PUBLISHED);
        }
        List<DataPublishListModel> outputStream = dataPublishMgrService.queryList(inputModel);
        pager.setTotal(dataPublishMgrService.queryListCount(inputModel));
        modelAndView.addObject("pager",pager);
        modelAndView.addObject("list",outputStream);
        return modelAndView;
    }

    /*
    *@Description 具体发布项的详细情况
    *@Param
    *@Date 2018/6/20
    *@return
    **/
    @RequestMapping(value = "detail.htm/{id}")
    public ModelAndView detail(@PathVariable Long id){
        ModelAndView modelAndView = new ModelAndView("admin/datapublish_mgr/detail");
        DataPublishDetailModel busiModel = dataPublishMgrService.queryPublishInfoOne(id);
        if (busiModel != null){
            //获取文件名
            busiModel.setDataFile(StringUtils.substringAfterLast(busiModel.getDataFile(),File.separator));
            busiModel.setDemoFile(StringUtils.substringAfterLast(busiModel.getDemoFile(),File.separator));
            modelAndView.addObject("busiModel", busiModel);
            //取出图片映射路径
            String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
            busiModel.setResourceImg(imageContextPath+busiModel.getResourceImg());
            modelAndView.addObject("resourceImgName", StringUtils.isNotEmpty(busiModel.getResourceImg()) ? UploadFileUtils.getFileNameByPath(busiModel.getResourceImg()) : null);
        }
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value="edit.htm/{id}")
    public ModelAndView eidtPublishDataDetail(@PathVariable Long id ){
        ModelAndView modelAndView = new ModelAndView("admin/datapublish_mgr/edit");
        DataPublishDetailModel busiModel = dataPublishMgrService.queryPublishInfoOne(id);
        if (busiModel != null){
            //获取文件名
            busiModel.setDataFile(StringUtils.substringAfterLast(busiModel.getDataFile(),File.separator));
            busiModel.setDemoFile(StringUtils.substringAfterLast(busiModel.getDemoFile(),File.separator));
            modelAndView.addObject("busiModel", busiModel);
            modelAndView.addObject("resourceImgName", StringUtils.isNotEmpty(busiModel.getResourceImg()) ? UploadFileUtils.getFileNameByPath(busiModel.getResourceImg()) : null);
        }
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value="edit.action")
    @ResponseBody
    public ResultState eidtPublishDataDetail(DataPublishDetailModel inputModel, BindingResult bindingResult, MultipartFile resourceImgEdit ){
        // 保存文件
        String uniqueDir=null;
        if (StringUtils.isNotEmpty(inputModel.getResourceImg())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, inputModel.getResourceImg(), 2);
        }else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.DATA_PUBLISH_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.DATA_PUBLISH_RESOURCE_IMG_DIR);
        if (resourceImgEdit != null && !resourceImgEdit.isEmpty()){
            if (UploadFileUtils.writeUploadFile(resourceImgEdit, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setResourceImg(dataFileDir + resourceImgEdit.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }
        ResultState resultState= dataPublishMgrService.updatePublishDataDetial(inputModel);
        return resultState;
    }

    @RequestMapping(value = "delete.action/{id}")
    @ResponseBody
    public ResultState delete(@PathVariable long id) {
        ResultState<Long> resultState = dataPublishMgrService.delete(id);
        return resultState;
    }


    @RequestMapping("publishResourceIndex.htm")
    public String publishResourceIndex(){
        return "redirect:/pages/admin/datapublish_mgr/publishResourceIndex.jsp";
    }


    @RequestMapping("publishResourceList.htm")
    public ModelAndView publishResourceList(DataPublishSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setUserId(loginUser.getId());
        ModelAndView modelAndView = new ModelAndView("admin/datapublish_mgr/publishResourceList");
        BaseExample.Page pager = new BaseExample.Page(pageNo,10);
        inputModel.setPage(pager);
        List<DataPublishListModel> outputStream = dataPublishMgrService.queryPublishResourceDataList(inputModel);
        pager.setTotal(dataPublishMgrService.queryCount(inputModel));
        modelAndView.addObject("pager",pager);
        modelAndView.addObject("publishResourceDataList",outputStream);
        return modelAndView;
    }

    @RequestMapping(value="publishResourcePublic.htm/{id}")
    public ModelAndView publishResourcePublic(@PathVariable Long id ){
        ModelAndView modelAndView = new ModelAndView("admin/datapublish_mgr/publishResourcePublic");
        ResourceDataRegisterDataModel resourceDataRegisterDataModel = resourceDataRegisterService.queryOne(id);
        //取出数据文件和示例文件的文件名
        resourceDataRegisterDataModel.setDataFile(StringUtils.substringAfterLast(resourceDataRegisterDataModel.getDataFile(),File.separator));
        resourceDataRegisterDataModel.setDemoFile(StringUtils.substringAfterLast(resourceDataRegisterDataModel.getDemoFile(),File.separator));
        modelAndView.addObject("busiModel",resourceDataRegisterDataModel);
        return modelAndView;
    }

    @RequestMapping(value="publishResourcePublic.action")
    @ResponseBody
    public ResultState publishResourcePublicDo(@Valid DataPublishDetailModel inputModel, BindingResult bindingResult, MultipartFile ResourcePicture){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        // 保存文件
        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.DATA_PUBLISH_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.DATA_PUBLISH_RESOURCE_IMG_DIR);
        if (ResourcePicture != null && !ResourcePicture.isEmpty()){
            if (UploadFileUtils.writeUploadFile(ResourcePicture, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setResourceImg(dataFileDir + ResourcePicture.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }
        ResultState<Long> resultState=dataPublishMgrService.publishResourceDetailAdd(inputModel);
        return resultState;
    }

    @RequestMapping(value="publishResourceDetail.htm/{id}")
    public ModelAndView publishResourceDetail(@PathVariable Long id ){
        ModelAndView modelAndView = new ModelAndView("admin/datapublish_mgr/publishResourceDetail");
        ResourceDataRegisterDataModel resourceDataRegisterDataModel = resourceDataRegisterService.queryOne(id);
        //取出数据文件和示例文件的文件名
        resourceDataRegisterDataModel.setDataFile(StringUtils.substringAfterLast(resourceDataRegisterDataModel.getDataFile(),File.separator));
        resourceDataRegisterDataModel.setDemoFile(StringUtils.substringAfterLast(resourceDataRegisterDataModel.getDemoFile(),File.separator));
        modelAndView.addObject("busiModel",resourceDataRegisterDataModel);
        return modelAndView;
    }


    /*
    *@Description 商品下架
    *@Param
    *@Date 2018/6/7
    *@return
    **/
    @RequestMapping(value="offPublishData.action")
    @ResponseBody
    public ResultState<Long> offPublishData(Long id){
        ResultState resultState=dataPublishMgrService.offPublishData(id);
        return resultState;
    }
}
