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.TagWithBLOBs;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.ITagSerice;
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 java.io.File;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/admin/tag")
public class TagController extends BaseController{

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

    @Autowired
    private ITagSerice tagSerice ;

    @RequestMapping(value = "index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("/admin/tag/index") ;
        List<TagEntityExtendModel> list = new ArrayList<>();
        List<TagWithBLOBs> allTage = tagSerice.getAllTag();
        List<MainNameAndValue> mainNameAndValues = tagSerice.getMains();
        for (TagWithBLOBs item : allTage) {
            TagEntityExtendModel newItem = new TagEntityExtendModel();
            BeanUtils.copyProperties(item, newItem);
            newItem.setTagImgFileName(StringUtils.isNotEmpty(item.getCategoryImg()) ? UploadFileUtils.getFileNameByPath(item.getCategoryImg()) : null);
            list.add(newItem);
        }
        String allTagJsonStr = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            allTagJsonStr = objectMapper.writeValueAsString(list);
        }catch (JsonProcessingException jpe){
            logger.error(jpe.getMessage());
        }
        modelAndView.addObject("allTagJsonStr", allTagJsonStr);
        modelAndView.addObject("mainNameAndValues", mainNameAndValues);
        return modelAndView;
    }

    @RequestMapping(value = "tagTreeData.action")
    @ResponseBody
    public List<TreeModel> tagTreeData(Long selectedId){
        List<TreeModel> outputModel = tagSerice.tagTreeData(selectedId);
        return outputModel;
    }

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

         //保存文件
        String uniqueDir;
        if (StringUtils.isNotEmpty(inputModel.getCategoryImg())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, inputModel.getCategoryImg(), 2);
        } else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String file1Dir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.RESOURCE_Tag_ROOT_DIR, uniqueDir, SysContants.UploadFilePath.RESOURCE_Tag_ROOT_DIR);
        if (imgCatelog != null && !imgCatelog.isEmpty()){
            if (UploadFileUtils.writeUploadFile(imgCatelog, file1Dir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                inputModel.setCategoryImg(file1Dir + imgCatelog.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.UNKNOWN_ERROR, "数据文件保存失败");
            }
        }

        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setCreatedBy(loginUser.getId());
        ResultState<TagWithBLOBs> resultStateRaw = tagSerice.addOrEdit(inputModel);
        TagWithBLOBs entity = resultStateRaw.getData();
        TagEntityExtendModel model = new TagEntityExtendModel();
        BeanUtils.copyProperties(entity, model);
        model.setTagImgFileName(StringUtils.isNotEmpty(entity.getCategoryImg()) ? UploadFileUtils.getFileNameByPath(entity.getCategoryImg()) : null);
        ResultState<TagEntityExtendModel> resultState = new ResultState<>();
        resultState.setMsg(resultStateRaw.getMsg());
        resultState.setData(model);
        return resultState;
    }

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

}
