package com.bcxin.ars.rest.sb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ars.dao.log.LogMessageDao;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.dto.SecurityPersonSearchRerurnDTO;
import com.bcxin.ars.dto.page.PerconUnRegDto;
import com.bcxin.ars.dto.page.PersonPageSearchDto;
import com.bcxin.ars.dto.sb.*;
import com.bcxin.ars.model.Config;
import com.bcxin.ars.model.User;
import com.bcxin.ars.model.log.LogMessage;
import com.bcxin.ars.model.sb.Personcertificate;
import com.bcxin.ars.model.sys.Approval;
import com.bcxin.ars.service.certificate.SecurityCertificateService;
import com.bcxin.ars.service.exam.TrainExamPersonService;
import com.bcxin.ars.service.sb.ActivityRepairService;
import com.bcxin.ars.service.sb.FamilyService;
import com.bcxin.ars.service.sb.PersoncertificateService;
import com.bcxin.ars.service.sb.PersonworkexperienceService;
import com.bcxin.ars.service.sys.ApprovalService;
import com.bcxin.ars.service.util.ArsUtil;
import com.bcxin.ars.service.util.ConfigUtils;
import com.bcxin.ars.util.Constants;
import com.bcxin.ars.util.StringUtil;
import com.bcxin.ars.util.approval.ApprovalState;
import com.bcxin.ars.util.approval.BusinessType;
import com.com.bcxin.ars.com.abcxin.smart.core.web.validate.AjaxPageResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by 苏 on 2017/5/19.
 */

@Controller
@RequestMapping("personcertificate")
public class PersoncertificateController {
	Logger logger = LoggerFactory.getLogger(PersoncertificateController.class);

	@Autowired
	private PersoncertificateService personcertificateService;

	@Autowired
	private LogMessageDao logMessageDao;

	@Autowired
	private ApprovalService approvalService;

	@Autowired
	private ActivityRepairService activityRepairService;

	@Autowired
	private TrainExamPersonService trainExamPersonService;

	@Autowired
	private FamilyService familyService;

	@Autowired
	private PersonworkexperienceService personworkexperienceService;

	@Autowired
	private SecurityCertificateService securityCertificateService;

	@Autowired
	private ArsUtil arsUtil;

	@Value("${upload-folder}")
	private String uploadFolder;

	@Value("${approval-download-folder}")
	private String downloadFolder;

	@Value("${temp-folder}")
	private String tempfolder;

	@Autowired
	private ConfigUtils configUtils;

	/**************************************************
	 ************* 与培训平台对接接口 开始**********************
	 **************************************************/

