package com.lightinit.hsdataplatform.controller.admin;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lightinit.hsdataplatform.common.GuidGenerator;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;
import com.lightinit.hsdataplatform.entity.ResourceCatelog;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.LoginUser;
import com.lightinit.hsdataplatform.model.admin.ResourceCatelogDataModel;
import com.lightinit.hsdataplatform.model.admin.ResourceCatelogEntityExtendModel;
import com.lightinit.hsdataplatform.model.admin.TreeModel;
import com.lightinit.hsdataplatform.service.admin.ICommonService;
import com.lightinit.hsdataplatform.service.admin.IResourceCatelogMgrService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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.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.ArrayList;
import java.util.List;

/**
 * @author WangYao
 * @date 2018/6/3 11:44
 * @description 目录管理控制器
 */
@Controller
@RequestMapping("/admin/resource_catelog_mgr")
public class ResourceCatelogMgrController extends BaseController {

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

    @Autowired
    private IResourceCatelogMgrService resourceCatelogMgrService;

    @RequestMapping(value = "index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/resource_catelog_mgr/index");
        List<ResourceCatelogEntityExtendModel> list = new ArrayList<>();
        List<ResourceCatelog> allResourceCatelog = resourceCatelogMgrService.getAllResourceCatelog(null);
        for (ResourceCatelog item : allResourceCatelog) {
            ResourceCatelogEntityExtendModel newItem = new ResourceCatelogEntityExtendModel();
            BeanUtils.copyProperties(item, newItem);
            newItem.setCatelogImgFileName(StringUtils.isNotEmpty(item.getCatelogImg()) ? UploadFileUtils.getFileNameByPath(item.getCatelogImg()) : null);
            list.add(newItem);
        }
        String allResourceCatelogJsonStr = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            allResourceCatelogJsonStr = objectMapper.writeValueAsString(list);
        }catch (JsonProcessingException jpe){
            logger.error(jpe.getMessage());
        }
        modelAndView.addObject("allResourceCatelog", allResourceCatelogJsonStr);
        return modelAndView;
    }

    @RequestMapping(value = "tree_data.action")
    @ResponseBody
    public List<TreeModel> getTreeData(String resourceCatelogType){
        return resourceCatelogMgrService.queryTreeData(resourceCatelogType);
    }

    @RequestMapping(value = "edit.action")
    @ResponseBody
    public ResultState doEdit(HttpSession session, @Valid ResourceCatelogDataModel inputModel, BindingResult bindingResult, MultipartFile imgCatelog){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }

        // 保存文件
        String uniqueDir;
        if (StringUtils.isNotEmpty(inputModel.getCatelogImg())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, inputModel.getCatelogImg(), 2);
        } else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String file1Dir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.RESOURCE_CATELOG_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.RESOURCE_CATELOG_IMG_DIR);
        if (imgCatelog != null && !imgCatelog.isEmpty()){
            if (UploadFileUtils.writeUploadFile(imgCatelog, file1Dir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setCatelogImg(file1Dir + imgCatelog.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }
        
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setCreatedBy(loginUser.getId());
        ResultState<ResourceCatelog> resultStateRaw = resourceCatelogMgrService.addOrEdit(inputModel);
        //如果为400，就代表目录创建失败，不必走下面创建结果对象的流程
        if (ResultStateCode.INVALID_DATA == resultStateRaw.getStateCode()){
            ResultState<ResourceCatelogEntityExtendModel> resultState = new ResultState<>();
            resultState.setStateCode(resultStateRaw.getStateCode());
            resultState.setMsg(resultStateRaw.getMsg());
            return resultState;
        }
        ResourceCatelog entity = resultStateRaw.getData();
        ResourceCatelogEntityExtendModel model = new ResourceCatelogEntityExtendModel();
        BeanUtils.copyProperties(entity, model);
        model.setCatelogImgFileName(StringUtils.isNotEmpty(entity.getCatelogImg()) ? UploadFileUtils.getFileNameByPath(entity.getCatelogImg()) : null);
        ResultState<ResourceCatelogEntityExtendModel> resultState = new ResultState<>();
        resultState.setStateCode(resultStateRaw.getStateCode());
        resultState.setMsg(resultStateRaw.getMsg());
        resultState.setData(model);
        return resultState;
    }

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