/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.fund.web;

import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActProcessService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sg.audit.information.entity.Information;
import com.jeeplus.modules.sg.audit.information.utils.RandomUtil;
import com.jeeplus.modules.sg.fund.entity.Fund;
import com.jeeplus.modules.sg.fund.service.FundService;
import com.jeeplus.modules.sg.managementcenter.activiti.entity.*;
import com.jeeplus.modules.sg.managementcenter.activiti.service.ConstructionService;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyImportUtils;
import com.jeeplus.modules.sg.managementcenter.constructionProject.entity.ConstructionProject;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialinfo.service.MaterialInfoService;
import com.jeeplus.modules.sg.managementcenter.materialproject.service.MaterialProjectService;
import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.materialmodule.activiti.entity.NonPower;
import com.jeeplus.modules.sg.materialmodule.activiti.service.NonPowerService;
import com.jeeplus.modules.sg.picking.activiti.entity.ShowList;
import com.jeeplus.modules.sg.picking.activiti.service.ShowListService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 施工交底Controller
 *
 * @author
 * @version 2019-11-08
 */
@Controller
@RequestMapping(value = "${adminPath}/fund")

public class FundController extends BaseController {
    @Autowired
    private FundService fundService;
    @Autowired
    private ActProcessService actProcessService;
    @Autowired
    private ActTaskService actTaskService;
    @Autowired
    private ProjectService projectService;

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

    /**
     * 项目转资信息管理页面
     */
    @RequestMapping(value = "fundList")
    @RequiresPermissions("sg:managementcenter:fundList:list")
    public String fundList(Fund fund, Model model) {
        model.addAttribute("fund", fund);
        return "modules/sg/fund/fundList";
    }

    /**
     * 转资流程开始选择项目页面
     */
    @RequestMapping(value = "fundStart")
    public String fundStart(Fund fund, Model model) {
        model.addAttribute("fund", fund);
        return "modules/sg/fund/fundStart";
    }

    /**
     * 转资流程填写wbs编码
     */
    @RequestMapping(value = "wbsForm")
    public String wbsForm(Fund fund, Model model) {
        model.addAttribute("fund", fund);
        return "modules/sg/fund/wbsForm";
    }

    /**
     * 转资流程填写资产卡片号
     */
    @RequestMapping(value = "assetForm")
    public String assetForm(Fund fund, Model model) {
        model.addAttribute("fund", fund);
        return "modules/sg/fund/assetForm";
    }

    @RequestMapping(value = "fundForm")
    public String form(Fund fund, Model model) {
        model.addAttribute("fund", fund);
        return "modules/sg/fund/fundForm";
    }

    /**
     * 项目管理列表数据
     */
    @ResponseBody
    @RequiresPermissions("modules:sg:information:information:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(Fund fund, HttpServletRequest request, HttpServletResponse response, Model model) {
        String projectId = fund.getProjectId();
        if (null != projectId && !"".equals(projectId)) {
            String[] strArr = projectId.split("\\s+");
            fund.setProjectIdList(strArr);
            fund.setProjectId("");
        }
        Page<Fund> page = fundService.findPage(new Page<Fund>(request, response), fund);
        return getBootstrapData(page);
    }

    /**
     * 转资修改
     */
    @ResponseBody
    @RequestMapping(value = "fundUpdate")
    public AjaxJson EngAmountSave(Fund fund, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        try {
//            constructionService.EngAmountSave(engineeringAmount);
//            fundService.fundUpdate();
            j.setSuccess(true);
            j.setMsg("修改成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("修改失败");
        }
        return j;
    }



    /**
     * 转资删除
     */
    @ResponseBody
    @RequestMapping(value = "delFund")
    public AjaxJson delFund(Fund fund) {
        AjaxJson j = new AjaxJson();
        fundService.delete(fund);
        j.setMsg("删除转资信息成功");
        return j;
    }

    /**
     * 修改成功
     */
    @ResponseBody
    @RequestMapping(value = "update")
    public AjaxJson update(Fund fund) {
        AjaxJson j = new AjaxJson();
        fundService.update(fund);
        j.setMsg("修改成功");
        return j;
    }

    /**
     * 发起转资流程
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxJson save(Fund fund, Model model) throws Exception {
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String projectId = fund.getProjectId();
        if (null == projectId || "".equals(projectId)) {
            j.setSuccess(false);
            j.setMsg("请选择项目");
            return j;
        }
        String errMsg = beanValidator(fund);
        if (StringUtils.isNotBlank(errMsg)) {
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        /**
         * 流程审批
         */
        if (StringUtils.isBlank(fund.getId())) {
            //获取流程图id
            String procDefId = fund.getAct().getProcDefId();
            //定义vars用于指派流程走向
            Map<String, Object> vars = Maps.newHashMap();
            Project project = new Project();
            project.setId(projectId);
            //获取选择的项目
            Project ass = projectService.getAss(project);
            if (null == ass) {
                j.setSuccess(false);
                j.setMsg("请选完善项目信息");
                return j;
            }
            if (null == ass.getAssignment()) {
                j.setSuccess(false);
                j.setMsg("请先填写人员信息");
                return j;
            }
            fund.setId("");
            fund.setProjectId(ass.getProjectId());
            fund.setProjectName(ass.getProjectName());
            fund.setReserveProjectName(ass.getReserveProjectName());
            fundService.save(fund);
            vars.put("manager", UserUtils.getByUserName(ass.getAssignment().getOwnerManager()).getLoginName());

            // 启动流程
            ProcessDefinition p = actProcessService.getProcessDefinition(fund.getAct().getProcDefId());
            String title = fund.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
            actTaskService.startProcessNew(p.getKey(), "xm_fund_process", fund.getId(), title, vars);
            //新增或编辑表单保存
            j.setMsg("发起流程审批成功!");
            j.getBody().put("targetUrl", "/act/task/process/");
        }
        return j;
    }

    /**
     * 转资提交wbs流程
     * */
    @ResponseBody
    @RequestMapping(value = "wbsTask")
    public AjaxJson wbsTask(Act act, String wbsEncoding,String wbsNumber) {
        AjaxJson j = new AjaxJson();
        try {
            fundService.updateWbs(wbsEncoding,wbsNumber, act.getProcInsId());
            String comment = URLDecoder.decode(act.getComment(), "UTF-8");
            act.setComment(comment);
            actTaskService.wbsTask(act);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        j.setMsg("审批成功");
        return j;
    }

    @ResponseBody
    @RequestMapping(value = "assetTask")
    public AjaxJson assetTask(Act act, String assetCardNumber) {
        AjaxJson j = new AjaxJson();
        try {
            if ("yes".equals(act.getFlag())) {
                fundService.updateAsset(assetCardNumber, act.getProcInsId());
            }
            String comment = URLDecoder.decode(act.getComment(), "UTF-8");
            act.setComment(comment);
            actTaskService.assetTask(act);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        j.setMsg("审批成功");
        return j;
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids) {
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
        fundService.deleteList(idArray);
        j.setMsg("删除项目运营管理成功");
        return j;
    }
}