package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.dictionary.DicRequirementState;
import com.lightinit.hsdataplatform.dictionary.DicResourceAuditResult;
import com.lightinit.hsdataplatform.dictionary.DicResourceMicroappReqmntState;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.entity.Requirement;
import com.lightinit.hsdataplatform.entity.ResourceCatelog;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.common.PermissionUtilsPro;
import com.lightinit.hsdataplatform.service.admin.IAccountService;
import com.lightinit.hsdataplatform.service.admin.IRequirementMicroappService;
import com.lightinit.hsdataplatform.service.admin.IRequirementService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Date;

import static com.lightinit.hsdataplatform.controller.admin.BaseController.getAllFieldInvalidResultState;

/**
 * Created by herbert on 2018/5/24.
 * 服务开发需求
 */
@Controller("adminMicroAppController")
@RequestMapping("/admin/microapp")
public class RequirementMicroappController {

    @Autowired
    private IRequirementMicroappService requirementMicroappService;

    @Autowired
    private IRequirementService requirementService;

    @Autowired
    private  PermissionUtilsPro permissionUtilsPro;

    @Autowired
    private IAccountService accountService;

    @RequestMapping(value = "index.htm",method = RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/microapp/index");
        modelAndView.addObject("dicRequirementState", DicResourceMicroappReqmntState.getInstacne().getDicMap());
        return modelAndView;
    }
    @RequestMapping(value = "list.action")
        public ModelAndView list(RequirementMicroappSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo) throws IOException {
        ModelAndView modelAndView = new ModelAndView("admin/microapp/list");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        List<Requirement> outputModel = requirementMicroappService.queryList(inputModel, pager);
        pager.setTotal(requirementMicroappService.queryCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    @RequestMapping(value = "info/{id}")
    public ModelAndView info(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/microapp/info");
        modelAndView.addObject("info",requirementMicroappService.info(id));
        return modelAndView;
    }

    @RequiresAuthentication
    @RequestMapping(value = "aduit/{id}")
    public ModelAndView aduit(@PathVariable long id, HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ModelAndView modelAndView = new ModelAndView("admin/microapp/edit");
        modelAndView.addObject("info",requirementMicroappService.info(id));
        modelAndView.addObject("datetime",new Date());
        modelAndView.addObject("admin",loginUser.getUsername());
        return modelAndView;
    }

    @RequestMapping(value = "unshelve/{id}")
    public ModelAndView unshelve(@PathVariable long id){
        ModelAndView modelAndView = new ModelAndView("admin/microapp/unshelve");
        modelAndView.addObject("id",id);
        return modelAndView;
    }
    @RequestMapping(value = "unshelveresult/{status}")
    public ModelAndView unshelveState(@PathVariable int  status){
        ModelAndView modelAndView = new ModelAndView("admin/microapp/unshelveresult");
        modelAndView.addObject("status",status);
        return modelAndView;
    }
    @RequiresAuthentication
    @RequestMapping(value = "edit.action")
    @ResponseBody
    public ResultState doEdit(RequirementAuditModel auditDataModel,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        Requirement tmpRequirement=requirementService.info(auditDataModel.getId());
        ResultState<Long> resultState=new ResultState<Long>();
        if (tmpRequirement==null){
            resultState.setStateCode(ResultStateCode.DATA_ITEM_NOT_EXIST);
            resultState.setMsg("数据不存在");
            return resultState;
        }
        //TODO 是否需要根据是否过期判断该记录是否属于已关闭的状态
        if ( auditDataModel.getAuditStatus()==2   ){
            tmpRequirement.setRqrmntState(DicRequirementState.REJECTED);
            tmpRequirement.setAuditResult(DicResourceAuditResult.REJECTED);
        }else  if (auditDataModel.getAuditStatus()==1 ){
            tmpRequirement.setRqrmntState(DicRequirementState.PROSCESSING);
            tmpRequirement.setAuditResult(DicResourceAuditResult.APPROVED);
            tmpRequirement.setPublishAt(new Date());
        }else {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据非法");
            return resultState;
        }
        tmpRequirement.setAuditOpinion(auditDataModel.getAuditOpinion());
        tmpRequirement.setAuditedBy(loginUser.getId());
        tmpRequirement.setAuditedAt(new Date());
        resultState = requirementService.edit(tmpRequirement);
        return resultState;
    }

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

    @RequiresAuthentication
    @RequestMapping(value = "unshelve.action")
    @ResponseBody
    public ResultState unshelveRequirement(RequirementUnShelveModel unShelveModel,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ResultState<Long> resultState=new ResultState<Long>();
        if (unShelveModel==null){
            resultState.setStateCode(ResultStateCode.DATA_ITEM_NOT_EXIST);
            resultState.setMsg("数据不存在");
            return resultState;
        }
        if ( unShelveModel.getId()<=0   ){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("数据非法");
            return resultState;
        }
        Requirement tmpRequirement=requirementService.info(unShelveModel.getId());
        tmpRequirement.setRqrmntState(DicRequirementState.OFF_SHELVES);
        tmpRequirement.setAuditedBy(loginUser.getId());
        tmpRequirement.setAuditedAt(new Date());
        tmpRequirement.setAuditOpinion(unShelveModel.getUnshelvereasons());//下架原因（审核意见）
        // tmpRequirement.setAuditResult("下架");// TODO 审核结果 在下架时不做处理
        resultState=requirementService.edit(tmpRequirement);
        return resultState;
    }


    @RequestMapping(value = "receive.htm/{id}")
    public ModelAndView receive(@PathVariable Long id){
        ModelAndView modelAndView = new ModelAndView("admin/microapp/receive");
        modelAndView.addObject("rqrmntId",id);
        return modelAndView;
    }

    @RequestMapping(value = "toReceive.action")
    @ResponseBody
    public ResultState receive(HttpSession session, RequirementReceiveModel inputModel) {
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setReceivedBy(loginUser.getId());
        ResultState   resultState = requirementService.receive(inputModel);
        return resultState;
    }


    @RequestMapping(value = "add.htm")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("admin/microapp/add");
        List<ResourceCatelog> obj = requirementService.selectCatelog();
        modelAndView.addObject("obj", obj);
        return modelAndView;
    }


    @RequestMapping(value = "toAdd.action")
    @ResponseBody
    public ResultState toAdd(HttpSession session, @Valid RequirementMicroappPublishModel inputModel, BindingResult bindingResult) {
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        inputModel.setPublishBy(loginUser.getId());

        return requirementService.publish(inputModel);
    }


}
