package com.lightinit.hsdataplatform.controller.admin;

import com.lightinit.hsdataplatform.common.ContractNumberUtils;
import com.lightinit.hsdataplatform.common.GuidGenerator;
import com.lightinit.hsdataplatform.common.SysContants;
import com.lightinit.hsdataplatform.common.UploadFileUtils;
import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.BaseExample;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
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;

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

@Controller
@RequestMapping("/admin/contract")
public class ContractController {

    @Autowired
    private IContractService contractService ;

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

    @RequestMapping(value = "list.action")
    public ModelAndView list(ContractSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo, HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ModelAndView modelAndView = new ModelAndView("admin/contract/list");
        BaseExample.Page pager = new BaseExample.Page();
        pager.setPageNo(pageNo);
        inputModel.setPage(pager);
        int isFlag = contractService.isAdminFalg(loginUser.getId()) ;
        if (!(isFlag>0)){
            inputModel.setOrgId(loginUser.getOrgId());
        }
        List<ContractListModel> outputModel = contractService.queryList(inputModel);
        pager.setTotal(contractService.queryCount(inputModel));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        modelAndView.addObject("weishengxiao", DicContractState.NO_EFFECT);
        modelAndView.addObject("yiguoqi", DicContractState.OVERDUE);
        modelAndView.addObject("yishengxiao", DicContractState.EFFECT);
        return modelAndView;
    }

    @RequestMapping(value = "add.htm")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("admin/contract/add");
        modelAndView.addObject("contractNumber", ContractNumberUtils.generate()) ;
        return modelAndView;
    }



    @RequestMapping(value = "addResource.htm")
    public ModelAndView addResource(){
        ModelAndView modelAndView = new ModelAndView("admin/contract/addResource");
        modelAndView.addObject("resourceType", DicResourceType.getInstacne().getDicMap()) ;
        modelAndView.addObject("chargeMethod", DicPublishSettingChargeMethod.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value="resourceList.action")
    public ModelAndView resourceList(ContractResourceSearchModel inputModel, @RequestParam(defaultValue = "1") int pageNo,HttpSession session){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        ModelAndView modelAndView = new ModelAndView("admin/contract/resourceList");
        BaseExample.Page pager = new BaseExample.Page(pageNo, 10);
        inputModel.setPage(pager);
        int isFlag = contractService.isAdminFalg(loginUser.getId()) ;
        if (!(isFlag>0)){
            inputModel.setOrgId(loginUser.getOrgId());
        }
        inputModel.setOpenType(DicResourceOpenType.NOT_OPEN);
        inputModel.setPublishState(DicDataPublishState.PUBLISHED);
        List<ContractResourceListModel> resourceList = contractService.resourceList(inputModel);
        pager.setTotal(contractService.resourceCount(inputModel));
        modelAndView.addObject("resourceList", resourceList);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    @RequestMapping(value = "addFinally.action")
    @ResponseBody
    public ResultState addFinally(ContractAddModel input,HttpSession session,MultipartFile attachmentFile){
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        // 保存图片
        String uniqueDir = GuidGenerator.generate() + File.separator;
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.CONTRACT_ATTACHMENT, uniqueDir, SysContants.UploadFilePath.CONTRACT_ATTACHMENT_DIR);
        if (attachmentFile != null && !attachmentFile.isEmpty()){
            if (UploadFileUtils.writeUploadFile(attachmentFile, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                input.setAttachment(dataFileDir + attachmentFile.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "电子版合同保存失败");
            }
        }
        return contractService.addFinally(input,loginUser.getId());
    }

    @RequestMapping(value = "view.htm/{id}")
    public ModelAndView view(@PathVariable Long id){
        ModelAndView modelAndView = new ModelAndView("admin/contract/view");
        ContractViewModel contractViewModel = contractService.queryOne(id) ;
        modelAndView.addObject("contract", contractViewModel);
        if (contractViewModel!=null){
            modelAndView.addObject("attachmentName", org.apache.commons.lang.StringUtils.isNotEmpty(contractViewModel.getAttachment()) ? UploadFileUtils.getFileNameByPath(contractViewModel.getAttachment()) : null);
        }
        return modelAndView;
    }

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

    @RequestMapping(value = "edit.htm/{id}")
    public ModelAndView edit(@PathVariable Long id){
        ModelAndView modelAndView = new ModelAndView("admin/contract/edit");
        ContractViewModel contractViewModel = contractService.queryOne(id) ;
        modelAndView.addObject("contract", contractViewModel);
        if (contractViewModel!=null){
            modelAndView.addObject("attachmentName", org.apache.commons.lang.StringUtils.isNotEmpty(contractViewModel.getAttachment()) ? UploadFileUtils.getFileNameByPath(contractViewModel.getAttachment()) : null);
        }
        return modelAndView;
    }

    @RequestMapping(value = "editFinally.action")
    @ResponseBody
    public ResultState editFinally(ContractEditModel input,HttpSession session,MultipartFile attachmentFile){
        // 保存图片
        String uniqueDir ;
        if (org.apache.commons.lang.StringUtils.isNotEmpty(input.getAttachment())){
            uniqueDir = UploadFileUtils.getExistingFileRelativeDir(1, input.getAttachment(), 2);
        } else {
            uniqueDir = GuidGenerator.generate() + File.separator;
        }
        String dataFileDir = UploadFileUtils.buildRelativeDir(SysContants.UploadFilePath.CONTRACT_ATTACHMENT, uniqueDir, SysContants.UploadFilePath.CONTRACT_ATTACHMENT_DIR);
        if (attachmentFile != null && !attachmentFile.isEmpty()){
            if (UploadFileUtils.writeUploadFile(attachmentFile, dataFileDir, SysContants.PropertyKey.UPLOAD_IMAGE_ROOT_DIR)){
                input.setAttachment(dataFileDir + attachmentFile.getOriginalFilename());
            }else {
                return buildInvalidResultState(ResultStateCode.INVALID_DATA, "电子版合同保存失败");
            }
        }
        LoginUser loginUser = (LoginUser) session.getAttribute(LoginUser.SESSION_KEY_LOGIN_USER);
        return contractService.editFinally(input,loginUser.getId()) ;
    }

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

}
