package cn.com.countrygarden.bi.main.controller.performance;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.performance.AssessmentTarget;
import cn.com.countrygarden.bi.main.model.performance.PerformanceElement;
import cn.com.countrygarden.bi.main.model.performance.PerformanceTarget;
import cn.com.countrygarden.bi.main.model.performance.monthly.AssessmentMonthlyTarget;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.performance.*;

import cn.com.countrygarden.bi.main.util.ExcelAnalysis;

import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Logger;

/**
 * Created by tracy on 2018/4/3.
 */
@Controller("PerformanceController")
@RequestMapping("/api/biapp/marketing/backend/performance")
public class PerformanceController {

	@Autowired
	private AccessTokenService accessTokenService;

	@Autowired
	private PerformanceEnvService performanceEnvService;
	@Autowired
	private PerformanceElementService performanceElementService;
	@Autowired
	private PerformanceTargetService performanceTargetService;
	@Autowired
	private AssessmentTargetService assessmentTargetService;

	@Autowired
	private AssessmentMonthlyTargetService assessmentMonthlyTargetService;

	@Autowired
	private PerformanceCompanyService performanceCompanyService;

	@Autowired
	private PerformanceMonthlyService performanceMonthlyService;

	@Autowired
	private ExcelAnalysis ea;

	@ResponseBody
	@RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
	@Deprecated
	public Result upload(@RequestParam(value = "name", defaultValue = "1", required = true) String name,
			@RequestParam(value = "uploadfile", defaultValue = "", required = true) MultipartFile multipartFile,
			HttpServletRequest request, HttpServletResponse response) throws ServiceException {
		String accessToken = request.getParameter("AccessToken");
		AccessToken token = accessTokenService.findByToken(accessToken);
		if (multipartFile == null) {
			throw new ServiceException("请选择需要上传的文件");
		} else if (name == null) {
			throw new ServiceException("请输入文件名");
		}
		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
		if (commonsMultipartFile.isEmpty()) {
			return Response.responseFail("上传文件为空文件");
		}
		String fileName = commonsMultipartFile.getOriginalFilename();
		if (fileName.indexOf(".xlsx") <= 0 || fileName.indexOf(".xls") <= 0) {
			return Response.responseFail("上传文件应为excel文件格式为：xlsx 或 xls");
		}
		ea.excelToObject(multipartFile, name, token.getUserCode());

		return Response.response("导入成功");

	}

	@ResponseBody
	@RequestMapping(value = "/scoreDetail", method = { RequestMethod.POST, RequestMethod.GET })
	@Deprecated
	public Object scoreDatail(@RequestParam(value = "AccessToken") String AccessToken, Integer year,
			@RequestParam(value = "organList", required = false) String[] organList) {
		AccessToken token = this.accessTokenService.findByToken(AccessToken);
		if (token == null || token.getUserCode() == null) {
			return Response.response(ResultCode.UNAUTHORIZED);
		}
		return Response.response(this.performanceEnvService.selectEnvScoreInfo(organList, year, token.getUserCode()));
	}

	/**
	 * 我的考核-城市公司数据查询
	 *
	 * @param AccessToken
	 * @param year
	 * @param organList
	 * @return
	 * @Author:wyman
	 * @Date:2018/9/12
	 */
	@ResponseBody
	@RequestMapping(value = "/companyScoreDetail", method = { RequestMethod.POST, RequestMethod.GET })
	@Deprecated
	public Object scoreCompanyDetail(@RequestParam(value = "AccessToken") String AccessToken, Integer year,
			@RequestParam(value = "organList", required = false) String[] organList) {
		AccessToken token = this.accessTokenService.findByToken(AccessToken);
		if (token == null || token.getUserCode() == null) {
			return Response.response(ResultCode.UNAUTHORIZED);
		}

		return Response
				.response(this.performanceCompanyService.selectCompanyScoreInfo(organList, year, token.getUserCode()));
	}

