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

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
import com.jeeplus.modules.workstaff.dao.WorkStaffAchivesDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目登记Controller
 * @author ppt
 * @version 2018-05-02
 */
@Controller
	@RequestMapping(value = "${adminPath}/project/projectRecordUsers")
public class ProjectRecordsUserController extends BaseController {

	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private WorkStaffAchivesDao workStaffAchivesDao;

	@Autowired
	private WorkContractInfoService contractInfoService;
	@Autowired
	private WorkProjectUserDao workProjectUserDao;
	
	@ModelAttribute
	public ProjectRecords get(@RequestParam(required=false) String id) {
		ProjectRecords entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectRecordsService.get(id);
		}
		if (entity == null){
			entity = new ProjectRecords();
		}
		return entity;
	}
	
	/**
	 * 项目列表页面
	 */
	@RequiresPermissions("project:projectRecords:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProjectRecords projectRecords, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectRecords.setProjectStatus(5);
		Page<ProjectRecords> page = projectRecordsService.findPageByStatus(new Page<ProjectRecords>(request, response), projectRecords);
		model.addAttribute("page", page);
		return "modules/projectrecord/projectRecordUsersList";
	}

	/**
	 * 查看，增加，编辑项目表单页面
	 */
	@RequestMapping(value = "form")
	public String form(ProjectRecords projectRecords, Model model) {
		if (projectRecords!=null&&StringUtils.isNotBlank(projectRecords.getId())) {
			//设置合同信息
			WorkContractInfo workContractInfo = contractInfoService.get(projectRecords.getWorkContractInfo().getId());
			workContractInfo.setConstructionProjectTypeStr(DictUtils.getDictLabel(String.valueOf(workContractInfo.getConstructionProjectType()), "construction_project_type", ""));
			projectRecords.setWorkContractInfo(workContractInfo);
			//设置项目组成员
			projectRecordsService.queryUserNames(projectRecords);
			//设置委托方联系人信息
			projectRecordsService.queryLinkmanInfos(projectRecords);
			List<User> users = workProjectUserDao.isDelFalg(projectRecords.getId(),"");
			String userIds = "";
			String delUserIds = "";
			for (User user :users){
				if (user.getDelFlag().equals("0")){
					userIds += user.getId()+",";
				}else {
					delUserIds += user.getId()+",";
				}
			}
			projectRecords.setUserIds(userIds);
			projectRecords.setDelUserIds(delUserIds);
			model.addAttribute("users", users);
		}

		model.addAttribute("projectRecords", projectRecords);
		return "modules/projectrecord/projectRecordUsersForm";
	}
	/**
	 * 查看，增加，编辑项目表单页面
	 */
	@RequestMapping(value = "getProjectRecordUsers")
	@ResponseBody
	@Transactional(readOnly = false)
	public List<Map<String,Object>> getProjectRecordUsers(@RequestParam(required=false) String projectId,@RequestParam(required=false) String ids) {
		List<Map<String,Object>> list = new ArrayList<>();
		String[] idArr = ids.split(",");
		List<User> users = workProjectUserDao.isDelFalg(projectId,"");
		List<User> userList = new ArrayList<>();
		String userIds = "";
		String delUserIds = "";
		for (User user :users){
			if (user.getDelFlag().equals("0")){
				userIds += user.getId()+",";
			}else {
				if (ids.contains(user.getId())){
					delUserIds += user.getId()+",";
				}
			}
		}
		String names = "";
		for (String id : idArr){
			User user = UserUtils.get(id);
			Map<String,Object> map = new HashMap<>();
			if (!userIds.contains(id) && !delUserIds.contains(id)){
				userList.add(new User(id));
				map.put("id",StringUtils.isBlank(user.getId())?"":user.getId());
				map.put("name",StringUtils.isBlank(user.getName())?"":user.getName());
				map.put("officeId",StringUtils.isBlank(user.getOffice().getTopCompany())?"":user.getOffice().getTopCompany());
				map.put("no",StringUtils.isBlank(user.getNo())?"":user.getNo());
				map.put("mobile",StringUtils.isBlank(user.getMobile())?"":user.getMobile());
				map.put("email",StringUtils.isBlank(user.getEmail())?"":user.getEmail());
				map.put("msg","msg");
				WorkStaffBasicInfo workStaffBasicInfo=workStaffAchivesDao.getJob(id);
				if(workStaffBasicInfo!=null&&workStaffBasicInfo.getJobGrade()!=null){
					map.put("jobName",StringUtils.isBlank(workStaffBasicInfo.getJobGrade().getName())?"":workStaffBasicInfo.getJobGrade().getName());
				}
				list.add(map);
			}else if(delUserIds.contains(id)){
				map.put("id",StringUtils.isBlank(user.getId())?"":user.getId());
				map.put("msg","del");
				list.add(map);
			}else {
				names += StringUtils.isBlank(user.getName())?"":(user.getName()+",");
			}
		}

		if (userList!=null && userList.size()!=0){
			ProjectRecords projectRecords = new ProjectRecords();
			projectRecords.setId(projectId);
			projectRecords.setUsers(userList);
			workProjectUserDao.insertUsers(projectRecords);
		}
		if (delUserIds!=null){
			ProjectRecords projectRecords = new ProjectRecords();
			projectRecords.setId(projectId);
			for (String id :delUserIds.split(",")){
				projectRecords.setUserId(id);
				projectRecords.setDelFlag("0");
				workProjectUserDao.deleteUsers(projectRecords);
			}

		}
		if (StringUtils.isNotBlank(names)){
			Map<String,Object> map = new HashMap<>();
			names = names.substring(0,names.length()-1);
			names += "已在成员明细中！";
			map.put("msg",names);
			list.add(map);
		}
		return list;
	}

	/**
	 * 查看，增加，编辑项目表单页面
	 */
	@RequestMapping(value = "removeProjectRecordUsers")
	@ResponseBody
	@Transactional(readOnly = false)
	public Map<String,Object> removeProjectRecordUsers(@RequestParam(required=false) String projectId,@RequestParam(required=false) String userId) {
		ProjectRecords projectRecords = new ProjectRecords();
		projectRecords.setId(projectId);
		projectRecords.setUserId(userId);
		projectRecords.setDelFlag("1");
		int count = workProjectUserDao.deleteUsers(projectRecords);
		Map<String,Object> map = new HashMap<>();
		if (count == 1){
			map.put("msg",true);
		}else {
			map.put("msg",false);
		}
		return map;
	}
}