package com.jeeplus.modules.sg.project.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.overheadline.service.OverheadLineService;
import com.jeeplus.modules.sg.overheadline.util.BashInfo;
import com.jeeplus.modules.sg.project.entity.WbsItem;
import com.jeeplus.modules.sg.project.entity.WbsProject;
import com.jeeplus.modules.sg.project.entity.WbsSelection;
import com.jeeplus.modules.sg.project.service.ItemService;
import com.jeeplus.modules.sg.project.service.ProjectService;
import com.jeeplus.modules.sg.substation.service.SubstationService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("${adminPath}/project/tem")
public class ProjectTemController extends BaseController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private OverheadLineService overheadLineService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private SubstationService substationService;


    /**
     *首页跳转  单体工程管理页面
     */
    @RequestMapping("/index")
    public String toIndex(){
        return "modules/sg/projecttem/addItem2Form";
    }


    /**
     * 项目分页展示
     * @param wbsProject
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"list", ""})
    public String list(WbsProject wbsProject, HttpServletRequest request, HttpServletResponse response, Model model) {
       List<WbsProject> list =  projectService.findList(wbsProject);
       model.addAttribute("list",list);
        return "modules/sg/projecttem/manageList";
    }


    /**
     * 多文件导入  导入工程
     * @param file 文件数组
     * @param projectName 单体工程名称
     * @param projectNo  单体工程编号
     * @param itemNames 结算书名称
     * @param units  供应商
     * @return
     */
    @ResponseBody
    @RequestMapping("/import")
    public HashMap importFile(@RequestParam(value = "file")MultipartFile[] file,String projectName,String projectNo,String[] itemNames,String[] units) {
        HashMap map = new HashMap();
//        添加工程
        WbsProject wbsProject = new WbsProject();
        wbsProject.setProjectName(projectName);
        wbsProject.setProjectNo(projectNo);
        projectService.save(wbsProject);
        String projectId = wbsProject.getId();
        String fileName = "";
        try {
            for(int i = 0;i<itemNames.length;i++) {
                fileName = file[i].getOriginalFilename();
                WbsItem wbsItem = new WbsItem();
                wbsItem.setItemName(itemNames[i]);
                wbsItem.setProjectId(projectId);
                if(null != units && units.length >0){
                    if(StringUtils.isNotBlank(units[i])){
                     wbsItem.setUnit(units[i]);
                    }
                }
                //获取唯一ID
                String id = getId();
                wbsItem.setId(id);
                //分析保存
                String str = projectService.save(file[i],wbsItem);
                if(str.equals(BashInfo.INVALIDFORMAT)){
                    throw new RuntimeException(str);
                }
            }
        }  catch (Exception e){
            map.put("code",0);
            map.put("msg","导入失败，"+fileName+e.getMessage());
            projectService.delete(wbsProject);
            return map;
        }
        map.put("code",1);
        map.put("msg","导入成功");
        map.put("id",projectId);
        return map;
    }


    /**
     * 单个文件导入
     * @param file  文件
     * @param wbsItem 项目信息
     * @param redirectAttributes
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/importfile")
    public String importFile(MultipartFile file,WbsItem wbsItem, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) {
        String projectId = wbsItem.getProjectId();
        String id = getId();
        wbsItem.setId(id);
        try {
//            保存数据到数据库
            String str = projectService.save(file,wbsItem);
            if(str.equals(BashInfo.INVALIDFORMAT)){
                throw new RuntimeException(str);
            }
            addMessage(redirectAttributes, "导入成功");
            return "redirect:/a/jkxl/list?id="+id+"&type="+str+"&projectId="+projectId;
        }   catch (Exception e){
            addMessage(redirectAttributes, "导入失败，"+e.getMessage());
            return "redirect:/a/project/tem/list?projectId="+projectId;
        }
    }





    /**
     * 返回单个工程
     * @param request
     * @return
     */
    @RequestMapping(value = "tolist")
    public String toList(HttpServletRequest request){
        String projectId = request.getParameter("projectId");
        return "redirect:/a/project/tem/list?projectId="+projectId;
    }


    /**
     * 获取工程数据
     * @param wbsProject
     * @param model
     * @return
     */
    @RequestMapping("/form")
    public String form(WbsProject wbsProject, Model model) {
        WbsProject wbsProject1 = projectService.get(wbsProject.getId());
        List<WbsProject> list = new ArrayList<>();
        list.add(wbsProject1);
        model.addAttribute("list", list);
        String view = "updateItem";
        String tabId = request.getParameter("tabId");
        if("1".equals(tabId)){
            view = "lookItem";
        }
        return "modules/sg/projecttem/"+view;
    }





    /**
     * 创建项目ID
     */
    public String getId() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }


    //校验项目名称是否存在
    @RequestMapping("/verfiy")
    @ResponseBody
    public HashMap getVerfiy(String projectName,String projectId){
        HashMap map = new HashMap();
        List<WbsItem> wbsItemList = itemService.findItemByName(projectName,projectId);
        if (wbsItemList!=null&&!wbsItemList.isEmpty()){
            map.put("msg","导入失败! 结算书名称:"+projectName+" 已存在");
            return map;
        }
        map.put("code",1);
        map.put("msg","导入成功");
        return map;
    }

    //删除项目
    @RequestMapping("/deleteItem")
    @ResponseBody
    public AjaxJson deleteItem(WbsItem wbsItem){
       return  itemService.deleteItemOne(wbsItem);
    }


    //返回
    @RequestMapping("/return")
    public String returnto(){
      return  "modules/sg/projecttem/addItem2Form";
    }
}
