package com.bcxin.ins.coninsweb.preservation.controller;

import com.bcxin.ins.dto.Result;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.service.preservation.InsPreservationDetailAPIService;
import com.bcxin.ins.service.preservation.InsPreservationRecordAPIService;
import com.bcxin.ins.service.preservation.InsPreservationResultSetAPIService;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.entity.policy_core.InsPreservationResultSet;
import com.bcxin.ins.spring.annotation.LoginRequired;
import com.bcxin.ins.spring.annotation.OperationLog;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.util.DateUtil;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 自用保全申请单控制器
 * @author zxf
 *
 */
@Controller
@RequestMapping("/pc/preservation")
public class InsPreservationRecordController extends BaseController {

	@Autowired
	private InsPreservationRecordAPIService insPreservationRecordAPIService;
	@Autowired
	private InsPreservationDetailAPIService insPreservationDetailAPIService;
	@Autowired
	private InsPreservationResultSetAPIService insPreservationResultSetAPIService;
	@Autowired
	private PolicyService policyService;

	private static String IPRLIST = "iprList";
	private static String REVISE_STATUS = "revise_status";
	private static String START_TIME = "start_time";
	private static String END_TIME = "end_time";
	private static String KEYWORD = "keyword";
	private static String IPRVO = "iprVo";
	private static String DETAILLIST = "detailList";
	private static String MIN = "min";
	private static String MAX = "max";
	private static String ORDERVO = "orderVo";

