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.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.overheadline.entity.JkxlDetailFee;
import com.jeeplus.modules.sg.overheadline.entity.Settlement;
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.project.util.ExportUtil;
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.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;
    @Autowired
    private SubstationService substationService;



    @RequestMapping(value = {"list", ""})
    public String list(WbsProject wbsProject, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<WbsProject> page = projectService.findPage(new Page<WbsProject>(request, response), wbsProject);
//       List<WbsProject> list =  projectService.findList(wbsProject);
       model.addAttribute("page",page);
        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,WbsItem wbsItem, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) throws IOException, InvalidFormatException {
//        String type = wbsItem.getType();   //项目类型
        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;
//        } catch (RuntimeException e) {
//            addMessage(redirectAttributes, "导入失败,"+e.getMessage());
//            return "redirect:/a/project/list";
//        }   catch (Exception e){
//            addMessage(redirectAttributes, "导入失败");
//            return "redirect:/a/project/list";
//        }
//        return "redirect:/a/jkxl/list?id="+id;
    }

    //导出
    @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());
            for (int i=0;i<jkxlDetailFees.size();i++){
                jkxlDetailFees.get(i).setIndex(i+1);
            }
            exportUtil.setDataList(jkxlDetailFees,j+1);
        }
        exportUtil.write(response,fileName).dispose();
        return "redirect:/a/project/list";
    }



    //导出
    @RequestMapping("/exportone")
    public String exportone(HttpServletRequest request,Model model,HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        WbsProject wbsProject = projectService.get(id);
        String fileName = wbsProject.getProjectNo()+wbsProject.getProjectName()+".xlsx";
        List<WbsItem> wbsItems = wbsProject.getWbsItems();
        List<WbsItem> wbsItems1 = new ArrayList<>();
        for(WbsItem wbsItem : wbsItems){
            if(!wbsItems1.contains(wbsItem)){
                wbsItems1.add(wbsItem);
            }
        }
        String[] sts = new String[wbsItems1.size()+1];
        sts[0] = "合计";
        for (int i=0;i<wbsItems1.size();i++){
            sts[i+1] = wbsItems1.get(i).getUnit();
        }
        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);
        //分别写入项目
        int count = 0;
        for(int j=0;j<wbsItems.size();j++){
            String unit = wbsItems.get(j).getUnit();
            if(unit != null) {
                List<JkxlDetailFee> jkxlDetailFees = overheadLineService.findList(wbsItems.get(j).getId(), wbsItems.get(j).getType());
                for (int k = j + 1; k < wbsItems.size(); k++) {
                    if (unit.equals(wbsItems.get(k).getUnit())) {
                        wbsItems.get(k).setUnit(null);
                        List<JkxlDetailFee> jkxl = overheadLineService.findList(wbsItems.get(k).getId(), wbsItems.get(k).getType());
                        jkxlDetailFees.addAll(jkxl);
                    }
                }
                count++;
                List<JkxlDetailFee> list2 = getNewList(jkxlDetailFees);
                for (int i=0;i<list2.size();i++){
                    list2.get(i).setIndex(i+1);
                }
                exportUtil.setDataList(list2,count);
            }

        }
        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 jzFee = jkxlDetailFee1.getJzFee()!=null? jkxlDetailFee1.getJzFee():0.00;
                       double jzFee1 = jkxlDetailFee.getJzFee()!=null? jkxlDetailFee.getJzFee():0.00;
//                       double sbgzFee = jkxlDetailFee1.getSbgzFee()!=null? jkxlDetailFee1.getSbgzFee():0.00;
//                       double sbgzFee1 = jkxlDetailFee.getSbgzFee()!=null? jkxlDetailFee.getSbgzFee():0.00;
                       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.setJzFee(jzFee+jzFee1);
//                       jkxlDetailFee1.setSbgzFee(sbgzFee+sbgzFee1);
                       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;
    }

    /**
     * 删除
     */
    @RequestMapping("/deleteProject")
    @ResponseBody
    public AjaxJson deleteProject(WbsProject wbsProject){
      return projectService.deleteProject(wbsProject);
    }
}