	/**
	 * 绩效分析——区域
	 *
	 * @param AccessToken
	 *            accessToken
	 * @param element
	 *            指标
	 * @return Json
	 */
	@ResponseBody
	@RequestMapping(value = "/scoreList", method = { RequestMethod.GET, RequestMethod.POST })
	@Deprecated
	public Object scoreList(@RequestParam(value = "AccessToken") String AccessToken, String element) {
		AccessToken token = this.accessTokenService.findByToken(AccessToken);
		if (token == null || token.getUserCode() == null) {
			return Response.response(ResultCode.UNAUTHORIZED);
		}
		return Response.response(this.performanceEnvService.selectScoreList(element, token.getUserCode()));
	}

	/**
	 * 绩效分析——城市公司
	 *
	 * @param AccessToken
	 *            accessToken
	 * @param element
	 *            指标
	 * @return Json
	 */
	@ResponseBody
	@RequestMapping(value = "/companyScoreList", method = { RequestMethod.GET, RequestMethod.POST })
	@Deprecated
	public Object companyScoreList(@RequestParam(value = "AccessToken") String AccessToken, String element) {
		AccessToken token = this.accessTokenService.findByToken(AccessToken);
		if (token == null || token.getUserCode() == null) {
			return Response.response(ResultCode.UNAUTHORIZED);
		}
		return Response.response(this.performanceCompanyService.selectScoreCompanyList(element, token.getUserCode()));
	}

