package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.common.GuidGenerator;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;
import com.lightinit.hsdataplatform.dictionary.DicResourceAuditResult;
import com.lightinit.hsdataplatform.dictionary.DicResourceOpenType;
import com.lightinit.hsdataplatform.dictionary.DicResourceShareType;
import com.lightinit.hsdataplatform.dictionary.DicResourceState;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.mapper.PublishInfoMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IResourceDataRegisterService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.List;

/**
 * 数据注册
 */
@Controller
@RequestMapping("/admin/data_register")
public class ResourceDataRegisterController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ResourceDataRegisterController.class);

    @Autowired
    private IResourceDataRegisterService resourceDataRegisterService;

    @RequestMapping(value = "index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/data_register/index");
        modelAndView.addObject("dicResourceState", DicResourceState.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "list.action")
    public ModelAndView list(ResourceDataRegisterSearchModel 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/data_register/list");
        BaseExample.Page pager = new BaseExample.Page(pageNo, 10);
        inputModel.setPage(pager);
        List<ResourceDataRegisterListModel> outputModel = resourceDataRegisterService.queryList(inputModel);
        pager.setTotal(resourceDataRegisterService.queryCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    @RequestMapping(value = "add.htm")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("admin/data_register/add");
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "add.action")
    @ResponseBody
    public ResultState doAdd(HttpSession session, @Valid ResourceDataRegisterDataModel inputModel, BindingResult bindingResult, MultipartFile fileData, MultipartFile fileDemo){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }

        // 保存文件
        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.DATA_REGISTER_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.DATA_REGISTER_DATA_DIR);
        if (fileData != null && !fileData.isEmpty()){
            if (UploadFileUtils.writeUploadFile(fileData, dataFileDir, SysContants.PropertyKey.UPLOAD_FILE_ROOT_DIR)){
                inputModel.setDataFile(dataFileDir + fileData.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }
        String demoFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.DATA_REGISTER_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.DATA_REGISTER_DEMO_DIR);
        if (fileDemo != null && !fileDemo.isEmpty()){
            if (UploadFileUtils.writeUploadFile(fileDemo, demoFileDir, SysContants.PropertyKey.UPLOAD_FILE_ROOT_DIR)){
                inputModel.setDemoFile(demoFileDir + fileDemo.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "示例文件保存失败");
            }
        }

        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setCreatedBy(loginUser.getId());
        ResultState resultState = resourceDataRegisterService.add(inputModel);


        return resultState;
    }

    @RequestMapping(value = "edit.htm/{id}")
    public ModelAndView edit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/data_register/edit");
        ResourceDataRegisterDataModel busiModel = resourceDataRegisterService.queryOne(id);
        if (busiModel != null){
            modelAndView.addObject("busiModel", busiModel);
            modelAndView.addObject("dataFileName", StringUtils.isNotEmpty(busiModel.getDataFile()) ? UploadFileUtils.getFileNameByPath(busiModel.getDataFile()) : null);
            modelAndView.addObject("demoFileName", StringUtils.isNotEmpty(busiModel.getDemoFile()) ? UploadFileUtils.getFileNameByPath(busiModel.getDemoFile()) : null);
        }
        modelAndView.addObject("dicResourceShareType", DicResourceShareType.getInstacne().getDicMap());
        modelAndView.addObject("dicResourceOpenType", DicResourceOpenType.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "edit.action")
    @ResponseBody
    public ResultState doEdit(@Valid ResourceDataRegisterDataModel inputModel, BindingResult bindingResult, MultipartFile fileData, MultipartFile fileDemo){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }

        // 保存文件
        String uniqueDir;
        if (StringUtils.isNotEmpty(inputModel.getDataFile())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, inputModel.getDataFile(), 2);
        }else if (StringUtils.isNotEmpty(inputModel.getDemoFile())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, inputModel.getDemoFile(), 2);
        }else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.DATA_REGISTER_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.DATA_REGISTER_DATA_DIR);
        if (fileData != null && !fileData.isEmpty()){
            if (UploadFileUtils.writeUploadFile(fileData, dataFileDir, SysContants.PropertyKey.UPLOAD_FILE_ROOT_DIR)){
                inputModel.setDataFile(dataFileDir + fileData.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }
        String demoFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.DATA_REGISTER_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.DATA_REGISTER_DEMO_DIR);;
        if (fileDemo != null && !fileDemo.isEmpty()){
            if (UploadFileUtils.writeUploadFile(fileDemo, demoFileDir, SysContants.PropertyKey.UPLOAD_FILE_ROOT_DIR)){
                inputModel.setDemoFile(demoFileDir + fileDemo.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "示例文件保存失败");
            }
        }

        ResultState<Long> resultState = resourceDataRegisterService.edit(inputModel);
        return resultState;
    }

    @RequestMapping(value = "audit.htm/{id}")
    public ModelAndView audit(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/data_register/audit");
        modelAndView.addObject("busiModel", resourceDataRegisterService.queryOne(id));
        return modelAndView;
    }

    @RequestMapping(value = "audit.action")
    @ResponseBody
    public ResultState doAudit(HttpSession session, @Valid ResourceDataRegisterAuditModel inputModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        if (!DicResourceAuditResult.getInstacne().getDicMap().containsKey(inputModel.getAuditResult())){
            return buildInvalidResultState("审核结果不正确");
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setAuditedBy(loginUser.getId());
        ResultState resultState = resourceDataRegisterService.audit(inputModel);
        return resultState;
    }

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

}
