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

import com.alibaba.fastjson.JSONArray;
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;
    @Autowired
    private ItemService itemService;


    /**
     * 工程项目数据
     */
    @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);
        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;
    }

    /**
     * 工程项目信息修改
     * @param wbsProject  工程信息
     * @param ids  项目ID
     * @param units 项目供应商
     * @return
     */
    @ResponseBody
    @RequestMapping("/update")
    public Map update(WbsProject wbsProject,String ids,String units){
        Map map = new HashMap();
        WbsItem wbsItem = null;
        List<WbsItem> list = new ArrayList<>();
        try {
            String[] id = ids.split(",");
            String[] unit = units.split(",");
            for (int i = 0; i < id.length; i++) {
                wbsItem = new WbsItem();
                wbsItem.setId(id[i]);
                wbsItem.setUnit(unit[i]);
                list.add(wbsItem);
            }
            projectService.update(wbsProject, list);
        }catch (Exception e){
            map.put("code",0);
            map.put("msg","修改失败");
            return map;
        }
        map.put("code",1);
        map.put("msg","修改成功");
        return map;
    }

    /**
     *数据导入
     */
    @RequestMapping("/import")
    public String importFile(MultipartFile file,WbsItem wbsItem, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) throws IOException, InvalidFormatException {
        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;
        }   catch (Exception e){
            addMessage(redirectAttributes, "导入失败,"+e.getMessage());
            return "redirect:/a/project/list";
        }
    }



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

        }
        //写入EXCAL
        exportUtil.write(response,fileName).dispose();
        return "redirect:/a/project/list";
    }

    /**
     * 诚信扣款调整页面
     */
    @RequestMapping("withholdform")
    public String withholdForm(String id,Model model){
        WbsProject wbsProject = projectService.get(id);
        List<WbsItem> list = null;
        if(wbsProject != null){
            list = wbsProject.getWbsItems();
        }
        model.addAttribute("list",list);
        return "modules/sg/project/withholdForm";
    }

    /**
     * 甲供调整页面
     */
    @RequestMapping("materialOffsetForm")
    public String materialOffsetForm(String id,Model model){
        WbsProject wbsProject = projectService.get(id);
        List<WbsItem> list = null;
        if(wbsProject != null){
            list = wbsProject.getWbsItems();
        }
        model.addAttribute("list",list);
        return "modules/sg/project/materialOffsetForm";
    }

    /**
     * 税金页面
     */
    @RequestMapping("taxDeductionsForm")
    public String taxDeductionsForm(String id,Model model){
        WbsProject wbsProject = projectService.get(id);
        List<WbsItem> list = null;
        if(wbsProject != null){
            list = wbsProject.getWbsItems();
        }
        model.addAttribute("list",list);
        return "modules/sg/project/taxDeductionsForm";
    }

    /**
     * 添加诚信扣款、甲供材超供抵扣工程款、税金处理
     * @param ids
     * @param fees
     * @param unitTypes
     * @param decFunds
     * @param texs
     * @return
     */
    @ResponseBody
    @RequestMapping("withhold")
    public AjaxJson withhold(String ids,String fees,String unitTypes,String decFunds,String texs){
        AjaxJson j = new AjaxJson();
        List<WbsItem> ts = new ArrayList<>();
        WbsItem wbsItem = null;
        try {
            String[] idArr = ids.split(",");
            String[] feeArr = fees.split(",");
            String[] unitTypeArr = unitTypes.split(",");
            String[] decFundArr = decFunds.split(",");
            String[] texArr = texs.split(",");
            for(int i=0;i<idArr.length;i++){
                wbsItem = new WbsItem();
                wbsItem.setId(idArr[i]);
                //是否扣款 （1：扣 0：不扣）
//                wbsItem.setState("1");
                String unitType = unitTypeArr[i];
                if(unitType.equals("null")){
                    unitType = null;
                }
                wbsItem.setUnitType(unitType);
                String fee = feeArr[i];
                if(fee.equals("null")){
                    wbsItem.setIntegrityFee(null);
                }else {
                    wbsItem.setIntegrityFee(Double.valueOf(fee));
                }
                String decFund = decFundArr[i];
                if(decFund.equals("null")){
                    wbsItem.setDecFund(null);
                }else{
                    wbsItem.setDecFund(Double.valueOf(decFund));
                }
                String tex = texArr[i];
                if(tex.equals("null")){
                    wbsItem.setTexDeal(null);
                }else{
                    wbsItem.setTexDeal(Double.valueOf(tex));
                }

                ts.add(wbsItem);

            }
            itemService.updateFee(ts);
            j.setSuccess(true);
            j.setMsg("操作成功");
        }catch (Exception e){
            j.setSuccess(false);
            j.setMsg("操作失败");
        }
        return j;
    }



    /**
     * list中 所有wbs编码一样的JkxlDetailFee对象只保留一个，且相同wbs对象的“安装费”、“建筑费”、“其他费”、“合计”等费用合并
     * @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 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;
                       jkxlDetailFee1.setJzFee(jzFee+jzFee1);
                       jkxlDetailFee1.setAzFee(azFee+azFee1);
                       jkxlDetailFee1.setQtFee(qtFee+qtFee1);
                       jkxlDetailFee1.setTotalFee(totalFee+totalFee1);
                   }
               }
           }
       }
       //按照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);
    }
}
