package com.nbclass.szxgl.controller.mobile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbclass.system.controller.BaseController;
import com.nbclass.szxgl.model.ListType;
import com.nbclass.szxgl.model.Project;
import com.nbclass.szxgl.model.ProjectFiles;
import com.nbclass.szxgl.service.ProjectClientService;
import com.nbclass.szxgl.service.ProjectService;
import com.nbclass.util.MemoryCacheUtil;
import com.nbclass.util.ResultUtil;
import com.nbclass.vo.base.PageResultVo;
import com.nbclass.vo.base.ResponseVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author Leon
 * @datetime 2019年4月24日 下午4:27:39
 */
@Controller
@RequestMapping("/mobile/api/project")
public class ProjectController extends BaseController {

	@Resource
	private ProjectService service;

	@Resource
	private ProjectClientService projectClientService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

	/**
	 * 获取项目列表
	 *
	 * @param entity
	 * @param limit  每页数量
	 * @param offset 页码
	 * @return
	 */
	@RequestMapping("/getList")
	@ResponseBody
	public PageResultVo getList(Project entity, String userIds, @RequestParam(defaultValue = "10") Integer limit,
			@RequestParam(defaultValue = "1") Integer offset) {
		if (StringUtils.isNotBlank(entity.getDeptId())) { // 根据部门id查询，查询出所有部门/子部门成员id
			// 注意，分页查询中，子查询不能在PageHelper.startPage内，否则分页会失效，service.getList会返回所有数据
			entity.setDeptUserIds(service.selectUserIdsByDeptId(entity.getDeptId()));
		}
		if (StringUtils.isNotBlank(userIds)) { // 根据成员id查询，把id全部到到DeptUserIds内
			List<String> deptUserIds = null;
			if(entity.getDeptUserIds()!=null) {
				//AbstractList中的add方法系统并没有给我们默认实现，而是直接抛出java.lang.UnsupportedOperationException,需要强行转化
				//使用ArrayList（ java.util.ArrayList）的构造方法去创建
				deptUserIds = new ArrayList<>(entity.getDeptUserIds());
			}
//			logger.info("从数据库查询部门用户信息："+ JSON.toJSONString(deptUserIds));
			if(deptUserIds==null)deptUserIds=new ArrayList<>();
			deptUserIds.addAll(Arrays.asList(userIds.split(",")));
//			logger.info("最终保存用户信息："+JSON.toJSONString(deptUserIds));
			entity.setDeptUserIds(deptUserIds);
		}

		PageHelper.startPage(offset, limit);
		List<Project> list = service.getList(entity);
		if(list!=null && !list.isEmpty()){
			String loginId = StringUtils.trimToEmpty(getLoginUserIdStr());
			for (Project p : list) {
				boolean allowModify = (p!=null && p.getStatus()!=null && p.getStatus()!=0); // 0为作废状态，不给修改
				if(allowModify && p!=null && StringUtils.isNotBlank(p.getFzrIds())){
					List<String> fzrIds = Arrays.asList(p.getFzrIds().split(","));
					allowModify = StringUtils.equals(loginId, p.getCreateUserId()) || fzrIds.contains(loginId);
				}
				p.setAllowModify(allowModify);
			}
		}
		PageInfo<Project> pages = new PageInfo<>(list, limit);
		return ResultUtil.table(list, pages.getTotal());
	}

	/**
	 * 根据ID查询项目详情记录
	 *
	 * @param id
	 */
	@RequestMapping("/findById")
	@ResponseBody
	public ResponseVo findById(String id) {
		JSONObject obj = service.findById(id);
		return ResultUtil.success(obj);
	}

	/**
	 * 获取项目任务列表
	 *
	 * @param pid
	 * @param limit
	 * @param offset
	 */
	/*
	@RequestMapping("/task/getList")
	@ResponseBody
	public void selectProjectTaskList(String pid, @RequestParam(defaultValue = "100") Integer limit,
			@RequestParam(defaultValue = "1") Integer offset) {
		PageHelper.startPage(PageUtil.getPageNo(limit, offset), limit);
		List<ProjectTask> list = service.getTaskList(pid);
		PageInfo<ProjectTask> pages = new PageInfo<>(list);
		JSONObject obj = new JSONObject();
		JSONObject pageObj = toJSON(ResultUtil.table(list, pages.getTotal()));
		obj.putAll(pageObj);
		boolean allowModify = service.hasPowerForTask(pid);
		obj.put("allowModify", allowModify);
		outPrint(obj);
	}
	*/

