package com.jeeplus.modules.sg.managementcenter.reserveManagement.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.act.service.ActProcessService;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.filing.basicInformation.entity.BasicInformation;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.entity.PersonnelTurnover;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.entity.ReserveProcess;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.service.PersonnelTurnoverService;
import com.jeeplus.modules.sg.managementcenter.reserveManagement.service.ReserveProcessService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.test.one.dialog.entity.Leave1;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.shiro.authz.annotation.Logical;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 项目规模 Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/managementCenter/personnelTurnover")
public class PersonnelTurnoverController extends BaseController {

    @Autowired
    private PersonnelTurnoverService service;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ActProcessService actProcessService;

    @Autowired
    private ActTaskService actTaskService;

    @Autowired
    private ReserveProcessService reserveProcessService;


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

    /**
     * 项目规模信息列表页面
     * @param personnelTurnover
     * @param model
     * @return
     */
    @RequiresPermissions("sg:reserve:personnelTurnover:list")
    @RequestMapping(value = "list")
    public String skipList(PersonnelTurnover personnelTurnover, Model model) {
        model.addAttribute("personnelTurnover", personnelTurnover);
        return "modules/sg/managementcenter/reserveManagement/personnelTurnoverList";
    }

    /**
     * 项目规模信息数据列表
     * @param personnelTurnover
     * @param request
     * @param response
     * @param model
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:personnelTurnover:list")
    @RequestMapping(value = "data")
    public Map<String, Object> basicData(PersonnelTurnover personnelTurnover, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<PersonnelTurnover> page = service.findPage(new Page<PersonnelTurnover>(request, response), personnelTurnover);
        return getBootstrapData(page);
    }

    /**
     * 专职人员增加，编辑表单页面
     * @param personnelTurnover
     * @param model
     * @return
     */
    @RequiresPermissions(value={"sg:reserve:personnelTurnover:add","sg:reserve:personnelTurnover:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(PersonnelTurnover personnelTurnover, Model model) {
        model.addAttribute("personnelTurnover", personnelTurnover);
        return "modules/sg/managementcenter/reserveManagement/personnelTurnoverForm";
    }

    /**
     * 保存表单
     * @param personnelTurnover
     * @return
     */
    @ResponseBody
    @RequiresPermissions(value={"sg:reserve:personnelTurnover:add","sg:reserve:personnelTurnover:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(PersonnelTurnover personnelTurnover){
        AjaxJson j = new AjaxJson();
        /**
         * 后台hibernate-validation插件校验
         */
        String errMsg = beanValidator(personnelTurnover);
        if (StringUtils.isNotBlank(errMsg)){
            j.setSuccess(false);
            j.setMsg(errMsg);
            return j;
        }
        //新增或编辑表单保存
        //通过储备项目编号
        service.save(personnelTurnover);//保存
        j.setSuccess(true);
        j.setMsg("保存项目规模信息成功");
        return j;
    }


    /**
     *
     */
    @ResponseBody
    @RequiresPermissions(value={"sg:reserve:personnelTurnover:del"},logical=Logical.OR)
    @RequestMapping(value = "deleteAll")
    public AjaxJson delete(String ids){
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
        for(String id : idArray){
            service.delete(service.get(id));
        }
        j.setMsg("删除项目规模信息成功");
        return j;
    }

   

    /**
     * 经理导入Excel数据
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:personnelTurnover:import")
    @RequestMapping(value = "import")
    public AjaxJson jlImportBasic(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            StringBuffer stringBuffer = new StringBuffer();
            List<PersonnelTurnover> list = ei.getDataList(PersonnelTurnover.class);
            for (PersonnelTurnover s :
                    list) {
                //通过储备项目名称查询项目信息
                PersonnelTurnover byProjectId = service.findByProjectId(s);

                if (null == byProjectId) {
                    s.preInsert();
                    s.setOpenProcessStatus("1");
                    service.insert(s);
                    ReserveProcess reserveProcess = new ReserveProcess();
                    reserveProcess.preInsert();
                    reserveProcess.setProjectReserveId(s.getProjectReserveId());
                    //更新
                    reserveProcessService.insert(reserveProcess);
                    //发送流程，更改项目状态
                    Map<String, Object> vars = Maps.newHashMap();
                    vars.put("manager", UserUtils.getByUserName(s.getDesignUnit()).getLoginName());
                    String procDefId = projectService.findDefId("cbry");
                    ProcessDefinition p = actProcessService.getProcessDefinition(procDefId);
                    String title = s.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                    actTaskService.startProcess(p.getKey(), "cb_personnel_activiti", reserveProcess.getId(), title, vars);
                } else {
                    //当有项目信息时，判断是否在流程中
                    if ("1".equals(byProjectId.getOpenProcessStatus())) {
                        stringBuffer.append(s.getProjectReserveId() + "流程已开启;");
                    }else {
                        s.setOpenProcessStatus("1");
                        s.preUpdate();
                        service.update(s);
                        //添加流程数据条数
                        ReserveProcess reserveProcess = new ReserveProcess();
                        reserveProcess.preInsert();
                        reserveProcess.setProjectReserveId(s.getProjectReserveId());
                        //更新
                        reserveProcessService.insert(reserveProcess);
                        //发送流程，更改项目状态
                        Map<String, Object> vars = Maps.newHashMap();
                        vars.put("manager", UserUtils.getByUserName(s.getDesignUnit()).getLoginName());
                        String procDefId = projectService.findDefId("cbry");
                        ProcessDefinition p = actProcessService.getProcessDefinition(procDefId);
                        String title = s.getCurrentUser().getName() + "在" + DateUtils.getDateTime() + "发起" + p.getName();
                        actTaskService.startProcess(p.getKey(), "cb_personnel_activiti", reserveProcess.getId(), title, vars);
                    }
                }
            }
            j.setSuccess(true);
            j.setMsg("已成功导入" + stringBuffer);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入项目规模信息失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    //导出excel
    @ResponseBody
    @RequiresPermissions("sg:reserve:personnelTurnover:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(PersonnelTurnover personnelTurnover, HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "人员流转信息"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<PersonnelTurnover> page = service.findPage(new Page<PersonnelTurnover>(request, response, -1), personnelTurnover);
            new ExportExcel("人员流转信息", PersonnelTurnover.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出人员流转信息记录失败！失败信息："+e.getMessage());
        }
        return j;
    }

   
    /**
     * 下载导入模板
     */
    @ResponseBody
    @RequiresPermissions("sg:reserve:personnelTurnover:import")
    @RequestMapping(value = "template")
    public AjaxJson importTemplate(HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "项目规模信息导入模板.xlsx";
            List<BasicInformation> list = Lists.newArrayList();
            new ExportExcel("项目规模信息表", PersonnelTurnover.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
        }
        return j;
    }

    

}
