package com.bcxin.ars.rest;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ars.dao.sys.MessageLogDao;
import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.dto.PersonSearchDto;
import com.bcxin.ars.dto.RoleSubjectVo;
import com.bcxin.ars.dto.SecurityPersonSearchRerurnDTO;
import com.bcxin.ars.exception.ArsException;
import com.bcxin.ars.model.*;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.service.*;
import com.bcxin.ars.service.bean.factory.CustomPersoncertificateBeanFactory;
import com.bcxin.ars.service.sb.CustomPersoncertificateService;
import com.bcxin.ars.service.util.ConfigUtils;
import com.bcxin.ars.util.*;
import com.bcxin.ars.util.message.messageUtils;
import org.apache.commons.lang.StringUtils;
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.ResponseBody;

import java.util.*;

@Controller
	@RequestMapping("company")
public class SecurityCompanyController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(SecurityCompanyController.class);

	@Autowired
	private SecurityCompanyService companyService;
	@Autowired
	private InvoiceService invoiceService;
	@Autowired
	private SecurityPersonService personService;

	@Autowired
	private SecurityCompanyPersonService securityCompanyPersonService;


	@Autowired
	private SecurityCompanyScheduleService scheduleService;

	@Autowired
	private ArsRestUtil arsUtil;

	@Autowired
	private UserService userService;

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

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

	@Autowired
	private OrderService orderService;

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

	@Value("${base-folder}")
	private String baseFolder;

	@Autowired
	private MessageLogDao messageLogDao;
	@Autowired
	private ConfigUtils configUtils;

	@Autowired
	 private PoliceService policeService;
	/***
	 * 保存单位与订单号的信息
	 * @param user_id 单位ID
	 * @param orderNo 订单号
	 * @return
	 */
	@RequestMapping("cancelOrderInfo")
	public  @ResponseBody  AjaxResult cancelOrderInfo(Long user_id,String orderNo) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			//获取单位信息
			SecurityCompany company = companyService.findByUserid(user_id);
			company.setOrderNo("");
			companyService.saveOrUpdateForFX(company);
			List<SecurityPerson> list = personService.findByCompanyId(company.getId());
			int i=0;
			if(list!=null && list.size()>0){
				for (SecurityPerson person:
						list) {
//					if(person.getInsured()!=null && person.getInsured()){
//						person.setInsured(false);
//						personService.updateBX(person);
//						break;
//					}
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return result;
	}


	/**
	 *
	 * @Decription:根据公司的UserName获取在职人员信息（百课堂使用）
	 * @author：zhongjianhui
	 * @method  findPersonByUserid
	 * @date：2018/6/19 9:33
	 * @params： * @param user_id
	 * @param work_status
	 * @return com.bcxin.ars.dto.AjaxResult
	 */
	@RequestMapping("findPersonByUserName")
	public  @ResponseBody  AjaxResult findPersonByUserName(SecurityPersonSearchRerurnDTO securityPersonSearchDto) throws Exception  {
		AjaxResult result = new AjaxResult();
		try {
			//获取单位信息
			SecurityCompany company = companyService.findByUserName(securityPersonSearchDto.getUserName());
			if(company != null) {
				//获取人员信息
				securityPersonSearchDto.setCompanyId(company.getId());
				/*根据不同环境获取不同的*/
				CustomPersoncertificateService customPersoncertificateService = CustomPersoncertificateBeanFactory.getPersoncertificateBean();
				SecurityPersonSearchRerurnDTO securityPersonSearchRerurn=customPersoncertificateService.findPersonByCompanyIdSearchReturnDTO(securityPersonSearchDto);
				result.setSuccessful(true);
				result.setData(securityPersonSearchRerurn);
			} else {
				result.setSuccessful(false);
				result.setMsg("未找到指定公司信息。");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 *
	 * @Decription:根据公司的id获取在职人员信息（百课堂使用）
	 * @author：zhongjianhui
	 * @method  findPersonByUserid
	 * @date：2018/6/19 9:33
	 * @params： * @param user_id
	 * @param work_status
	 * @return com.bcxin.ars.dto.AjaxResult
	 */
	@RequestMapping("findPersonByComId")
	public  @ResponseBody  AjaxResult findPersonByComId(SecurityPersonSearchRerurnDTO securityPersonSearchDto) throws Exception  {
		AjaxResult result = new AjaxResult();
		try {
			securityPersonSearchDto.setSaasComId(true);
			/*根据不同环境获取不同的*/
			CustomPersoncertificateService customPersoncertificateService = CustomPersoncertificateBeanFactory.getPersoncertificateBean();
			SecurityPersonSearchRerurnDTO securityPersonSearchRerurn=customPersoncertificateService.findPersonByCompanyIdSearchReturnDTO(securityPersonSearchDto);
			result.setSuccessful(true);
			result.setData(securityPersonSearchRerurn);
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 *
	 * @Decription:根据公司的ID获取公司发票信息（百课堂使用）
	 * @author：zhongjianhui
	 * @method  findPersonByUserName
	 * @date：2018/6/19 9:33
	 * @params： * @param user_id
	 * @param work_status
	 * @return com.bcxin.ars.dto.AjaxResult
	 */
	@RequestMapping("findInvoiceByUserName")
	public  @ResponseBody  AjaxResult findInvoiceByUserName(String userName) throws Exception  {
		AjaxResult result = new AjaxResult();
		try {
			//获取发票信息
			Invoice invoice =  invoiceService.getMsgByUserName(userName);
			if(invoice != null) {

				result.setSuccessful(true);
				result.setData(invoice);
			} else {
				result.setSuccessful(false);
				result.setMsg("未找到指定公司的发票信息。");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/***
	 * 保存单位与订单号的信息
	 * @param user_id 单位ID
	 * @param orderNo 订单号
	 * @return
	 */
	@RequestMapping("saveOrderInfo")
	public  @ResponseBody  AjaxResult saveOrderInfo(Long user_id,String orderNo,String cardList,String insuranceamount,String insuranceEscortAmount) throws Exception {
		//获取单位信息
		AjaxResult result = new AjaxResult();
		try {
			SecurityCompany company = companyService.findByUserid(user_id);
			JSONObject jsonObject = JSONObject.parseObject(cardList);
			List<String> ordercards  = new ArrayList<String>() ;
			for(int i = 0;i<Integer.parseInt(jsonObject.getString("count"));i++){
				String cardNo = jsonObject.getString(i+"");
				ordercards.add(cardNo);
			}
			if(company!=null) {
//				String orderNotemp =  company.getOrderNo();
//				orderNotemp = orderNo;
				//注释，投保成功之无需把保险信息存到公司信息表，个人信息表已存 edit 2018-4-22 subh start
				/*company.setOrderNo(orderNo);
				company.setInsuranceAmount(insuranceamount);
				company.setInsuranceEscortAmount(insuranceEscortAmount);
				companyService.saveOrUpdateForFX(company);*/
				//注释，投保成功之无需把保险信息存到公司信息表，个人信息表已存 edit 2018-4-22 subh end
				List<Long>  personIdlists  = new ArrayList<Long>();
				List<SecurityPerson> list = personService.findByCompanyId(company.getId());
				int i=0;
				/*******************获取保险信息并更新到人员信息表 edit 2018-4-22 subh start ******************************/
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("order_id", orderNo);
				//获得保险信息
				String url = ThirdPartyURL.BAILIANBAO + "/api/order/policyDal";
				String resultStr = messageUtils.doPost2(url, messageUtils.packageMap(map, "ARS"));
				//产品名称
				String product_name = messageUtils.getStringValueByKey(resultStr, "product_name");
				//保险公司名称
				String insurance_ame = messageUtils.getStringValueByKey(resultStr, "insurance_ame");
				//生效日期
				String inception_date = messageUtils.getStringValueByKey(resultStr, "inception_date");
				//失效日期
				String planned_end_date = messageUtils.getStringValueByKey(resultStr, "planned_end_date");
				//保费
				String gross_premium = messageUtils.getStringValueByKey(resultStr, "gross_premium");
				//投保人名称
				String applicant_name = messageUtils.getStringValueByKey(resultStr, "applicant_name");
				//被保险人数量
				String ins_count = messageUtils.getStringValueByKey(resultStr, "ins_count");

				List<SecurityPerson> listSecurityPerson = new ArrayList<>();
				if(list!=null && list.size()>0){
					for (SecurityPerson person: list) {
						/*Map<String, Object> map = new HashMap<String, Object>();
						map.put("oid", orderNo);
						map.put("webType", Constants.POLICY_WEBTYPE);
						map.put("idCard", person.getIdNumber());
						map.put("token", Sha1Util.entryptPassword(Constants.POLICY_WEBTYPE + company.getUser().getId()));//生成密钥 当密钥相同的时候才进行插入数据
						//保存分销商
						String url = ThirdPartyURL.FENXIAO + ThirdPartyURL.CHECK_USER_POLICY;
						String resultStr = messageUtils.doPost2(url, messageUtils.packageMap(map, "ARS"));
						String status = messageUtils.getStringValueByKey(resultStr, "status");
						String flag = messageUtils.getStringValueByKey(resultStr, "flag");*/
						for (String cardno : ordercards) {
							if(person.getIdNumber()!=null && person.getIdNumber().equals(cardno)){
								if(StringUtil.isNotEmpty(person.getPersonType()) && person.getPersonType().equals("3")) {
									//押运人员
									person.setInsuranceAmount(insuranceEscortAmount);
								}else {
									person.setInsuranceAmount(insuranceamount);
								}
								//person.setInsured(true);
								person.setBxOrderno(orderNo);

								//产品名称
								person.setProduct_name(product_name);
								//保险公司名称
								person.setInsurance_ame(insurance_ame);
								//生效日期
								person.setInception_date(inception_date);
								//失效日期
								person.setPlanned_end_date(planned_end_date);
								//保费
								person.setGross_premium(gross_premium);
								//投保人名称
								person.setApplicant_name(applicant_name);
								//被保险人数量
								person.setIns_count(ins_count);

								listSecurityPerson.add(person);
							//	personService.updateBX(person);
								personIdlists.add(person.getId());
								break;

							}
						}
					}
				}

				if(listSecurityPerson.size()>0){
					personService.updateBXBatch(listSecurityPerson);
				}


				/*******************获取保险信息并更新到人员信息表 edit 2018-4-22 subh end ******************************/
				//TODO
				Order order = new Order();
				//金额
				order.setAmount("0");
				//付款状态
				order.setPaystate("2");
				//订单类型
				order.setOrdertype("2");
				//订单号
				order.setOrdernumber(orderNo);
				//商品
				order.setGoodsname("任务管理+在职保安员继续教育培训课程");
				//金额
				order.setUnitprice("120");
//				Map<String, Object> map = new HashMap<String, Object>();
//				map.put("order_id", orderNo);
				//保存保险信息
//				String url = ThirdPartyURL.BAILIANBAO + "/api/order/policyDal";
//				String resultStr = messageUtils.doPost2(url, messageUtils.packageMap(map, "ARS"));
//				String inception_date = messageUtils.getStringValueByKey(resultStr, "inception_date");//生效日期
//				String planned_end_date = messageUtils.getStringValueByKey(resultStr, "planned_end_date");//失效日期
				if(planned_end_date!=null && inception_date !=null && !"".equals(inception_date) && !"".equals(planned_end_date)) {
					//生效日期
					order.setEffectiveendtime(DateUtil.convertStringToDate(planned_end_date));
					//失效日期
					order.setEffectivestarttime(DateUtil.convertStringToDate(inception_date));
				}
				//订单状态
				order.setOrderstate("4");
				//订单类型
				order.setTraintype("2");
				//订单名称
				order.setCompanyname(company.getName());
				//订单培训机构
				order.setTrainorgid(100l);
				//人数
				order.setCountnumber(i);
				Long[] personIds = new Long[personIdlists.size()];
				for(int j=0;j<personIdlists.size();j++){
					personIds[j]=personIdlists.get(j);
				}
				//TODO 调用培训平台人员与视频关系
				orderService.createOrderForBxMF(order,personIds,company.getUser());
				//上线与百课堂、百联保对接稳定后再去悼短信通知
				MessageUtil.sendMessage("13328701375","百联保订单号："+orderNo+"已生效请及时检查百课堂培训信息！",messageLogDao);
			}
			result.setSuccessful(true);
		}catch(Exception e) {
			throw e;
		}
		return result;
	}



	/***
	 * 保险保全
	 * @param user_id 单位ID
	 * @param orderNo 订单号
	 * @param cardList 身份证信息
	 * @return
	 */
	@RequestMapping("insurancePreservationOld")
	public  @ResponseBody  AjaxResult insurancePreservationOld(Long user_id,String orderNo,String cardList) throws Exception {
		//获取单位信息
		AjaxResult result = new AjaxResult();
		try {
			SecurityCompany company = companyService.findByUserid(user_id);

			if(company!=null) {
//				String orderNotemp =  company.getOrderNo();
//				orderNotemp = orderNo;
				company.setOrderNo(orderNo);
				companyService.saveOrUpdateForFX(company);

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("order_id", orderNo);
				//获得保险信息
				String url = ThirdPartyURL.BAILIANBAO + "/api/order/policyDal";
				String resultStr = messageUtils.doPost2(url, messageUtils.packageMap(map, "ARS"));
				String product_name = messageUtils.getStringValueByKey(resultStr, "product_name");//产品名称
				String insurance_ame = messageUtils.getStringValueByKey(resultStr, "insurance_ame");//保险公司名称
				String inception_date = messageUtils.getStringValueByKey(resultStr, "inception_date");//生效日期
				String planned_end_date = messageUtils.getStringValueByKey(resultStr, "planned_end_date");//失效日期
				String gross_premium = messageUtils.getStringValueByKey(resultStr, "gross_premium");//保费
				String applicant_name = messageUtils.getStringValueByKey(resultStr, "applicant_name");//投保人名称
				String ins_count = messageUtils.getStringValueByKey(resultStr, "ins_count");//被保险人数量

				List<Long>  personIdlists  = new ArrayList<Long>();
				List<SecurityPerson> list = personService.findByCompanyId(company.getId());

				JSONObject jsonObject = JSONObject.parseObject(cardList);
				List<String> ordercards  = new ArrayList<String>() ;
				for(int i = 0;i<Integer.parseInt(jsonObject.getString("count"));i++){
					String cardNo = jsonObject.getString(i+"");
					ordercards.add(cardNo);
				}

				if(list!=null && list.size()>0){
					for (SecurityPerson person: list) {
						for (String cardno : ordercards) {
							String recordType = cardno.split("#")[1];//1增 2减
							cardno = cardno.split("#")[0];
							if(person.getIdNumber()!=null && person.getIdNumber().equals(cardno)){
								if(recordType.equals("1")) {
									if(StringUtil.isNotEmpty(person.getPersonType()) && person.getPersonType().equals("3")) {
										//押运人员
										person.setInsuranceAmount(company.getInsuranceEscortAmount());
									}else {
										person.setInsuranceAmount(company.getInsuranceAmount());
									}

									//person.setInsured(true);

									person.setProduct_name(product_name);
									person.setInsurance_ame(insurance_ame);
									person.setInception_date(inception_date);
									person.setPlanned_end_date(planned_end_date);
									person.setGross_premium(gross_premium);
									person.setApplicant_name(applicant_name);
									person.setIns_count(ins_count);
									person.setBxOrderno(orderNo);
									personIdlists.add(person.getId());
								}else {
									person.setBxOrderno("");
									//person.setInsured(false);
								}

								personService.updateBX(person);
								break;
							}
						}
					}
				}
				//TODO
				Order order = new Order();
				//金额
				order.setAmount("0");
				//付款状态
				order.setPaystate("2");

				//订单类型
				order.setOrdertype("2");
				//订单号
				order.setOrdernumber(orderNo);
				//商品
				order.setGoodsname("任务管理+在职保安员继续教育培训课程");
				order.setUnitprice("120");
				if(planned_end_date!=null && inception_date !=null && !"".equals(inception_date) && !"".equals(planned_end_date)) {
					//生效日期
					DateUtil.convertStringToDate(planned_end_date);

					order.setEffectiveendtime(DateUtil.convertStringToDate(planned_end_date));
					//失效日期
					order.setEffectivestarttime(DateUtil.convertStringToDate(inception_date));
				}
				//订单状态
				order.setOrderstate("4");
				//订单类型
				order.setTraintype("2");
				//订单名称
				order.setCompanyname(company.getName());
				//订单培训机构
				order.setTrainorgid(100l);
				//人数
				order.setCountnumber(personIdlists.size());
				Long[] personIds = new Long[personIdlists.size()];
				for(int j=0;j<personIdlists.size();j++){
					personIds[j]=personIdlists.get(j);
				}
				//TODO 调用培训平台人员与视频关系
				orderService.createOrderForBxMF(order,personIds,company.getUser());


			}
			result.setSuccessful(true);
		}catch(Exception e) {
			throw e;
		}
		return result;
	}


	/***
	 * 保险保全
	 * @param user_id 单位ID
	 * @param orderNo 订单号
	 * @param cardList 身份证信息
	 * @return
	 */
	@RequestMapping("insurancePreservation")
	public  @ResponseBody  AjaxResult insurancePreservation(Long user_id,String orderNo,String cardList) throws Exception {
		//获取单位信息
		AjaxResult result = new AjaxResult();
		try {
			SecurityCompany company = companyService.findByUserid(user_id);

			if(company!=null) {
//				String orderNotemp =  company.getOrderNo();
//				orderNotemp = orderNo;
				company.setOrderNo(orderNo);
				companyService.saveOrUpdateForFX(company);

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("order_id", orderNo);
				//获得保险信息
				String url = ThirdPartyURL.BAILIANBAO + "/api/order/policyDal";
				String resultStr = messageUtils.doPost2(url, messageUtils.packageMap(map, "ARS"));
				//产品名称
				String product_name = messageUtils.getStringValueByKey(resultStr, "product_name");
				//保险公司名称
				String insurance_ame = messageUtils.getStringValueByKey(resultStr, "insurance_ame");
				//生效日期
				String inception_date = messageUtils.getStringValueByKey(resultStr, "inception_date");
				//失效日期
				String planned_end_date = messageUtils.getStringValueByKey(resultStr, "planned_end_date");
				//保费
				String gross_premium = messageUtils.getStringValueByKey(resultStr, "gross_premium");
				//投保人名称
				String applicant_name = messageUtils.getStringValueByKey(resultStr, "applicant_name");
				//被保险人数量
				String ins_count = messageUtils.getStringValueByKey(resultStr, "ins_count");

				List<Long>  personIdlists  = new ArrayList<Long>();
				List<SecurityPerson> list = personService.findByCompanyId(company.getId());

				JSONObject jsonObject = JSONObject.parseObject(cardList);
				List<String> ordercards  = new ArrayList<String>() ;
				for(int i = 0;i<Integer.parseInt(jsonObject.getString("count"));i++){
					String cardNo = jsonObject.getString(i+"");
					ordercards.add(cardNo);
				}

				List<SecurityPerson> listSecurityPerson = new ArrayList<>();
				if(list!=null && list.size()>0){
					for (SecurityPerson person: list) {
						for (String cardno : ordercards) {
							//1增 2减
							String recordType = cardno.split("#")[1];
							cardno = cardno.split("#")[0];
							if(person.getIdNumber()!=null && person.getIdNumber().equals(cardno)){
								if("1".equals(recordType)) {
									if(StringUtil.isNotEmpty(person.getPersonType()) && "3".equals(person.getPersonType())) {
										//押运人员
										person.setInsuranceAmount(company.getInsuranceEscortAmount());
									}else {
										person.setInsuranceAmount(company.getInsuranceAmount());
									}

								//	person.setInsured(true);

									person.setProduct_name(product_name);
									person.setInsurance_ame(insurance_ame);
									person.setInception_date(inception_date);
									person.setPlanned_end_date(planned_end_date);
									person.setGross_premium(gross_premium);
									person.setApplicant_name(applicant_name);
									person.setIns_count(ins_count);
									person.setBxOrderno(orderNo);
									personIdlists.add(person.getId());
								}else {
									person.setBxOrderno("");
								//	person.setInsured(false);
								}
								person.setUpdateTime(new Date());

								listSecurityPerson.add(person);
							//	personService.updateBX(person);
								break;
							}
						}
					}
				}

				if(listSecurityPerson.size()>0){
					personService.updateBXBatch(listSecurityPerson);
				}

				//TODO
				Order order = new Order();
				//金额
				order.setAmount("0");
				//付款状态
				order.setPaystate("2");

				//订单类型
				order.setOrdertype("2");
				//订单号
				order.setOrdernumber(orderNo);
				//商品
				order.setGoodsname("任务管理+在职保安员继续教育培训课程");
				order.setUnitprice("120");
				if(planned_end_date!=null && inception_date !=null && !"".equals(inception_date) && !"".equals(planned_end_date)) {
					//生效日期
					DateUtil.convertStringToDate(planned_end_date);

					order.setEffectiveendtime(DateUtil.convertStringToDate(planned_end_date));
					//失效日期
					order.setEffectivestarttime(DateUtil.convertStringToDate(inception_date));
				}
				//订单状态
				order.setOrderstate("4");
				//订单类型
				order.setTraintype("2");
				//订单名称
				order.setCompanyname(company.getName());
				//订单培训机构
				order.setTrainorgid(100l);
				//人数
				order.setCountnumber(personIdlists.size());
				Long[] personIds = new Long[personIdlists.size()];
				for(int j=0;j<personIdlists.size();j++){
					personIds[j]=personIdlists.get(j);
				}
				//TODO 调用培训平台人员与视频关系
				orderService.createOrderForBxMF(order,personIds,company.getUser());

			}
			result.setSuccessful(true);
		}catch(Exception e) {
			throw e;
		}
		return result;
	}

	/***
	 * 根据公司的ID获取公司信息和人员信息（百联保使用）
	 * @param user_id
	 * @return
	 */
	@RequestMapping("findCompnayAndPersonByUserid")
	public  @ResponseBody  AjaxResult findCompnayAndPersonByUserid(Long user_id) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List list = new ArrayList();
			result.setSuccessful(true);
			result.setData(list);
			//获取单位信息
			SecurityCompany company = companyService.findByUserid(user_id);
			if(company != null) {
				//单位信息
				RoleSubjectVo vo = new RoleSubjectVo();
				vo.setKind("1");
				vo.setName_cn(company.getName());//单位名称
				vo.setId_type("2");
				vo.setPhone(company.getTel());
//				vo.setRegProvince(company.getProvince());//省
//				vo.setRegCity(company.getCity());//市
//				vo.setRegDistrict(company.getArea());//区
				vo.setReg_address(company.getLocation());
				vo.setDo_business_address(company.getLocation());
				vo.setTotal_emp(company.getSecurityAmount()+"");
				vo.setOrganization_code(company.getSocialCode());

				list.add(vo);
				//获取人员信息 2018年8月3日17:28:32 wjb 人数改为可配置的
				PersonSearchDto personSearchDto = new PersonSearchDto();
				personSearchDto.setCompanyId(company.getId());
				List<SecurityPerson> listperson = personService.findByCompanyIdForInsuranceAndCheckId(personSearchDto);
				Map<String,Object> data = new HashMap<String,Object>();
				for (SecurityPerson person : listperson) {
					RoleSubjectVo temp = new RoleSubjectVo();
					if(person.getRelation().getActive()) {
						temp.setKind("2");
						temp.setName_cn(person.getRealName());//单位名称
						temp.setId_type("0");
						temp.setMobile(person.getPhone().length()==11?person.getPhone():"");
						temp.setSex(person.getGender().equals("男") ? "1" : "2");
						temp.setOrganization_code(person.getIdNumber().trim().replaceAll(" ", "").toUpperCase());
						temp.setBirth_date(IdNumUtil.getBirthdayByIdCard(person.getIdNumber()));
						temp.setMajor_group(person.getPersonType());
						list.add(temp);
					}
				}
				result.setSuccessful(true);
				result.setData(list);
			} else {
				result.setSuccessful(false);
				result.setMsg("未找到指定公司信息。");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}



	/***
	 * 根据公司的ID以及在职状态获取人员信息
	 * @param user_id
	 * @return
	 */
	@RequestMapping("findPersonByUseridAndStatus")
	public  @ResponseBody  AjaxResult findPersonByUseridAndStatus(Long user_id,String work_status) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			List<RoleSubjectVo> list = new ArrayList<RoleSubjectVo>();
			//获取单位信息
			SecurityCompany company = companyService.findByUserid(user_id);
			if(company != null) {
				//获取人员信息
				List<SecurityPerson> listperson = personService.findPersonByCompanyIdAndStatus(company.getId(),work_status);
				if(listperson != null && listperson.size() > 0){
					for (SecurityPerson person : listperson) {
						RoleSubjectVo temp = new RoleSubjectVo();
						temp.setKind("2");
						temp.setName_cn(person.getRealName());//单位名称
						temp.setId_type("0");
						temp.setMobile(person.getPhone());
						temp.setSex(person.getGender().equals("男") ? "1" : "2");
						temp.setOrganization_code(person.getIdNumber().trim().replaceAll(" ", "").toUpperCase());
						temp.setBirth_date(IdNumUtil.getBirthdayByIdCard(person.getIdNumber()));
						temp.setMajor_group(person.getPersonType());
						list.add(temp);
					}
				}
				result.setSuccessful(true);
				result.setData(list);
			} else {
				result.setSuccessful(false);
				result.setMsg("未找到指定公司信息。");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}



	/**
	 * 调百联宝（企业）是否有购买保险的接口
	 * @return
	 */
	@RequestMapping("checkCompanyPolicy")
	public @ResponseBody AjaxResult checkCompanyPolicy() throws Exception{
		return companyService.checkCompanyPolicy();
	}


	/**
	 * 创建或更新安保公司信息
	 * @param company 基本信息
	 * @param securityScopes	安保范围
	 * @return
	 */
	@RequestMapping("update")
	public @ResponseBody AjaxResult update(SecurityCompany company, Long[] securityScopes) {
		AjaxResult result = new AjaxResult();
		try {
			User currentUser = arsUtil.getCurrentUser();
			User dbuser = null;
			//服务范围
			if (null != securityScopes && securityScopes.length > 0) {
				company.setSecurityScopeType(StringUtils.join(securityScopes, ","));
				//company.setSecurityScopeType(companyService.changeToARSSafeRange(company.getSecurityScopeType()));
			}
			//判断是否为分公司
			if(Constants.ISSUBHSIDIARY_YES.equals(company.getIsSubsidiary())
					&& Constants.INSTITUTIONTYPE_FWGS.equals(company.getInstitutionType())){
				//类型为0105，saas传过来为0102当成保安服务公司类型
				company.setInstitutionType(Constants.INSTITUTIONTYPE_FGS);
			}
			if(company.getLocal() == null || company.getLocal()){
				//本地公司
				company.setLocal(true);
				if (null == currentUser) {
					dbuser = new User();
					dbuser.setPlatform(Constants.PLATFORM_COMPANY);
					if (StringUtil.isEmpty(company.getInstitutionType())) {
						//saas创建公司，公司类型 为分公司
						if (company.getLocal() == null || company.getLocal()) {
							company.setInstitutionType(Constants.INSTITUTIONTYPE_FGS);
							//分公司
							company.setIsSubsidiary(Constants.ISSUBHSIDIARY_YES);
						}
					}
					//判断是否需要分公司备案，如果需要则saas不能创建分公司
					Config isSubsidiaryApprove =configUtils.getConfigByKey(Constants.IS_SUBSIDIARY_APPROVE);
					if(isSubsidiaryApprove!= null &&  Constants.IS_SUBSIDIARY_APPROVE_YES.equals(isSubsidiaryApprove.getValue()) ) {
						throw new ArsException("【"+company.getName()+"】备案后由系统自动创建，如已备案请联系管理员创建！");
					}
				} else {
					SecurityCompany dbcompany = companyService.findByUserid(currentUser.getId());

					if (null != dbcompany) {
						//注册地监管机构
						if(company.getOrgId()!=null){
							Police p = policeService.findById(Long.valueOf(company.getOrgId()));
							//区域
							company.setAreaCode(p.getAreacode());
							//公司ID
							company.setOrgId(p.getId().toString());
							//公司ID
							company.setOrgName(p.getOrgname());
						}
						//办公地监管机构
						if(company.getOfficeOrgId()!=null){
							Police p = policeService.findById(Long.valueOf(company.getOfficeOrgId()));
							//区域
							company.setOfficeAreaCode(p.getAreacode());
							//公司ID
							company.setOfficeOrgId(p.getId().toString());
							//公司ID
							company.setOfficeOrgName(p.getOrgname());
						}
						//公司ID
						company.setId(dbcompany.getId());
						dbuser = dbcompany.getUser();
					} else {
						throw new ArsException("公司不存在！");
					}
				}
			}else{
				//异地公司
				SecurityCompany dbcompany = companyService.findByComId(Long.parseLong(company.getComId()));
				if (null != dbcompany) {
					//公司ID
					company.setId(dbcompany.getId());
					dbuser = dbcompany.getUser();
				} else {
					dbuser = new User();
					dbuser.setPlatform(Constants.PLATFORM_COMPANY);
				}
			}

			if (dbuser != null) {
				//设置用户名
				if (StringUtil.isNotEmpty(company.getUserRealname())) {
					dbuser.setUsername(company.getUserRealname());
				}
				//设置公司名
				if (StringUtil.isNotEmpty(company.getName())) {
					dbuser.setRealname(company.getName());
				}
				//设置用户联系方式
				if (StringUtil.isNotEmpty(company.getUserPhone())) {
					dbuser.setPhone(company.getUserPhone());
				}
				//设置头像
				if (StringUtil.isNotEmpty(company.getUserPhoto())) {
					dbuser.setPhoto(company.getUserPhoto());
				}
				//更新信息同时把公司的初始化设置为初始化，3.0版本init在列表显示 未登陆或正常
				dbuser.setInit(true);
				company.setInit(true);
				company.setCompanyState(Constants.COMPANY_STATE_1);
				userService.saveOrUpdateCompanyUserForSAAS(dbuser);
				company.setUser(dbuser);
			} else {
				throw new ArsException("公司账户信息不存在！");
			}
			companyService.saveOrUpdateForSAAS(company);
			result.setSuccessful(true);
		} catch(Exception e) {
			result.setSuccessful(false);
			result.setMsg(e.getMessage());
			logger.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 新增或更新公司班次信息
	 * @return
	 */
	@RequestMapping("updateSchedule")
	public @ResponseBody AjaxResult updateSchedule(SecurityCompanySchedule schedule) {
		AjaxResult result = new AjaxResult();
		try {
			SecurityCompany company = companyService.findByUserid(arsUtil.getCurrentUser().getId());
			if(company != null) {
				schedule.setCompanyId(company.getId());
				scheduleService.saveOrUpdate(schedule);
				result.setSuccessful(true);
			} else {
				throw new RuntimeException("无法获取当前公司信息，UserID:" + arsUtil.getCurrentUser().getId());
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/**
	 * 删除公司班次信息
	 * @return
	 */
	@RequestMapping("deleteSchedule")
	public @ResponseBody AjaxResult deleteSchedule(SecurityCompanySchedule schedule) {
		AjaxResult result = new AjaxResult();
		try {
			SecurityCompany company = companyService.findByUserid(arsUtil.getCurrentUser().getId());
			if(company != null) {
				schedule.setCompanyId(company.getId());
				scheduleService.delete(schedule);
				result.setSuccessful(true);
			} else {
				throw new RuntimeException("无法获取当前公司信息，UserID:" + arsUtil.getCurrentUser().getId());
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg(e.getMessage());
		}
		return result;
	}

	/**
	 * 更新证件照片
	 * @return
	 */
	@RequestMapping("updateCertificatesPhoto")
	public @ResponseBody AjaxResult updateCertificatesPhoto(String companys) {
		AjaxResult result = new AjaxResult();
		try {
			List<SecurityCompany> companyList = JSONObject.parseArray(companys,SecurityCompany.class);
			companyList.forEach(company->{
				if(StringUtil.isNotEmpty(company.getBusinessLicense())){
					company.setBusinessLicense(getPhotoPath(company.getBusinessLicense()));
				}
				if(StringUtil.isNotEmpty(company.getPublicSecurityLicense())){
					company.setPublicSecurityLicense(getPhotoPath(company.getPublicSecurityLicense()));
				}
			});
			companyService.updateCertificatesPhoto(companyList);
			result.setSuccessful(true);
		} catch(Exception e) {
			result.setSuccessful(false);
			result.setMsg(e.getMessage());
			logger.error(e.getMessage(),e);
		}
		return result;
	}

	public static void main(String[] args) {
		List<SecurityCompany> companyList = new ArrayList<>();
		for (Integer i = 0; i < 5; i++) {

			SecurityCompany company = new SecurityCompany();
			company.setUsername(i.toString());
			company.setPublicSecurityLicense(i.toString());
			company.setBusinessLicense(i.toString());
			companyList.add(company);
		}



		System.out.println(JSONObject.toJSONString(companyList));
	}
}