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.DicNewsCategory;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.ConsultSearchModel;
import com.lightinit.hsdataplatform.model.admin.LoginUser;
import com.lightinit.hsdataplatform.model.admin.NewModel;
import com.lightinit.hsdataplatform.service.admin.IConsultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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 java.io.File;
import java.util.List;

/**
 * @Author: sunxiang
 * @Date: 2018/7/5 13:56
 * @Description:
 **/
@Controller
@RequestMapping("/admin/consult_mgr")
public class ConsultController extends BaseController{

    @Autowired
    private IConsultService consultService;
    @RequestMapping(value = "index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/consult_mgr/index");
        return modelAndView;
    }

    @RequestMapping(value = "list.action")
    public ModelAndView list(ConsultSearchModel inputModel,@RequestParam(defaultValue = "1") int pageNo){
        ModelAndView modelAndView = new ModelAndView("admin/consult_mgr/list");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        pager.setTotal(consultService.queryCount(inputModel));
        modelAndView.addObject("list", consultService.getList(inputModel));
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    @RequestMapping(value = "add.htm")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("admin/consult_mgr/add");
        modelAndView.addObject("dicNewsCategory", DicNewsCategory.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "edit.action/{id}")
    public ModelAndView edit(@PathVariable Long id){
        ModelAndView modelAndView = new ModelAndView("admin/consult_mgr/add");
        if(id !=null){
            ConsultSearchModel inputModel = new ConsultSearchModel();
            inputModel.setId(id);
            List<NewModel> list = consultService.getList(inputModel);
            if(list!=null && list.size()>0){
                NewModel newModel = list.get(0);
                //放入映射路径
                String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
                String imgTag = "<img src=\"";
                if(newModel.getNewsContent()!=null){
                 newModel.setNewsContent(newModel.getNewsContent().replaceAll(imgTag, imgTag + imageContextPath));
                }
                modelAndView.addObject("outputModel",newModel);
            }
        }
        modelAndView.addObject("dicNewsCategory", DicNewsCategory.getInstacne().getDicMap());
        return modelAndView;
    }
    /*
    *@Description 文本提交/修改：根据是否有id来区别
    *@Param
    *@Date 2018/7/6
    *@return
    **/
    @RequestMapping(value = "consult.action")
    @ResponseBody
    public ResultState consult(@Validated NewModel inputModel, BindingResult bindingResult, HttpSession session){
        if(bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel,bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setUserId(loginUser.getId());
        //得到图片保存路径开头映射头
        String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
        //将图片上传绝对路径切成相对路径
        inputModel.setNewsContent(inputModel.getNewsContent().replaceAll(imageContextPath,""));
        ResultState resultState=null;
        if(inputModel.getId()==null){
            resultState=consultService.add(inputModel);
        }else{
            resultState=consultService.update(inputModel);
        }
        return resultState;
    }


    /*
    *@Description 图片上传
    *@Param 
    *@Date 2018/7/6
    *@return 
    **/
    @RequestMapping(value = "upload.action")
    @ResponseBody
    public ResultState upload(MultipartFile file){
        // 保存图片文件
        ResultState resultState = new ResultState();
        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.CONSULT_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.CONSULT_RESOURCE_IMG_DIR);
        if (file != null && !file.isEmpty()){
            if (UploadFileUtils.writeUploadFile(file, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                resultState.setData(dataFileDir + file.getOriginalFilename());//得到图片上传路径
                //得到图片保存路径开头映射头
                String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
                resultState.setData(imageContextPath+resultState.getData());//拼接图片绝对路径
                return resultState;
            }
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg( "数据文件保存失败");
        return resultState;
    }

    /*
    *@Description 删除
    *@Param 
    *@Date 2018/7/8
    *@return 
    **/
    @RequestMapping(value = "delete.action/{id}")
    @ResponseBody
    public ResultState delete(@PathVariable Long id){
       return  consultService.delete(id);
    }

    /*
    *@Description 视频上传,暂时不做
    *@Param
    *@Date 2018/7/6
    *@return
    **/
    /*@RequestMapping(value = "uploadVideo.action")
    @ResponseBody
    public ResultState uploadVedio(MultipartFile file){
        // 保存视频文件
        ResultState resultState = new ResultState();
        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.CONSULT_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.CONSULT_RESOURCE_VIDEO_DIR);
        if (file != null && !file.isEmpty()){
            if (UploadFileUtils.writeUploadFile(file, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                resultState.setData(dataFileDir + file.getOriginalFilename());//得到图片上传路径
                //得到图片保存路径开头映射头
                String imageContextPath = ConfigUtils.getConfiguration(SysContants.PropertyFilePath.CONFIG).getString(SysContants.PropertyKey.IMAGE_CONTEXT_PATH);
                resultState.setData(imageContextPath+resultState.getData());//拼接图片绝对路径
                return resultState;
            }
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg( "数据文件保存失败");
        return resultState;
    }*/


    //////////////////////////////增加咨询日志////////////////
    @RequestMapping(value = "logIndex.htm")
    public ModelAndView logIndex(){
        ModelAndView modelAndView = new ModelAndView("admin/consult_mgr/logIndex");
        return modelAndView;
    }

    @RequestMapping(value = "logList.action")
    public ModelAndView logList(ConsultSearchModel inputModel,@RequestParam(defaultValue = "1") int pageNo){
        ModelAndView modelAndView = new ModelAndView("admin/consult_mgr/logList");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        pager.setTotal(consultService.queryCount(inputModel));
        modelAndView.addObject("list", consultService.getList(inputModel));
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }
}
