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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.base.Strings;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.workperformance.entity.WorkPerformance;
import com.jeeplus.modules.workperformance.service.WorkPerformanceService;

/**
 * 公司业绩库Controller
 * @author ssrh
 * @version 2018-08-20
 */
@Controller
@RequestMapping(value = "${adminPath}/workperformance/workPerformance")
public class WorkPerformanceController extends BaseController {

	@Autowired
	private WorkPerformanceService workPerformanceService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private HttpServletRequest request;
	@ModelAttribute
	public WorkPerformance get(@RequestParam(required=false) String id) {
		WorkPerformance entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workPerformanceService.get(id);
		}
		if (entity == null){
			entity = new WorkPerformance();
		}
		return entity;
	}
	
	/**
	 * 公司业绩库列表页面
	 */
	@RequiresPermissions("workperformance:workPerformance:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkPerformance workPerformance, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkPerformance> page = workPerformanceService.findPage(new Page<WorkPerformance>(request, response), workPerformance); 
		model.addAttribute("page", page);
		return "modules/workperformance/workPerformanceList";
	}

	/**
	 * 查看，增加，编辑公司业绩库表单页面
	 */
	@RequiresPermissions(value={"workperformance:workPerformance:view","workperformance:workPerformance:add","workperformance:workPerformance:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkPerformance workPerformance, Model model) {
		model.addAttribute("workPerformance", workPerformance);
		String view=request.getParameter("tabId");
		if(StringUtils.isNotBlank(view) && view.equals("view")){
			return "modules/workperformance/workPerformanceView";
		}
		return "modules/workperformance/workPerformanceForm";
	}

	/**
	 * 保存公司业绩库
	 */
	@RequiresPermissions(value={"workperformance:workPerformance:add","workperformance:workPerformance:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkPerformance workPerformance, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workPerformance)){
			return form(workPerformance, model);
		}
		if(!workPerformance.getIsNewRecord()){//编辑表单保存
			WorkPerformance t = workPerformanceService.get(workPerformance.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workPerformance, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workPerformanceService.save(t);//保存
		}else{//新增表单保存
			workPerformanceService.save(workPerformance);//保存
		}
		addMessage(redirectAttributes, "保存公司业绩库成功");
		return "redirect:"+Global.getAdminPath()+"/workperformance/workPerformance/?repage";
	}
	
	/**
	 * 删除公司业绩库
	 */
	@RequiresPermissions("workperformance:workPerformance:del")
	@RequestMapping(value = "delete")
	public String delete(WorkPerformance workPerformance, RedirectAttributes redirectAttributes) {
		workPerformanceService.delete(workPerformance);
		addMessage(redirectAttributes, "删除公司业绩库成功");
		return "redirect:"+Global.getAdminPath()+"/workperformance/workPerformance/?repage";
	}
	
	/**
	 * 批量删除公司业绩库
	 */
	@RequiresPermissions("workperformance:workPerformance:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workPerformanceService.delete(workPerformanceService.get(id));
		}
		addMessage(redirectAttributes, "删除公司业绩库成功");
		return "redirect:"+Global.getAdminPath()+"/workperformance/workPerformance/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workperformance:workPerformance:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkPerformance workPerformance, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "公司业绩库"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkPerformance> page = workPerformanceService.findPage(new Page<WorkPerformance>(request, response, -1), workPerformance);
    		new ExportExcel("公司业绩库", WorkPerformance.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出公司业绩库记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workperformance/workPerformance/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workperformance:workPerformance:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkPerformance> list = ei.getDataList(WorkPerformance.class);
			for (WorkPerformance workPerformance : list){
				try{
					workPerformance.setCompanyId(UserUtils.getSelectCompany().getId());
					workPerformance.setOfficeId(UserUtils.getSelectOffice().getId());
					workPerformance.setSource("导入");
					workPerformanceService.save(workPerformance);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条公司业绩库记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条公司业绩库记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入公司业绩库失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workperformance/workPerformance/?repage";
    }
	
	/**
	 * 下载导入公司业绩库数据模板
	 */
	@RequiresPermissions("workperformance:workPerformance:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "公司业绩库数据导入模板.xlsx";
    		List<WorkPerformance> list = Lists.newArrayList(); 
    		new ExportExcel("公司业绩库数据", WorkPerformance.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workperformance/workPerformance/?repage";
    }

	@RequestMapping(value = "projectIds")
	@ResponseBody
	public AjaxJson projectIds(String ids, RedirectAttributes redirectAttributes) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		AjaxJson ajaxJson = new AjaxJson();
		if(Global.isDemoMode()){
			ajaxJson.setSuccess(false);
			return ajaxJson;
		}
		try {
			String[] arrid = ids.split(",");
			StringBuilder msg = new StringBuilder();
			//int newNum = 0;
			for (String id:arrid){
				if(StringUtils.isNotBlank(id)){
					ProjectRecords p = projectRecordsService.getQueryProjectUsers(id);
					if(p!=null){
						WorkPerformance workPerformance = new WorkPerformance();
						workPerformance.setCompanyId(p.getCompany().getId());
						workPerformance.setOfficeId(p.getOffice().getId());
						workPerformance.setNum(p.getWorkContractInfo().getContractNum());
						workPerformance.setName(p.getProjectName());
						workPerformance.setClient(p.getClientName());
						workPerformance.setContent(p.getProjectDesc());//工程概况
						workPerformance.setType(DictUtils.getMainDictLabel(p.getWorkContractInfo().getContractType(),"contract_type",""));
						if(p.getWorkContractInfo().getEffectiveDate()!=null && p.getWorkContractInfo().getClosingDate()!=null){
							workPerformance.setServiceDate(formatter.format(p.getWorkContractInfo().getEffectiveDate())+"-"+formatter.format(p.getWorkContractInfo().getClosingDate()));
						}
						workPerformance.setContractPrice(p.getContractPrice());
						workPerformance.setInvestmentAmount(p.getWorkContractInfo().getInvestmentAmount());
						if(StringUtils.isNotBlank(p.getScaleType()) && p.getScaleQuantity()!=null){
							workPerformance.setScaleQuantity(p.getScaleType()+"/"+p.getScaleQuantity());
						}else if(StringUtils.isNotBlank(p.getScaleType()) && p.getScaleQuantity()==null){
							workPerformance.setScaleQuantity(p.getScaleType());
						}else if(StringUtils.isBlank(p.getScaleType()) && p.getScaleQuantity()!=null){
							workPerformance.setScaleQuantity(""+p.getScaleQuantity());
						}
						if(StringUtils.isNotBlank(p.getWorkContractInfo().getClient().getName()) && StringUtils.isNotBlank(p.getWorkContractInfo().getClient().getTelephone())){
							workPerformance.setLinkman(p.getWorkContractInfo().getClient().getName()+"+"+p.getWorkContractInfo().getClient().getTelephone());
						}else if(StringUtils.isNotBlank(p.getWorkContractInfo().getClient().getName()) && StringUtils.isBlank(p.getWorkContractInfo().getClient().getTelephone())){
							workPerformance.setLinkman(p.getWorkContractInfo().getClient().getName());
						}else if(StringUtils.isBlank(p.getWorkContractInfo().getClient().getName()) && StringUtils.isNotBlank(p.getWorkContractInfo().getClient().getTelephone())){
							workPerformance.setLinkman(p.getWorkContractInfo().getClient().getTelephone());
						}

						if("0".equals(p.getWorkContractInfo().getExt())){
							workPerformance.setContractSource("投标项目");
						}else{
							workPerformance.setContractSource("非投标项目");
						}
						workPerformance.setOfficeName(p.getWorkContractInfo().getChargeCompanyName());
						workPerformance.setProjectLeaders(p.getLeaderNameStr());
						if(StringUtils.isBlank(p.getWorkContractInfo().getRecordState())){
							workPerformance.setRecord("待归档");
						}else{
							workPerformance.setRecord(DictUtils.getDictLabel(p.getWorkContractInfo().getRecordState(),"record_state",""));
						}
						workPerformance.setSource("引用");
						List<WorkClientAttachment> workAttachments = p.getWorkContractInfo().getWorkAttachments();
						List<WorkClientAttachment> workAttachment = new ArrayList<>();
						for (WorkClientAttachment w:
							 workAttachments) {
							WorkClientAttachment workClientAttachment = new WorkClientAttachment();
							workClientAttachment.setUrl(w.getUrl());
							workClientAttachment.setType(w.getType());
							workClientAttachment.setAttachmentName(w.getAttachmentName());
							workAttachment.add(workClientAttachment);
						}
						workPerformance.setWorkAttachments(workAttachment);
						workPerformance.setId("");
						workPerformanceService.save(workPerformance);
					}
				}
			}
			addMessage(redirectAttributes, "引用成功");
			ajaxJson.setMsg("引用成功");
		}catch (Exception e){
			ajaxJson.setMsg("引用失败");
		}

		return ajaxJson;
	}
	

}