	/**
	 * 获取项目任务进度日志列表
	 *
	 * @param taskId
	 */
	/*
	@RequestMapping("/task/journal/getList")
	@ResponseBody
	public void selectProjectTaskJournalList(String taskId) {
		List<ProjectTaskJournal> list = service.getTaskJournalList(taskId);
		JSONObject obj = new JSONObject();
		obj.put("rows", list);
		outPrint(obj);
	}
	*/

	/**
	 * 获取select枚举列表 -- 用于移动端查询地区列表
	 * @param listType 地域列表:333
	 */
	@RequestMapping("/getListValues")
	@ResponseBody
	public JSONObject selectListValues(String listType) {
		List<ListType> list = service.getListValues(listType);
		JSONObject obj = new JSONObject();
		obj.put("ret", 0);
		obj.put("rows", list);
		return obj;
	}

	/**
	 * 添加项目
	 *
	 * @param p
	 * @param errors
	 * @param isSendMsg
	 * @param deptIds
	 * @return
	 */

	@RequestMapping("add")
	@ResponseBody
	public ResponseVo add(@Valid Project p, Errors errors, Integer isSendMsg, String[] deptIds, String filesList) {
		if (errors.hasErrors()) {
			return ResultUtil.error ("参数验证失败");
		}
		List<ProjectFiles> projectFiles = null;
		if(StringUtils.isNotBlank(filesList)) {
			filesList = filesList.replaceAll(" ", "");
			projectFiles = JSONArray.parseArray(filesList, ProjectFiles.class);
		}
		String projectId = service.addProject(p, isSendMsg, deptIds, projectFiles);
		return ResultUtil.success("success", projectId);

	}

	/**
	 * 修改项目
	 *
	 * @param p
	 * @param errors
	 * @param isSendMsg
	 * @param deptIds
	 */
	@RequestMapping("update")
	@ResponseBody
	public ResponseVo update(@Valid Project p, Errors errors, Integer isSendMsg, String[] deptIds, String filesList) {
		if (errors.hasErrors()) {
			return ResultUtil.error ("参数验证失败");
		}
		List<ProjectFiles> projectFiles = null;
		if(StringUtils.isNotBlank(filesList)) {
			filesList = filesList.replaceAll(" ", "");
			projectFiles = JSONArray.parseArray(filesList, ProjectFiles.class);
		}
		service.updateProject(p, isSendMsg, deptIds, projectFiles);
		return ResultUtil.success("success");
	}

	/**
	 * 删除项目
	 * @param ids
	 */
	@RequestMapping("del")
	@ResponseBody
	public ResponseVo delete(String[] ids) {
		service.deleteProject(ids);
		return ResultUtil.success("success");
	}

	/**
	 * 通过userid查询上级用户，包括负责人和抄送人
	 * @param userIds
	 * @return
	 */
	@RequestMapping("selectLeaderUsers")
	@ResponseBody
	public ResponseVo selectLeaderUsers(String userIds, String isZxrIds) {
		JSONObject obj = new JSONObject();
		if("true".equals(StringUtils.trimToEmpty(isZxrIds))) {
			List<Map<String, Object>> zxrMap = service.selectZxrUserObj(userIds);
			obj.put("zxrData",zxrMap);
		} else {
			JSONArray csrMap = service.selectLeaderUserObj(userIds, true); // 抄送人查询出所有上级
		//	JSONArray fzrMap = service.selectLeaderUserObj(userIds, false); // 负责人只查询选择用户的上级
		//	obj.put("fzrData", fzrMap); // 负责人数据。 后面改成负责人不自动添加上级，选择谁就是谁
			obj.put("csrData", csrMap); // 抄送人数据
		}
		return ResultUtil.success(obj);
	}

	/**
	 * 获取客户单位列表
	 */
	@RequestMapping("getCustomerList")
	@ResponseBody
	public ResponseVo getCustomerList() {
		JSONArray array = MemoryCacheUtil.getT("api_customer_list");
		if(array == null || array.isEmpty()){
			array = projectClientService.getTreeList();
			MemoryCacheUtil.set("api_customer_list", array, 1000*60*3); // 缓存三分钟
		}
		return ResultUtil.success("success",array);
	}

	/**findProductById
	 * 获取负责人区域列表
	 */
	@RequestMapping("queryArea")
	@ResponseBody
	public ResponseVo queryArea(String userIds) {
        Map<String, Set<String>> stringSetMap = service.selectCityByUserIds(userIds);
        return ResultUtil.success("success", stringSetMap);
	}

	/**
	 * 更新项目状态
	 */
	@RequestMapping("updateStatus")
	@ResponseBody
	public ResponseVo updateProjectStatus(String id, String contractno, String status) {
		service.updateProjectStatus(id, contractno, status);
		return ResultUtil.success("success");
	}

}
