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

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.overheadline.entity.JkxlDetailFee;
import com.jeeplus.modules.sg.overheadline.service.OverheadLineService;
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.ProjectService;
import com.jeeplus.modules.sg.project.util.ExportUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
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 org.springframework.ui.Model;

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")
public class ProjectController extends BaseController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private OverheadLineService overheadLineService;


//    @ModelAttribute
//    public WbsProject get(@RequestParam(required=false) String id) {
//        WbsProject entity = null;
//        if (StringUtils.isNotBlank(id)){
//            entity = projectService.get(id);
//        }
//        if (entity == null){
//            entity = new WbsProject();
//        }
//        return entity;
//    }


    @RequestMapping(value = {"list", ""})
    public String list(WbsSelection wbsSelection, HttpServletRequest request, HttpServletResponse response, Model model) {
       List<WbsProject> list =  projectService.findList(wbsSelection);
       model.addAttribute("list",list);
        return "modules/sg/project/management";
    }


    @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 = "updateItemForm";
        String tabId = request.getParameter("tabId");
        if("1".equals(tabId)){
            view = "lookItemForm";
        }
        return "modules/sg/project/"+view;
    }

    //项目保存
    @ResponseBody
    @RequestMapping("/save")
    public AjaxJson save(WbsProject wbsProject, Model model, RedirectAttributes redirectAttributes){
        AjaxJson j = new AjaxJson();
        //数据验证
        String errMsg = beanValidator(wbsProject);
        if (StringUtils.isNotBlank(errMsg)){
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        //新增或编辑表单保存
        projectService.save(wbsProject);//保存
        j.setSuccess(true);
        addMessage(redirectAttributes, "保存成功");
        return j;
    }

    /**
     *数据导入
     */
    @RequestMapping("/import")
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model)throws Exception {
        String projectName = request.getParameter("name");     //项目名称
        String projectId = request.getParameter("projectId");    //工程ID
        String type = request.getParameter("type");     //工程类型
        String id = getId();
        try {
//            保存数据到数据库
            if(type.equals("1")) {
                overheadLineService.saveJk(file, projectName, id, projectId, type);
            }
            if (type.equals("2")) {
                overheadLineService.saveDl(file, projectName, id, projectId, type);
            }
        } catch (RuntimeException e) {
            addMessage(redirectAttributes, "导入失败,"+e.getMessage());
            return "redirect:/a/project/list";
        }   catch (Exception e){
            addMessage(redirectAttributes, "导入失败");
            return "redirect:/a/project/list";
        }
        addMessage(redirectAttributes, "导入成功");
        return "redirect:/a/jkxl/list?id="+id+"&type="+type;
    }

    //导出
    @RequestMapping("/export")
    public String toList(HttpServletRequest request,Model model,HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        WbsProject wbsProject = projectService.get(id);
        String fileName = wbsProject.getProjectName()+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
        List<WbsItem> wbsItems = wbsProject.getWbsItems();
        String[] sts = new String[wbsItems.size()+1];
        sts[0] = "合计";
        for (int i=0;i<wbsItems.size();i++){
            sts[i+1] = wbsItems.get(i).getItemName();
        }
        List<JkxlDetailFee> list = new ArrayList<>();
        for(WbsItem wbsItem :wbsItems){
            List<JkxlDetailFee> jkxlDetailFees = overheadLineService.findList(wbsItem.getId(),wbsItem.getType());
            list.addAll(jkxlDetailFees);
        }
        //集合去重合并
        List<JkxlDetailFee> list1 = getNewList(list);
        //加序号
        for (int i=0;i<list1.size();i++){
            list1.get(i).setIndex(i+1);
        }
        ExportUtil exportUtil = new ExportUtil(null, JkxlDetailFee.class,sts);
        //写合计
        exportUtil.setDataList(list1,0);
        //分别写入项目
        for(int j=0;j<wbsItems.size();j++){
            List<JkxlDetailFee> jkxlDetailFees = overheadLineService.findList(wbsItems.get(j).getId(),wbsItems.get(j).getType());
            exportUtil.setDataList(jkxlDetailFees,j+1);
        }
        exportUtil.write(response,fileName).dispose();
        return "redirect:/a/project/list";
    }


    /**
     * 数据去重合并
     * @param list
     * @return
     */
    private List<JkxlDetailFee> getNewList(List<JkxlDetailFee> list) {
       List<JkxlDetailFee> list1 = new ArrayList<>();
       for(JkxlDetailFee jkxlDetailFee: list){
           String wbsCode = jkxlDetailFee.getWbsCode();
           if(!list1.contains(jkxlDetailFee)){
               list1.add(jkxlDetailFee);
           }else {
               for(JkxlDetailFee jkxlDetailFee1 : list1){
                   if(jkxlDetailFee1.getWbsCode().equals(wbsCode)){
                      double azFee = jkxlDetailFee1.getAzFee()!=null? jkxlDetailFee1.getAzFee():0.00;
                      double azFee1 = jkxlDetailFee.getAzFee()!=null? jkxlDetailFee.getAzFee():0.00;
                       double qtFee = jkxlDetailFee1.getQtFee()!=null? jkxlDetailFee1.getQtFee():0.00;
                       double qtFee1 = jkxlDetailFee.getQtFee()!=null? jkxlDetailFee.getQtFee():0.00;
                       double totalFee = jkxlDetailFee1.getTotalFee()!=null? jkxlDetailFee1.getTotalFee():0.00;
                       double totalFee1 = jkxlDetailFee.getTotalFee()!=null? jkxlDetailFee.getTotalFee():0.00;
                       double jsFee = jkxlDetailFee1.getJsFee()!=null? jkxlDetailFee1.getJsFee():0.00;
                       double jsFee1 = jkxlDetailFee.getJsFee()!=null? jkxlDetailFee.getJsFee():0.00;
                       double cFee = jkxlDetailFee1.getcFee()!=null? jkxlDetailFee1.getcFee():0.00;
                       double cFee1 = jkxlDetailFee.getcFee()!=null? jkxlDetailFee.getcFee():0.00;
                       jkxlDetailFee1.setAzFee(azFee+azFee1);
                       jkxlDetailFee1.setQtFee(qtFee+qtFee1);
                       jkxlDetailFee1.setTotalFee(totalFee+totalFee1);
                       jkxlDetailFee1.setJsFee(jsFee+jsFee1);
                       jkxlDetailFee1.setcFee(cFee+cFee1);
                   }
               }
           }
       }
       //按照wbs码排序
        Collections.sort(list1, new Comparator<JkxlDetailFee>() {
            @Override
            public int compare(JkxlDetailFee o1, JkxlDetailFee o2) {
                return o1.getWbsCode().compareTo(o2.getWbsCode());
            }
        });
        return list1;
    }

    //项目删除
    @ResponseBody
    @RequestMapping(value = "delete")
    public AjaxJson delete(WbsProject wbsProject) {
        AjaxJson j = new AjaxJson();
        projectService.delete(wbsProject);
        j.setMsg("删除项目成功");
        return j;
    }

    @RequestMapping(value = "tolist")
    public String toList(){
        return "redirect:/a/project/list";
    }



    /**
     * 创建项目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;
    }

}