	/**
	 * <b> 辅助当前版本保全重构时数据设置结果集的临时方法 </b>
	 * @author ZXF
	 * @create 2018/06/05 0005 13:48
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("test/{type}")
	public void test(@PathVariable String type) {
		insPreservationResultSetAPIService.initAllOrderToResultSet(type);
	}

	@RequestMapping("/batchMinus")
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT,title ="【视图】我的账户-人员管理-批量减员")
	public ModelAndView batchMinus() {
		ModelAndView view = new ModelAndView("/coninsweb/personalCenter/preservation/batchMinus/batchMinus");
		view.addObject("insDate", DateUtil.getTomorrow());
		setTokenByApi(view);
		return view;
	}

	@LoginRequired(redirectUrl = "redirect:/pc/preservation/batchMinus")
	@RequestMapping("/minus_policy_list_view")
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT,title ="【视图】我的账户-人员管理-批量减员-减员保单列表")
	public ModelAndView minusPolicyListView() {
		ModelAndView view = new ModelAndView("/coninsweb/personalCenter/preservation/batchMinus/minus_policy_list");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		view.addObject("insDate", DateUtil.getTomorrow());
		view.addObject("policyList", JedisUtils.getObject(ConstProp.REDIS_HEAD_POLICYS+userdetail.getOid()));
		JedisUtils.delObject(ConstProp.REDIS_HEAD_POLICYS+userdetail.getOid());
		setTokenByApi(view);
		return view;
	}

	@LoginRequired(redirectUrl = "redirect:/pc/preservation/batchMinus")
	@RequestMapping("/uploadBatchMinusFile")
	@ResponseBody
	public Result uploadBatchMinusFile(MultipartHttpServletRequest request) throws Exception {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		MultipartFile hireFile = request.getFile("batch_minus_record");
		if(hireFile != null){
			return insPreservationResultSetAPIService.minusBatchUploadInsPer(Long.parseLong(userdetail.getOid()),hireFile);
		}else{
			return Result.fail(Result.ERROR_MSG);
		}

	}

	@LoginRequired(redirectUrl = "redirect:/pc/preservation/batchMinus")
	@RequestMapping(value = "exportErrInsPer")
	public Result exportErrInsPer() {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		return insPreservationResultSetAPIService.downErrInsPer(userdetail.getOid(), getResponse());
	}

	/**
	 * <b>保全申请单查询 </b>
	 *
	 * @param revise_status
	 * @param start_time
	 * @param end_time
	 * @param request
	 * @param page
	 * @return
	 * @author ZXF
	 * @date 2016年12月29日 下午5:54:59
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"0#revise_status","1#start_time","2#end_time"},requestParamKey={"keyword"}, redirectUrl = "pc/preservation/recordList?revise_status={revise_status}&start_time={start_time}&end_time={end_time}&keyword={keyword}")
	@RequestMapping("recordList")
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT,title ="【视图】我的账户-人员管理-保全申请单查询")
	public ModelAndView recordList(String revise_status, String start_time, String end_time, HttpServletRequest request, DwzPage page) throws UnsupportedEncodingException {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		String keyword = request.getParameter("keyword");
		ModelAndView view = new ModelAndView("/coninsweb/personalCenter/preservation/recordList");
		page.setNumPerPage(5);
		if(StringUtils.isNotEmpty(keyword)){
			keyword = new String(keyword.getBytes(ConstProp.ENCODE_ISO_8859_1), ConstProp.ENCODE_UTF8);
		}
		String et = ConstProp.BLANK_CHAR;
		if(StringUtils.isNotEmpty(end_time)){
			et = end_time+ConstProp.DAY_23;
		}
		view.addObject(IPRLIST,insPreservationRecordAPIService.findInsPreservationRecordByKeyword( page, Long.parseLong(userdetail.getOid()), revise_status, start_time, et, keyword));
		view.addObject(REVISE_STATUS,revise_status);
		view.addObject(START_TIME,start_time);
		view.addObject(END_TIME,end_time);
		view.addObject(KEYWORD,keyword);
		setTokenByApi(view);
		return view;
	}

	@LoginRequired(redirectUrl = "redirect:/synopsis/unSession")
	@RequestMapping("getRecordListForPage")
	public ModelAndView ListForPage(String revise_status, String start_time, String end_time, HttpServletRequest request, DwzPage page) throws UnsupportedEncodingException {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		String keyword = request.getParameter("keyword");
		if(StringUtils.isNotEmpty(keyword)){
			keyword = new String(keyword.getBytes(ConstProp.ENCODE_ISO_8859_1), ConstProp.ENCODE_UTF8);
		}
		String et = ConstProp.BLANK_CHAR;
		if(StringUtils.isNotEmpty(end_time)){
			et = end_time+ConstProp.DAY_23;
		}
		ModelAndView view = new ModelAndView("/coninsweb/personalCenter/preservation/recordList_table");
		view.addObject(IPRLIST,insPreservationRecordAPIService.findInsPreservationRecordByKeyword( page, Long.parseLong(userdetail.getOid()), revise_status, start_time, et, keyword));
		setTokenByApi(view);
		return view;
	}
	
	/**
	 * <b>查看保全申请单详情 </b>
	 * 
	 * @param preservationId
	 * @return
	 * @author ZXF 
	 * @date 2017年1月12日 上午10:39:35
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(methodParamKey={"0#preservationId"}, redirectUrl = "pc/preservation/getRecordDetailByPreservationId/{preservationId}")
	@RequestMapping("getRecordDetailByPreservationId/{preservationId}")
	public ModelAndView getRecordDetailByPreservationId(@PathVariable Long preservationId){
		ModelAndView view = new ModelAndView();
		InsPreservationRecordVo iprVo = insPreservationRecordAPIService.findInsPreservationRecordVoById(preservationId);
		if(DictConst.REVISE_TYPE_Z.equals(iprVo.getRevise_type())&&DictConst.REVISE_STATUS_ZC.equals(iprVo.getRevise_status())){
			view.setViewName("/coninsweb/personalCenter/preservation/addRecordDetail");
		}if(DictConst.REVISE_TYPE_T.equals(iprVo.getRevise_type())){
			view.setViewName("/coninsweb/personalCenter/preservation/recordRepDetail");
		}else{
			view.setViewName("/coninsweb/personalCenter/preservation/recordDetail");
		}
		OrderFormVo orderVo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
		view.addObject(ORDERVO,orderVo);
		view.addObject(IPRVO,iprVo);
		view.addObject(DETAILLIST,iprVo.getInsPreservationDetailVoList());
		setTokenByApi(view);
		return view;
	}

	/**
	 * <b>查看保全申请单详情中保全人员分页 </b>
	 *
	 * @param preservationId
	 * @param keyword
	 * @param page
	 * @return
	 * @author ZXF
	 * @date 2017年1月12日 上午10:39:35
	 * @注意事项 </b>
	 * <b>
	 */
	@LoginRequired(redirectUrl = "redirect:/synopsis/unSession")
	@RequestMapping("recordDetailListForPage")
	public ModelAndView recordDetailListForPage(Long preservationId,String keyword, DwzPage page){
		ModelAndView view = new ModelAndView("/coninsweb/personalCenter/preservation/recordDetail_table");
		view.addObject(DETAILLIST,insPreservationDetailAPIService.findInsPreservationDetailByKeyword(page,preservationId,keyword));
		setTokenByApi(view);
		return view;
	}

	@RequestMapping("againRecord")
	@ResponseBody
	public JSONObject againRecord(long oid){
		JSONObject json = new JSONObject();
		String message;
		String status =ConstProp.CODE_FAILURE;
		try {
			if(insPreservationRecordAPIService.againRecord(oid)){
				message="再次提交审核成功！";
				status=ConstProp.CODE_SUCCESS;
			}else {
				message="提交审核失败！";
			}
		}catch (Exception e) {
			message=e.getMessage();
		}

		json.put("message", message);
		json.put("status", status);
		return json;
	}