	/**
	 * 发布功能-区域
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/releasing", method = { RequestMethod.GET, RequestMethod.POST })
	@Deprecated
	public Object releasing() {
		// 得到区域最新的年，季度
		List<PerformanceTarget> yearQuarter = performanceTargetService.getNewYearQuarterOrgan();
		if (yearQuarter.isEmpty() && yearQuarter.size() == 0) {
			return null;
		}
		Integer year = yearQuarter.get(0).getYear();// 最新的年
		String quarterly = yearQuarter.get(0).getQuarterly();// 最新的季度
		// 查询区域是否全部锁定
		List<AssessmentTarget> unLockList = assessmentTargetService.selectUnLockOrgan(year, quarterly);
		Map<String, Object> result = new HashMap<>();// 返回前台的数据
		List<String> unLockUserNameList = new ArrayList<>();
		if (unLockList.size() > 0) {// 未完全锁定
			result.put("total", unLockList.size());// 条数
			for (AssessmentTarget unLockUserName : unLockList) {
				unLockUserNameList.add(unLockUserName.getElementname());
			}
			result.put("rows", unLockUserNameList);// 未锁定的指标名
			return Response.response(result);
		} else {// 如果完全锁定
			assessmentTargetService.updatePublicStatusOrgan(year, quarterly);// 更新发布状态
			// 返回给前台数据
			result.put("total", -1);// 表示修改完成
			result.put("rows", unLockUserNameList);// 为了所有判断返回数据都对应一致
			return Response.response(result);
		}
	}

	/**
	 * 发布功能-城市公司
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/companyReleasing", method = { RequestMethod.GET, RequestMethod.POST })
	@Deprecated
	public Object companyReleasing() {
		// 得到城市公司最新的年，季度
		Map<String, Object> yearQuarter = performanceTargetService.getNewYearQuarterCompany();
		Integer year = (Integer) yearQuarter.get("year");// 最新的年
		String quarterly = (String) yearQuarter.get("quarterly");// 最新的季度
		// 查询城市公司是否全部锁定
		List<AssessmentTarget> unLockList = assessmentTargetService.selectUnLockCompany(year, quarterly);
		Map<String, Object> result = new HashMap<>();// 返回前台的数据
		List<String> unLockUserNameList = new ArrayList<>();
		if (unLockList.size() > 0) {// 未完全锁定
			result.put("total", unLockList.size());// 条数
			for (AssessmentTarget unLockUserName : unLockList) {
				unLockUserNameList.add(unLockUserName.getElementname());
			}
			result.put("rows", unLockUserNameList);// 未锁定的指标名
			return Response.response(result);
		} else {// 如果完全锁定
			assessmentTargetService.updatePublicStatusCompany(year, quarterly);// 更新发布状态
			// 返回给前台数据
			result.put("total", -1);// 表示修改完成
			result.put("rows", unLockUserNameList);// 为了所有判断返回数据都对应一致
			return Response.response(result);
		}
	}

	/**
	 * 月度发布功能-区域
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/monthlyOrganReleasing", method = { RequestMethod.GET, RequestMethod.POST })
	public Object monthlyOrganReleasing() {
		// 获得月度区域的最新年、月
		Map<String, Integer> organMap = performanceMonthlyService.selectOrganYearAndMonth();
		if (organMap == null) {
			return Response.responseFail("月度表无区域相关数据!");
		}
		Integer year = organMap.get("year");
		Integer month = organMap.get("month");
		// 根据年月获得未锁定的区域List
		List<AssessmentMonthlyTarget> unLockOrganList = assessmentMonthlyTargetService.getUnLockOrgans(year, month);
		// 返回前台的数据
		Map<String, Object> returnMap = new HashMap<>();
		List<String> unLockOrganNames = new ArrayList<>();
		// 若List大于0，不能发布，返回未锁定的指标名称
		if (unLockOrganList.size() > 0) {
			for (AssessmentMonthlyTarget unLockOrgan : unLockOrganList) {
				PerformanceElement pe = performanceElementService.getElementNameById(unLockOrgan.getElementId());
				if (pe != null) {
					unLockOrganNames.add(pe.getName());
				}
			}
			returnMap.put("rows", unLockOrganNames);
			return Response.response(returnMap);
		} else {
			// 否则可以发布，更新发布状态
			assessmentMonthlyTargetService.updateOrganMonthlyPublicStatus(year, month);
			returnMap.put("total", -1);// 修改成功
			returnMap.put("rows", unLockOrganNames);
			return Response.response(returnMap);
		}
	}

	/**
	 * 月度发布功能-城市公司
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/monthlyCompanyReleasing", method = { RequestMethod.GET, RequestMethod.POST })
	public Object monthlyCompanyReleasing() {
		// 获得月度城市公司的最新年、月
		Map<String, Integer> comMap = performanceMonthlyService.selectCompanyYearAndMonth();
		if (comMap == null) {
			return Response.responseFail("月度表无城市公司数据!");
		}
		Integer year = comMap.get("year");
		Integer month = comMap.get("month");
		// 根据年月获得未锁定的城市公司List
		List<AssessmentMonthlyTarget> unLockCompanyList = assessmentMonthlyTargetService.getUnLockCompanys(year, month);
		// 返回前台的数据
		Map<String, Object> returnMap = new HashMap<>();
		List<String> unLockCompanyNames = new ArrayList<>();
		// 若List大于0，不能发布，返回未锁定的指标名称
		if (unLockCompanyList.size() > 0) {
			for (AssessmentMonthlyTarget unLockCompany : unLockCompanyList) {
				PerformanceElement pe = performanceElementService.getElementNameById(unLockCompany.getElementId());
				if (pe != null) {
					unLockCompanyNames.add(pe.getName());
				}
			}
			returnMap.put("rows", unLockCompanyNames);
			return Response.response(returnMap);
		} else {
			// 否则可以发布，更新发布状态
			assessmentMonthlyTargetService.updateCompanyMonthlyPublicStatus(year, month);
			returnMap.put("total", -1);
			returnMap.put("rows", unLockCompanyNames);
			return Response.response(returnMap);
		}
	}

	/**
	 * 发布状态-区域
	 *
	 * @return 状态信息
	 */
	@ResponseBody
	@RequestMapping(value = "/publicStatus", method = { RequestMethod.GET, RequestMethod.POST })
	@Deprecated
	public Object publicStatus() {
		// 得到最新的年，季度
		List<PerformanceTarget> yearQuarter = performanceTargetService.getNewYearQuarterOrgan();
		if (yearQuarter.isEmpty() && yearQuarter.size() == 0) {
			return null;
		}
		Integer year = yearQuarter.get(0).getYear();// 最新的年
		String quarterly = yearQuarter.get(0).getQuarterly();// 最新的季度
		// 查询最新季度是否发布了
		List<AssessmentTarget> lastPublic = assessmentTargetService.selectLastPublicOrgan(year, quarterly);
		Map<String, Integer> result = new HashMap<>();
		if (lastPublic.size() > 0) {
			result.put("status", 0);// 表示还没发布
		} else {
			result.put("status", 1);// 表示发布了
		}
		return Response.response(result);
	}

