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";
    }




    @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";
    }



    /**
     *文件多个导入
     */
    @ResponseBody
    @RequestMapping("/import")
    public HashMap importFile(@RequestParam(value = "file")MultipartFile[] file,String projectName,String projectNo,String[] itemNames,String[] units,String[] itemNo) throws IOException, InvalidFormatException {
        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]);
                    }
                }
//                if(null != itemNo && itemNo.length >0) {
//                    if (StringUtils.isNotBlank(itemNo[i])) {
//                        wbsItem.setItemNo(itemNo[i]);
//                    }
//                }
//            保存数据到数据库
                String id = getId();
                wbsItem.setId(id);
                String str = projectService.save(file[i],wbsItem);
                if(str.equals(BashInfo.INVALIDFORMAT)){
                    throw new RuntimeException(str);
                }
            }
        } catch (RuntimeException e) {
            map.put("code",0);
            map.put("msg","导入失败，"+fileName+e.getMessage());
            projectService.delete(wbsProject);
            return map;
        }  catch (Exception e){
            map.put("code",0);
            map.put("msg","导入失败");
            projectService.delete(wbsProject);
            return map;
        }
        map.put("code",1);
        map.put("msg","导入成功");
        map.put("id",projectId);
        return map;
    }


    /**
     *文件导入
     */
    @RequestMapping("/importfile")
    public String importFile(MultipartFile file,WbsItem wbsItem, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) {
//        String type = wbsItem.getType();   //项目类型
        String projectId = wbsItem.getProjectId();
        String id = getId();
        wbsItem.setId(id);
        try {
//            保存数据到数据库
//            if(type.equals("1")) {
//                overheadLineService.saveJk(file, wbsItem);
//            }
//            if (type.equals("2")) {
//                overheadLineService.saveDl(file, wbsItem);
//            }
//            if (type.equals("3")) {
//                substationService.save(file, wbsItem);
//            }
            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 (RuntimeException e) {
            addMessage(redirectAttributes, "导入失败,"+e.getMessage());
            return "redirect:/a/project/tem/list?projectId="+projectId;
        }   catch (Exception e){
            addMessage(redirectAttributes, "导入失败");
            return "redirect:/a/project/tem/list?projectId="+projectId;
        }
//        addMessage(redirectAttributes, "导入成功");
//        return "redirect:/a/jkxl/list?id="+id+"&type="+type+"&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;
    }

//    @RequestMapping("/indexlist")
//    public String indexList(){
//        return "modules/sg/projecttem/addItem2Form";
//    }

    @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);
    }
}