	/**
	 * 增员再次提交审核的处理方法
	 * @param vo
	 * @return
	 */
	@RequestMapping("addAgainRecord")
	@ResponseBody
	public ResultDto addAgainRecord(InsPreservationRecordVo vo){
		//校验人员信息
		List<InsPreservationDetailVo> ipdVoList = vo.getInsPreservationDetailVoList();
		for(InsPreservationDetailVo ipdVo : ipdVoList){
			String result = insPreservationDetailAPIService.personnelToCheck(ipdVo,vo.getRevise_type());
			if(ConstProp.CODE_FAILURE.equals(result.split(ConstProp.POUND_SIGN)[0])){
				return new ResultDto(result.split(ConstProp.POUND_SIGN)[1], ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
			ipdVo.setRevise_type(ConstProp.DIGIT_ONE);
		}
		if(insPreservationRecordAPIService.addAgainRecord(Long.parseLong(vo.getOid()), ipdVoList)){
			return new ResultDto("再次提交审核成功！", ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}else{
			return new ResultDto("提交审核失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}

	@RequestMapping("deleteInsPreservationRecord")
	@ResponseBody
	public JSONObject deleteInsPreservationRecord(long oid){
		JSONObject json = new JSONObject();
		String message="保全申请单删除失败！";
		String status =ConstProp.CODE_FAILURE;
		if(insPreservationRecordAPIService.deleteInsPreservationRecord(oid)) {
			message = "保全申请单删除成功！";
			status = ConstProp.CODE_SUCCESS;
		}
		json.put("message", message);
		json.put("status", status);
		return json;
	}

	@RequestMapping("revokeInsPreservationRecord")
	@ResponseBody
	public JSONObject revokeInsPreservationRecord(long oid){
		JSONObject json = new JSONObject();
		String message="保全申请单撤销失败！";
		String status =ConstProp.CODE_FAILURE;
		if(insPreservationRecordAPIService.revokeInsPreservationRecord(oid)) {
			message = "保全申请单撤销成功！";
			status = ConstProp.CODE_SUCCESS;
		}
		json.put("message", message);
		json.put("status", status);
		return json;
	}



	/**
	 * 跳转到人员修改界面
	 * @param operate 操作标识：add,minus,replace
	 * @param preservationId 保全申请单id（如果已存在id，且状态为待提交说明该单为暂存单页面需要可修改）
	 * @return
	 */
	@LoginRequired(redirectUrl = "redirect:/synopsis/unSession")
	@RequestMapping("thr_preservation_view")
	public ModelAndView thr_preservation_view(String operate,Long preservationId){
		ModelAndView view = new ModelAndView();
		if(preservationId != null){
			InsPreservationRecordVo iprVo = insPreservationRecordAPIService.findInsPreservationRecordVoById(preservationId);
			if("add".equals(operate)){
				view.setViewName("/coninsweb/personalCenter/preservation/update_detail_add");
			}else if("minus".equals(operate)){
				view.setViewName("/coninsweb/personalCenter/preservation/update_detail_minus");
				List<InsPreservationResultSet> rsaList = insPreservationResultSetAPIService.initFindInsPreservationResultSetByKeyword(null,Long.parseLong(iprVo.getIns_insurance_slip_id()),ConstProp.BLANK_CHAR,ConstProp.DIGIT_ZERO,ConstProp.BLANK_CHAR,ConstProp.BLANK_CHAR);
				//当前在保的总人数
				view.addObject("rsaNum",rsaList!=null? rsaList.size() : 0);
				//当前需要提交减员的总人数
				view.addObject("ipdNum",iprVo.getInsPreservationDetailVoList()!=null? iprVo.getInsPreservationDetailVoList().size() : 0);
			}else{
				view.setViewName("/coninsweb/personalCenter/preservation/update_detail_replace");
			}
			OrderFormVo orderVo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
			view.addObject(ORDERVO,orderVo);
			view.addObject("iprVo",iprVo);
			String resultDate = insPreservationRecordAPIService.getEffectiveByPolicyId(Long.parseLong(iprVo.getIns_insurance_slip_id()));
			view.addObject(MIN,resultDate.split(",")[0]);
			view.addObject(MAX,resultDate.split(",")[1]);
		}
		setTokenByApi(view);
		return view;
	}

	/**
	 * 人员导入跳转到增员界面
	 * @param preservationId 保全申请单id（如果已存在id，且状态为待提交说明该单为暂存单页面需要可修改）
	 * @return
	 */
	@LoginRequired(redirectUrl = "redirect:/synopsis/unSession")
	@RequestMapping("update_detail_add_upload")
	public ModelAndView update_detail_add_upload(Long preservationId){
		ModelAndView view = new ModelAndView("/coninsweb/personalCenter/preservation/update_detail_add_upload");
		if(preservationId != null){
			InsPreservationRecordVo iprVo = insPreservationRecordAPIService.findInsPreservationRecordVoById(preservationId);
			List<InsPreservationDetailVo> list = iprVo.getInsPreservationDetailVoList();
			for(InsPreservationDetailVo ipdVo : getValueSession()){
				list.add(ipdVo);
			}
			OrderFormVo orderVo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
			view.addObject(ORDERVO,orderVo);
			view.addObject("ipdVoList",list);
		}
		setTokenByApi(view);
		return view;
	}

	/**
	 * <b> 导出批改人员清单 </b>
	 * @author ZXF
	 * @create 2020/01/19 0019 20:47
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/down_preservation_detail/{preservationId}")
	public void downPreservationDetail(@PathVariable Long preservationId, HttpServletResponse resp) {
		insPreservationDetailAPIService.downPreservationDetail(preservationId, resp);
	}

	/**
	 * <b> 导出所有保全信息 </b>
	 * @author ZXF
	 * @create 2020/01/19 0019 20:47
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/down_preservation_list")
	public void downPreservationList(HttpServletRequest req, HttpServletResponse resp) {
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail == null){
			return;
		}
		String userId = userdetail.getOid();
		String keyword = req.getParameter("keyword");
		String start_time = req.getParameter("start_time");
		String end_time = req.getParameter("end_time");
		String name = req.getParameter("name");
		insPreservationDetailAPIService.downPreservationList(userId,keyword,name,start_time,end_time,resp);
	}

	/**
	 * excel文件上传并解析,批量导入人员，增员的导入功能
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadRoleFile")
	@ResponseBody
	public ResultDto uploadRoleFile(MultipartHttpServletRequest request) throws Exception {
		MultipartFile roleFile = request.getFile("role_record");
		List<InsPreservationDetailVo> list = null;
		String[] arrStr = {"name","id_type","id_card","tel","career","scheme","sex","birthday"};
		if(roleFile != null){
			com.alibaba.fastjson.JSONObject jo = insPreservationDetailAPIService.readIPDExcel(roleFile);
			if(ConstProp.CODE_SUCCESS.equals(jo.get("ret"))){
				list = (List<InsPreservationDetailVo>)jo.get("list");
			}else{
				return new ResultDto(String.valueOf(jo.get("msg")), ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		}else{
			return new ResultDto("文件上传失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
		if(list!=null && !list.isEmpty()){
			if(setValueSession(list)){
				return new ResultDto("文件解析成功！", ConstProp.CODE_SUCCESS,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}else{
				return new ResultDto("数据缓存失败！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
			}
		}else{
			return new ResultDto("未解析到可用数据！", ConstProp.CODE_FAILURE,ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR, ConstProp.BLANK_CHAR);
		}
	}


	private boolean setValueSession(List<InsPreservationDetailVo> list) {
		JedisUtils.setObject(ConstProp.TB_IPRS_LIST + getToken(),list,3 * 60);
		return true;
//		HttpServletRequest request = null;
//		if (RequestContextHolder.getRequestAttributes() != null) {
//			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//			HttpSession session = null;
//			String sessionId = JedisUtils.get(ConstProp.REDIS_HEAD_THR_TOKEN + getToken());
//			if(StringUtils.isNotEmpty(sessionId)){
//				//获取session
//				session = SessionContext.getInstance().getSession(sessionId);
//			}else{
//				session = request.getSession();
//			}
//			session.setAttribute("iprsVoList",list);
//			return true;
//		}else{
//			return false;
//		}
	}

	private List<InsPreservationDetailVo> getValueSession() {
		List<InsPreservationDetailVo> list = (List<InsPreservationDetailVo>)JedisUtils.getObject(ConstProp.TB_IPRS_LIST + getToken());
		JedisUtils.delObject(ConstProp.TB_IPRS_LIST + getToken());
//		HttpServletRequest request = null;
//		List<InsPreservationDetailVo> list = null;
//		if (RequestContextHolder.getRequestAttributes() != null) {
//			request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//			HttpSession session = null;
//			String sessionId = JedisUtils.get(ConstProp.REDIS_HEAD_THR_TOKEN + getToken());
//			if(StringUtils.isNotEmpty(sessionId)){
//				//获取session
//				session = SessionContext.getInstance().getSession(sessionId);
//			}else{
//				session = request.getSession();
//			}
//			list = (List<InsPreservationDetailVo>)session.getAttribute("iprsVoList");
//			session.removeAttribute("iprsVoList");
//		}
		return list;
	}

}