	/**
	 * 发布状态-城市公司
	 *
	 * @return 状态信息
	 */
	@ResponseBody
	@RequestMapping(value = "/companyPublicStatus", method = { RequestMethod.GET, RequestMethod.POST })
	@Deprecated
	public Object companyPublicStatus() {
		try {
			// 得到最新的年，季度
			Map<String, Object> yearQuarter = performanceTargetService.getNewYearQuarterCompany();
			Integer year = (Integer) yearQuarter.get("year");// 最新的年
			String quarterly = (String) yearQuarter.get("quarterly");// 最新的季度
			// 查询最新季度是否发布了
			List<AssessmentTarget> lastPublic = assessmentTargetService.selectLastPublicCompany(year, quarterly);
			Map<String, Integer> result = new HashMap<>();
			if (lastPublic.size() > 0) {
				result.put("status", 0);// 表示还没发布
			} else {
				result.put("status", 1);// 表示发布了
			}
			return Response.response(result);
		} catch (Exception e) {

			Map<String, Integer> result = new HashMap<>();
			result.put("status", 1);// 表示发布了
			return Response.response(result);
		}
	}

	/**
	 * 月度发布状态--区域
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/monthlyOrganPublicStatus", method = { RequestMethod.GET, RequestMethod.POST })
	public Object monthlyOrganPublicStatus() {
		try {
			Map<String, Integer> organMap = performanceMonthlyService.selectOrganYearAndMonth();
			Integer year = organMap.get("year");
			Integer month = organMap.get("month");
			Map<String, Integer> resultMap = new HashMap<>();// 返回结果map
			// 查询最新月度是否发布
			List<AssessmentMonthlyTarget> lastPublicList = assessmentMonthlyTargetService.getOgranLastMonthPublic(year,
					month);
			if (lastPublicList.size() > 0) {
				resultMap.put("status", 0);// 表示还未发布
			} else {
				resultMap.put("status", 1);// 表示已发布
			}
			return Response.response(resultMap);
		} catch (Exception e) {
			Map<String, Integer> result = new HashMap<>();
			result.put("status", 1);// 表示发布了
			return Response.response(result);
		}
	}

	/**
	 * 月度发布状态--城市公司
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/monthlyCompanyPublicStatus", method = { RequestMethod.GET, RequestMethod.POST })
	public Object monthlyCompanyPublicStatus() {
		try {
			Map<String, Integer> organMap = performanceMonthlyService.selectCompanyYearAndMonth();
			Integer year = organMap.get("year");
			Integer month = organMap.get("month");
			Map<String, Integer> resultMap = new HashMap<>();// 返回结果map
			// 查询最新月度是否发布
			List<AssessmentMonthlyTarget> lastPublicList = assessmentMonthlyTargetService
					.getCompanyLastMonthPublic(year, month);
			if (lastPublicList.size() > 0) {
				resultMap.put("status", 0);// 表示还未发布
			} else {
				resultMap.put("status", 1);// 表示已发布
			}
			return Response.response(resultMap);
		} catch (Exception e) {
			Map<String, Integer> result = new HashMap<>();
			result.put("status", 1);// 表示发布了
			return Response.response(result);
		}
	}

	/**
	 * 根据类型获取分类指标
	 * 
	 * @param type
	 * @param AccessToken
	 * @return
	 * @Author Wyman
	 * @Date 2018/10/15
	 */
	@ResponseBody
	@RequestMapping(value = "/getElementByType", method = { RequestMethod.GET, RequestMethod.POST })
	@Deprecated
	public Object getElementByType(@RequestParam("type") String type,
			@RequestParam(value = "AccessToken") String AccessToken) {

		Map<String, Object> resultMap = new HashMap<>();

		try {
			List<Map<String, Object>> returnList = performanceElementService.getElementByType(type);
			resultMap.put("elementList", returnList);
		} catch (Exception e) {
			return Response.responseFail(e.getMessage());
		}

		return Response.response(resultMap);
	}
}