	/**
	 * 获取考试人员名单分页功能 <b>Function </b>（百课堂使用）
	 * 
	 * @param searchDto
	 * @return
	 * @author LinQingLin
	 * @date 2017年8月29日 下午2:00:07
	 * @注意事项 </b> <b>
	 */
	@RequestMapping("findUnScheduledPersonList")
	public @ResponseBody AjaxResult findUnScheduledPersonList(ExamSearchDto searchDto) {
		AjaxResult result = new AjaxResult();
		try {
			ExamSearchDto data = personcertificateService.findUnScheduledPersonList(searchDto);
			result.setData(data);
			result.setSuccessful(true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 更新考试安排状态 <b>Function </b>
	 * 
	 * @param examDetails
	 * @return
	 * @author LinQingLin
	 * @date 2017年8月29日 下午4:22:40
	 * @注意事项 </b> <b>
	 */
	@RequestMapping("updateExamState")
	public @ResponseBody AjaxResult updateExamState(String examDetails) {

		List<ExamDetailDto> examDetailDtos = JSONArray.parseArray(examDetails, ExamDetailDto.class);

		AjaxResult result = new AjaxResult();
		JSONArray resultArr = new JSONArray();
		JSONObject resultObj = null;
		if (examDetailDtos != null && examDetailDtos.size() > 0) {
			for (ExamDetailDto examDetailDto : examDetailDtos) {
				resultObj = new JSONObject();
				resultObj.put("cardnumber", examDetailDto.getTicket());
				resultObj.put("fullName", examDetailDto.getFullName());
				try {
					personcertificateService.updateExamState(examDetailDto);
					resultObj.put("result", true);
					resultObj.put("msg", "准考证号：" + examDetailDto.getTicket());
					resultArr.add(resultObj);
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
					resultObj.put("result", false);
					resultObj.put("msg", "错误的准考证号：" + examDetailDto.getTicket() + "," + e.getMessage());
					resultArr.add(resultObj);
				}
			}

			result.setSuccessful(true);
			result.setData(resultArr);
		} else {
			result.setSuccessful(false);
			result.setData("对接数据为空");
		}
		return result;

	}

	/**
	 * 根据身份证返回制证状态
	 * 
	 * @param personcertificate
	 * @return
	 */
	@RequestMapping("getCardState")
	public @ResponseBody AjaxResult getCardState(Personcertificate personcertificate) {
		AjaxResult result = new AjaxResult();
		try {

			Personcertificate dbpersoncertificate = personcertificateService.getCardState(personcertificate);
			if (dbpersoncertificate != null && dbpersoncertificate.getCardState() != null) {
				result.setData(dbpersoncertificate.getCardState());
				result.setSuccessful(true);
				result.setMsg("查询制证状态成功");
			} else {
				result.setMsg("查找不到制证信息");
				result.setSuccessful(false);
			}
		} catch (Exception e) {
			result.setMsg("查询制证状态失败" + e.getMessage());
			result.setSuccessful(false);
			/*
			 * logger.error(e.getMessage(), e); throw e;
			 */
		}
		return result;
	}

	/**
	 * 接收考试成绩功能,根据身份证号更新成绩信息(百课堂对接考试)
	 * 
	 * @param personcertificates
	 * @return
	 */
	@RequestMapping("saveScoreByID")
	public @ResponseBody AjaxResult saveScoreByID(String personcertificates) {
		List<Personcertificate> personcertificateList = JSONArray.parseArray(personcertificates,
				Personcertificate.class);
		AjaxResult result = new AjaxResult();
		result.setData(personcertificateService.updateScoreByBetchID(personcertificateList));
		result.setSuccessful(true);
		return result;
	}

	/**
	 *
	 * @Decription:更新缴费状态的人员信息（百课堂使用）
	 * @author：zhongjianhui
	 * @method savePercertificate @date：2018/6/19 9:33 @params： * @param user_id
	 *          * @param work_status
	 * @return com.bcxin.ars.dto.AjaxResult
	 */
	@RequestMapping("savePercertificateByID")
	@Deprecated
	public @ResponseBody AjaxResult savePercertificateByID(String data) throws Exception {
		AjaxResult result = new AjaxResult();
		JSONArray resultArr;
		String message = "data" + data;
		if (StringUtil.isNotEmpty(data)) {
			List<SecurityPersonSearchRerurnDTO> list = JSON.parseArray(data, SecurityPersonSearchRerurnDTO.class);
			resultArr = personcertificateService.updateBktfeeStateByBatchID(list);
			message += message + ",resultArr" + resultArr;
			result.setData(resultArr);
			result.setSuccessful(true);
		} else {
			result.setSuccessful(false);
			result.setMsg("错误信息：数据为空");
			message += message + ",resultArr" + "错误信息：数据为空";
		}
		saveLogMessage(message);
		return result;
	}

	private LogMessage saveLogMessage(String message) {
		LogMessage logMessage = new LogMessage();
		logMessage.setLogger_title("百课更新缴费状态");
		logMessage.setCreateTime(new Date());
		logMessage.setLogger_context(message);
		// 保持错误日志
		logMessageDao.save(logMessage);
		return logMessage;
	}

	/**************************************************
	 ************* 与培训平台对接接口 结束 *********************
	 **************************************************/


	/**
	 * 与saas对接
	 * 保安员证申报保存
	 * @param personStr 保安员证json字符串
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("saveOrUpdate")
	public @ResponseBody
	AjaxResult saveOrUpdate(String personStr) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
            User user = arsUtil.getCurrentUser();
            if (user != null) {
                result.setSuccessful(true);
                //json字符串转对象
                Personcertificate personcertificate = JSON.parseObject(personStr,Personcertificate.class);
                //saas那边都没传id,先判断我们数据库中是否已存在
                //Personcertificate dbPersoncertificate = personcertificateService.findBySecurityPersonId(personcertificate.getPersonid());
                //if(dbPersoncertificate != null){
                //	personcertificate.setId(dbPersoncertificate.getId());
                //}
                //默认提交审批
                personcertificate.setApprovalstate(ApprovalState.DSH);
				personcertificate.setNeedApprove(false);
                personcertificateService.saveOrUpdateForSaas(personcertificate);
                result.setData(personcertificate);
            } else {
                result.setSuccessful(false);
            }
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 *
	 * 与saas对接
	 * 根据id查询保安员证申报信息
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getDetail")
	public @ResponseBody
	AjaxResult getDetail(Long id) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			result.setSuccessful(true);
			SAASPersonCerDto personcertificate = personcertificateService.getDetailForSAAS(id);
			if(personcertificate != null) {
				//图片地址转完整的访问地址，不然saas那边访问不了
				String webHost = configUtils.getWebHost();
				//健康证明
				if(StringUtil.isNotEmpty(personcertificate.getHealthExamination())) {
					personcertificate.setHealthExamination(webHost + personcertificate.getHealthExamination());
				}
				//身份证正面
				if(StringUtil.isNotEmpty(personcertificate.getIdCardFront())) {
					personcertificate.setIdCardFront(webHost + personcertificate.getIdCardFront());
				}
				//身份证反面
				if(StringUtil.isNotEmpty(personcertificate.getIdCardReverse())) {
					personcertificate.setIdCardReverse(webHost + personcertificate.getIdCardReverse());
				}
				//学历证明
				if(StringUtil.isNotEmpty(personcertificate.getEduPhoto())) {
					personcertificate.setEduPhoto(webHost + personcertificate.getEduPhoto());
				}
				//一寸头像
				if(StringUtil.isNotEmpty(personcertificate.getImglogo())) {
					personcertificate.setImglogo(webHost + personcertificate.getImglogo());
				}

				result.setData(JSONObject.toJSONString(personcertificate));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/**
	 *
	 * 与saas对接
	 * 根据保安员id查询保安员证申报信息
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getDetailForSAAS")
	@Deprecated
	public @ResponseBody
	AjaxResult getDetailForSAAS(Long id) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			result.setSuccessful(true);
			SAASPersonCerDto personcertificate = personcertificateService.getDetailForSAAS(id);
			if(personcertificate != null) {
				//图片地址转完整的访问地址，不然saas那边访问不了
				String webHost = configUtils.getWebHost();
				//健康证明
				if(StringUtil.isNotEmpty(personcertificate.getHealthExamination())) {
					personcertificate.setHealthExamination(webHost + personcertificate.getHealthExamination());
				}
				//身份证正面
				if(StringUtil.isNotEmpty(personcertificate.getIdCardFront())) {
					personcertificate.setIdCardFront(webHost + personcertificate.getIdCardFront());
				}
				//身份证反面
				if(StringUtil.isNotEmpty(personcertificate.getIdCardReverse())) {
					personcertificate.setIdCardReverse(webHost + personcertificate.getIdCardReverse());
				}
				//学历证明
				if(StringUtil.isNotEmpty(personcertificate.getEduPhoto())) {
					personcertificate.setEduPhoto(webHost + personcertificate.getEduPhoto());
				}
				//头像
				if(StringUtil.isNotEmpty(personcertificate.getImglogo())) {
					personcertificate.setImglogo(webHost + personcertificate.getImglogo());
				}

				result.setData(JSONObject.toJSONString(personcertificate));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 校验人员是否可以资格证报名
	 * 是否可以报名 0：不可以 1：可以
	 * @param personId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("checkApplyForSAAS")
	@Deprecated
	@ResponseBody
	public AjaxResult checkApplyForSAAS(Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			result.setSuccessful(true);
			result.setData(personcertificateService.checkApplyForSAAS(personId));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 是否已持证
	 * @param idNum
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("checkCerStatus")
	@ResponseBody
	public AjaxResult checkCerStatus(String idNum) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			result.setSuccessful(true);
			result.setData(securityCertificateService.checkCerStatus(idNum));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 是否可报名
	 * @param idNum
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("checkStatusForApply")
	@ResponseBody
	public AjaxResult checkStatusForApply(String idNum) throws Exception {
		AjaxResult result = null;
		try {
			result = securityCertificateService.checkStatusForApply(idNum);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	@RequestMapping("searchForSAASPage")
	public @ResponseBody
	AjaxPageResponse searchForSAASPage(SAASPersonCertificateSearchDto searchDto, AjaxPageResponse<SAASPersonCertificateDto> page) throws Exception {
		try {
			User currentUser = arsUtil.getCurrentUser();
			if (currentUser != null) {
				//人员查询
				if(StringUtil.isNotEmpty(searchDto.getPersonId())){
					searchDto.setPersonId(searchDto.getPersonId());
				}else {
					//公司查询
					searchDto.setUserid(currentUser.getId());
				}
				personcertificateService.searchForSAASPage(searchDto,page);
			}
			return page;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 *
	 * 与saas对接
	 * 根据保安员id查询保安员证申报审批状态
	 * @param personId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getApprovalState")
	public @ResponseBody
	AjaxResult getApprovalState(Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			result.setSuccessful(true);
			Personcertificate personcertificate = personcertificateService.findBySecurityPersonId(personId);
			if(personcertificate != null){
				result.setData(personcertificate.getApprovalstate());
			}else{
				result.setData(ApprovalState.WTJ);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 *
	 * 与saas对接
	 * 根据保安员id查询保安员证申报审批意见
	 * @param personId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getApprovalReason")
	public @ResponseBody
	AjaxResult getApprovalReason(Long personId) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			result.setSuccessful(true);
			Personcertificate personcertificate = personcertificateService.findBySecurityPersonId(personId);
			if(personcertificate != null){
				Approval approval = approvalService.findBybusinessidAndType(personcertificate.getId(), BusinessType.BAYZ);
				result.setData(approval.getApprovalreason());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 *
	 * 与saas对接
	 * 获取申报项目的必填属性（家庭成员、工作经历、学历证明、体检证明）
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getRequiredInfo")
	public @ResponseBody
	AjaxResult getRequiredInfo() throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			JSONObject requiredInfo = new JSONObject();
			//家庭是否必填
			Config isRequiredFamilly =configUtils.getConfigByKey(Constants.IS_REQURIED_FAMILLY);
			requiredInfo.put("requiredFamilly",isRequiredFamilly != null? isRequiredFamilly.getValue() : "1");

			//工作经历是否必填
			Config isRequiredWork = configUtils.getConfigByKey(Constants.IS_REQURIED_WORK);
			requiredInfo.put("requiredWork",isRequiredWork != null? isRequiredWork.getValue() : "1");

			/**
			 * 是否显示初中以上学历证明原件
			 */
			Config eduPhotoConfig = configUtils.getConfigByKey(Constants.EDU_PHOTO);
			requiredInfo.put("requiredEduPhoto",eduPhotoConfig != null? eduPhotoConfig.getValue() : "1");

			/**
			 * 是否显示县级以上医院出具的体检证明
			 */
			Config healthExaminationConfig = configUtils.getConfigByKey(Constants.HEALTH_EXAMINATION);
			requiredInfo.put("requiredHealthExamination",healthExaminationConfig != null? healthExaminationConfig.getValue() : "1");

			result.setData(requiredInfo);
			result.setSuccessful(true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 取消缴费
	 * @param personIds
	 * @return
	 */
	@RequestMapping("cancelFeeState")
	@ResponseBody
	public AjaxResult cancelFeeState(@RequestParam(required = true) String personIds){
		AjaxResult result = new AjaxResult();
		try {
			if(StringUtil.isNotEmpty(personIds)){
				String[] ids = personIds.split(",");
				Long[] idArr = new Long[ids.length];
				for (int i = 0; i < ids.length; i++) {
					idArr[i] = Long.parseLong(ids[i]);
				}
				if(ids.length > 0){
					result.setSuccessful(true);
					result.setData(personcertificateService.cancelFeeState(idArr));
				}
			}else {
				result.setSuccessful(false);
				result.setMsg("id不能为空");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 保安员证审批批量打回+填写打回意见
	 *
	 * @param personIds
	 * @return
	 */
	@RequestMapping("batchRepulse")
	@ResponseBody
	public AjaxResult batchRepulse(String personIds,String returnreason) {
		AjaxResult result = new AjaxResult();
		try {
			if (personIds!=null) {
				String [] personId=  personIds.split(",");
				int strLen= personId.length;
				Long [] longIds=new Long[strLen];
				for (int i=0;i<strLen;i++){
					longIds[i]=  Long.parseLong(personId[i]);
				}
				result.setData(personcertificateService.batchRepulse(longIds,returnreason));
				result.setSuccessful(true);
				result.setMsg("打回成功！");
			}else {
				result.setSuccessful(false);
				result.setMsg("无人员数据！");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/***
	 * 批量修改资格证报名
	 */
	@RequestMapping("batchUpdate")
	@ResponseBody
	public AjaxResult batchUpdate(String persons){
		AjaxResult result = new AjaxResult();
		try {
			List<Personcertificate> list = JSONArray.parseArray(persons,Personcertificate.class);
			personcertificateService.batchUpdate(list);
			result.setSuccessful(true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	public static void main(String[] args) {
		String persons="{\"personGrades\":\"[{\\\"approvalstate\\\":\\\"002\\\",\\\"checkDate\\\":1600928250000,\\\"checkState\\\":\\\"1\\\",\\\"examState\\\":\\\"0\\\",\\\"examSubject\\\":\\\"资格证考试\\\",\\\"feeState\\\":\\\"1\\\",\\\"id\\\":758691042631516160,\\\"learnRate\\\":8,\\\"payComId\\\":\\\"697098409231777793\\\",\\\"payComName\\\":\\\"薪酬测试服务公司三\\\",\\\"personid\\\":697106685138829312,\\\"testState\\\":\\\"\\\",\\\"trainOrgID\\\":\\\"616669005482033152\\\",\\\"trainOrgName\\\":\\\"万乐明培训公司\\\",\\\"trainStartDate\\\":\\\"2020-09-24\\\"}]\"}";
		List<Personcertificate> list = JSONArray.parseArray(persons,Personcertificate.class);
		System.out.println(list.size());
	}

    /**
     * 接收百kt的 实训材料
     * @return
     */

    @RequestMapping("updateTrainMaterials")
    @ResponseBody
    public AjaxResult updateTrainMaterials(String  persons){
        AjaxResult result = new AjaxResult();
        try {
			List<Personcertificate> list = JSONArray.parseArray(persons,Personcertificate.class);


            personcertificateService.updateTrainMaterials(list);
            result.setSuccessful(true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }

	@RequestMapping("searchUnRegisterForPage")
	@ResponseBody
	public AjaxPageResponse searchUnRegisterForPage(PersonPageSearchDto dto, AjaxPageResponse<PerconUnRegDto> page){
		personcertificateService.searchUnRegisterForPage(dto,page);
		return page;
	}

	@RequestMapping("checkExists")
	@ResponseBody
	public AjaxResult checkExists(long id){
		AjaxResult result = new AjaxResult();
		try {
			Personcertificate detail = personcertificateService.findDetailById(id);
			if(detail != null){
				result.setData("1");
			}else{
				result.setData("0");
			}
			result.setSuccessful(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setData("0");
			result.setSuccessful(false);
			result.setMsg(e.getMessage());
		}
		return result;
	}

}
