package com.unis.base.app.service.impl;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.unis.base.app.feign.MyuserFeign;
import com.unis.base.app.service.CompanyRecordsService;
import com.unis.base.client.CompanyFeign;
import com.unis.base.client.CompanyRecordsFeign;
import com.unis.base.client.EquipmentFeign;
import com.unis.base.common.constant.FilingConstant;
import com.unis.base.common.vo.*;
import com.unis.common.utils.CurrentUtil;
import com.unis.common.utils.JsonUtils;
import com.unis.common.utils.LsBeanUtils;
import com.unis.common.utils.ResponseWrapper;
import com.unis.flowable.client.FlowAbleClient;
import com.unis.flowable.common.vo.FlowAbleCompleteVO;
import com.unis.flowable.common.vo.StartNewTaskVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/** 
 * @ClassName: CompanyRecordsServiceImpl
 * @Description: 企业记录 service实现类
 * @author WangZL
 * @date 2019年9月6日 上午11:18:54  
 */
@Service
public class CompanyRecordsServiceImpl implements CompanyRecordsService {

	@Autowired
	private CompanyRecordsFeign companyRecordsFeign;

	@Autowired
	private EquipmentFeign equipmentFeign;

	@Autowired
	private MyuserFeign myuserFeign;

	@Autowired
	private FlowAbleClient flowAbleClient;

    @Autowired
    private CompanyFeign companyFeign;

	private static final Integer SAVE = 0; //操作状态：保存
	private static final Integer SUBMIT = 1;//操作状态：提交

	private static final String PROCESS_KEY = "SLQYJCXXBADW";
	private static final String STATUS_KEY = "status";

	/**
	 * 分页查询列表
	 * @param companyRecordsQueryVO
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public ResponseWrapper getCompanyRecordsPage(CompanyRecordsQueryVO companyRecordsQueryVO, Integer pageNum, Integer pageSize) {
		ResponseWrapper responseWrapper = null;
		//获取待办列表
		responseWrapper = flowAbleClient.getUserTaskNoPage(CurrentUtil.getUserId());
		//responseWrapper = flowAbleClient.getUserTaskNoPage("userId");
		//便利拼接我的待办，
		String liucheng = ",";
		if(responseWrapper.getInfoCode() != 200) {
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "获取失败", null);
		}
		List<LinkedHashMap> data = (List<LinkedHashMap>) responseWrapper.getData();
		for(LinkedHashMap linkedHashMap:data) {
			String lcid = (String) linkedHashMap.get("procInsId");//获取审批列表数组
			liucheng += lcid +",";
		}
		responseWrapper = companyRecordsFeign.getCompanyRecordsPage(companyRecordsQueryVO, pageNum, pageSize);

		if(responseWrapper.getInfoCode() != 200) {
			return responseWrapper;
		}
		LinkedHashMap pageDate = (LinkedHashMap) responseWrapper.getData();
		List<LinkedHashMap> pageList  = (List<LinkedHashMap>) pageDate.get("list");
		for(LinkedHashMap linkedHashMap: pageList) {
			String lcid = (String) linkedHashMap.get("lcId");
			if(lcid == null) {
				linkedHashMap.put("sfxssh", 0);//改回0
				continue;
			}
			if(liucheng.contains(","+lcid+",")) {//包含，显示审核按钮
				linkedHashMap.put("sfxssh", 1);
			} else {
				linkedHashMap.put("sfxssh", 0);//改回0
			}
		}
		return responseWrapper;
	}

	/**
	 * 企业记录-查询详情
	 * @param  qybabh
	 * @return
	 */
	@Override
	public ResponseWrapper getCompanyRecordsInfoById(String qybabh) {
        ResponseWrapper responseWrapper = null;
        responseWrapper = companyRecordsFeign.getCompanyRecordsInfoById(qybabh);
		if(responseWrapper.getInfoCode() != 200) {
			return responseWrapper;
		}

		//对象Mapper
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		CompanyRecordsVO companyRecordsVO = objectMapper.convertValue(responseWrapper.getData(), CompanyRecordsVO.class);
		//获取设备列表信息
		List<DSbxxsjyVO> dSbxxsjyVOList = new ArrayList<>();
		if (companyRecordsVO != null) {

			ResponseWrapper responseWrapperEquipment = equipmentFeign.getEquipmentListByKddm(companyRecordsVO.getTyshxydm());
			if (responseWrapperEquipment.isSuccess()) {
				List<DSbxxsjyVO> sbxxsjyVOList = JsonUtils.parseList(JsonUtils.serialize(responseWrapperEquipment.getData())
						, DSbxxsjyVO.class);
				if (sbxxsjyVOList != null && sbxxsjyVOList.size() > 0) {
					for (DSbxxsjyVO dSbxxsjyVO : sbxxsjyVOList) {
						dSbxxsjyVOList.add(dSbxxsjyVO);
					}
					companyRecordsVO.setDSbxxsjyVOList(dSbxxsjyVOList);
				}
			} else {
				return responseWrapperEquipment;
			}
		}

		LinkedHashMap zfryzzsq = (LinkedHashMap) responseWrapper.getData();
		zfryzzsq.put("dsbxxsjyVOList", dSbxxsjyVOList);
		String lcid = companyRecordsVO.getLcId();
		if (lcid == null) {
			return responseWrapper;
		}

		//根据流程id获取审批历史
		ResponseWrapper processHis = flowAbleClient.findByProcessInfo(lcid);
		if(processHis.getInfoCode()!=200) {
			return processHis;
		}
		List<LinkedHashMap> linkedHashMaps = (List<LinkedHashMap>) processHis.getData();
		for(LinkedHashMap linkedHashMap : linkedHashMaps) {
			String assigneeName = (String) zfryzzsq.get("assigneeName");//获取审批用户id
			//根据id从用户中心获取用户信息
			//linkedHashMap.put("assigneeName", "肖礼兵");
		}
		zfryzzsq.put("processHis", processHis.getData());//添加审批历史信息
		return responseWrapper;
	}

	/**
	 *根据状态新增
	 * @param companyRecordsVO
	 * @param type
	 * @return
	 */
	@Override
	public ResponseWrapper insertCompanyRecords(CompanyRecordsVO companyRecordsVO, Integer type) {

		String zzqUsers = "";
		ResponseWrapper responseWrapper = null;
		responseWrapper = myuserFeign.getUserByRole(new String[] {"R0000085"});//获取库区主任角色
		if(responseWrapper.getInfoCode()!=200) {
			return ResponseWrapper.error("获取库区主任信息失败");
		}
		//获取自治区用户信息
		List<LinkedHashMap> datas =  (List<LinkedHashMap>) responseWrapper.getData();
		for(LinkedHashMap linkedHashMap:datas) {
			zzqUsers += (String) linkedHashMap.get("userCode");//获取审批列表数组
		}

		StartNewTaskVO startNewTaskVO = null;//初始化流程对象
		FlowAbleCompleteVO completeVO = null;
		if (type == SAVE){
			//当保存时，备案状态为待提交
			companyRecordsVO.setSfba(FilingConstant.TO_BE_SUBMIT.getValue());
		} else if (type == SUBMIT) {
			//当提交时，备案状态为待库区主任审批
			companyRecordsVO.setSfba(FilingConstant.TO_BE_SUBMIT.getValue());

			startNewTaskVO = new StartNewTaskVO();
			startNewTaskVO.setProcessKey(PROCESS_KEY);
			startNewTaskVO.setStatusKey(STATUS_KEY);
			startNewTaskVO.setStatus("1");//标识盟市提交
			startNewTaskVO.setUserId(CurrentUtil.getUserId());

			//审批对象拼接
			completeVO = new FlowAbleCompleteVO();
			completeVO.setStatusKey(STATUS_KEY);//状态标识
			completeVO.setUserId(CurrentUtil.getUserId());//当前用户审批
			completeVO.setMessage("提交");//审批意见
			completeVO.setAssignee(zzqUsers);
			completeVO.setStatus("1");//表示提交审核
		}

		companyRecordsVO.setStatus(1);
		companyRecordsVO.setCreator(CurrentUtil.getUserName());
		companyRecordsVO.setCreatorCode(CurrentUtil.getUserId());
		companyRecordsVO.setCreateDate(new Date());

        //新增设备/设施/仪器列表信息
        List<DSbxxsjyVO> dSbxxsjyVOList = companyRecordsVO.getDSbxxsjyVOList();
        if (dSbxxsjyVOList != null && dSbxxsjyVOList.size() > 0) {
            for (DSbxxsjyVO dSbxxsjyVO : dSbxxsjyVOList) {
                dSbxxsjyVO.setStatus(1);
                dSbxxsjyVO.setCreator(CurrentUtil.getUserName());
                dSbxxsjyVO.setCreateDate(new Date());
                ResponseWrapper responseWrapperResponse = equipmentFeign.insert(dSbxxsjyVO);
                if (!responseWrapperResponse.isSuccess()){
                    return responseWrapperResponse;
                }
            }
        }

		ResponseWrapper infoResponse = companyRecordsFeign.insert(companyRecordsVO);
		if (infoResponse.getInfoCode() == 200) {
			String qybabh = infoResponse.getData().toString();

			if (startNewTaskVO != null){
				startNewTaskVO.setId(qybabh);
				responseWrapper = flowAbleClient.start(startNewTaskVO);//启动流程
				//启动成功进行流程与数据进行绑定
				if(responseWrapper.getInfoCode() == 200) {
					LinkedHashMap data =  (LinkedHashMap) responseWrapper.getData();
					String lcId =  (String) data.get("processId");//获取到流程id
					companyRecordsVO.setLcId(lcId);
					companyRecordsVO.setQybabh(qybabh);
					companyRecordsFeign.update(companyRecordsVO);

					completeVO.setProcessId(lcId);
					responseWrapper = flowAbleClient.complete(completeVO);//进行第一次上报
					if(responseWrapper.getInfoCode() == 200) {//标识上报到自治区成功
						companyRecordsVO.setSfba(FilingConstant.TO_BE_KQZR_APPROVAL.getValue());//结果为待库区主任审批
						return  companyRecordsFeign.update(companyRecordsVO);
					}
				}else {
					return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"启动流程失败",null);
				}
			}
		}
		return ResponseWrapper.success(HttpStatus.OK.value(), "操作成功",null);
	}

	/**
	 * 提交
	 * @param qybabh
	 * @return
	 */
	@Override
	public ResponseWrapper companyRecordsRelay(String qybabh) {

		String zzqUsers = "";
		ResponseWrapper responseWrapper = null;
		responseWrapper = myuserFeign.getUserByRole(new String[] {"R0000085"});//获取库区主任角色
		if(responseWrapper.getInfoCode()!=200) {
			return ResponseWrapper.error("获取库区主任信息失败");
		}
		//获取自治区用户信息
		List<LinkedHashMap> datas =  (List<LinkedHashMap>) responseWrapper.getData();
		for(LinkedHashMap linkedHashMap:datas) {
			zzqUsers += (String) linkedHashMap.get("userCode");//获取审批列表数组
		}

		StartNewTaskVO startNewTaskVO = null;
		FlowAbleCompleteVO completeVO = null;

		startNewTaskVO = new StartNewTaskVO();
		startNewTaskVO.setProcessKey(PROCESS_KEY);
		startNewTaskVO.setStatusKey(STATUS_KEY);
		startNewTaskVO.setStatus("1");
		startNewTaskVO.setUserId(CurrentUtil.getUserId());
		startNewTaskVO.setId(qybabh);

		//审批对象拼接
		completeVO = new FlowAbleCompleteVO();
		completeVO.setStatusKey(STATUS_KEY);//状态标识
		completeVO.setUserId(CurrentUtil.getUserId());//当前用户审批
		completeVO.setMessage("提交");//审批意见
		completeVO.setAssignee(zzqUsers);
		completeVO.setStatus("1");//表示提交审核

		ResponseWrapper rw = companyRecordsFeign.getCompanyRecordsInfoById(qybabh);
		if(rw.getInfoCode() == 200) {
			//对象Mapper
			ObjectMapper objectMapper = new ObjectMapper();
			objectMapper.setSerializationInclusion(Include.ALWAYS);
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
			CompanyRecordsVO companyRecordsVO = objectMapper.convertValue(rw.getData(), CompanyRecordsVO.class);



			responseWrapper = flowAbleClient.start(startNewTaskVO);//启动流程
			//启动成功进行流程与数据进行绑定
			if(responseWrapper.getInfoCode() == 200) {//标识启动成功
				LinkedHashMap data =  (LinkedHashMap) responseWrapper.getData();
				String lcId =  (String) data.get("processId");//获取到流程id
				companyRecordsVO.setLcId(lcId);
				companyRecordsFeign.update(companyRecordsVO);
				//进行第一次审批
				completeVO.setProcessId(lcId);
				responseWrapper = flowAbleClient.complete(completeVO);//进行第一次转发

				if(responseWrapper.getInfoCode() == 200) {//标识上报到库区主任成功
					companyRecordsVO.setSfba(FilingConstant.TO_BE_KQZR_APPROVAL.getValue());//带库区主任审批
					return  companyRecordsFeign.update(companyRecordsVO);
				} else {//失败标识审核失败进行库点记录保存可再次提交
					return  ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"企业提交失败，请稍后！",null);
				}
			}else {
				return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"启动流程失败",null);
			}
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"企业提交失败",null);
	}

	/**
	 * 库区主任审批
	 * @param examineStampVO
	 * @return
	 */
	@Override
	public ResponseWrapper companyRecordsDirectorExamine(ExamineStampVO examineStampVO) {
		String zzqUsers = "";
		ResponseWrapper responseWrapper = null;
		responseWrapper = myuserFeign.getUserByRole(new String[] {"R0000086"});//待区粮办审批
		if(responseWrapper.getInfoCode()!=200) {
			return ResponseWrapper.error("获取区粮办信息失败");
		}
		//获取自治区用户信息
		List<LinkedHashMap> datas =  (List<LinkedHashMap>) responseWrapper.getData();
		for(LinkedHashMap linkedHashMap:datas) {
			zzqUsers += (String) linkedHashMap.get("userCode");//获取审批列表数组
		}

		ResponseWrapper rw = companyRecordsFeign.getCompanyRecordsInfoById(examineStampVO.getId());
		if(rw.getInfoCode() == 200 && rw.getData() != null) {
			//对象Mapper
			ObjectMapper objectMapper = new ObjectMapper();
			objectMapper.setSerializationInclusion(Include.ALWAYS);
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
			CompanyRecordsVO companyRecordsVO = objectMapper.convertValue(rw.getData(), CompanyRecordsVO.class);

			FlowAbleCompleteVO completeVO = new FlowAbleCompleteVO();
			completeVO.setProcessId(companyRecordsVO.getLcId());
			completeVO.setStatusKey(STATUS_KEY);
			Integer status = examineStampVO.getStatus();
			if(status == 0) {
				completeVO.setStatus("2");//驳回状态为2
			}else if(status == 1) {
				completeVO.setStatus("1");//通过状态为1
			}
			completeVO.setAssignee(zzqUsers);
			completeVO.setMessage(examineStampVO.getMessage());
			completeVO.setUserId(CurrentUtil.getUserId());
			ResponseWrapper flowResponse = flowAbleClient.complete(completeVO);
			if(flowResponse.getInfoCode() == 200) {
				if(status == 0) {
					companyRecordsVO.setSfba(FilingConstant.REJECTED.getValue());
				}else if(status == 1) {//通过传给区粮办审批
					companyRecordsVO.setSfba(FilingConstant.TO_BE_QLB_APPROVAL.getValue());
				}
				companyRecordsVO.setRefreshTime(new Date());
				companyRecordsVO.setRefresher(CurrentUtil.getUserName());
				companyRecordsVO.setRefresherCode(CurrentUtil.getUserId());
				companyRecordsFeign.update(companyRecordsVO);

				return ResponseWrapper.success(HttpStatus.OK.value(), "库区主任审批成功",null);
			}else {
				return flowResponse;
			}
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"库区主任审批失败",null);
	}



	/**
	 * 区粮办审批
	 * @param examineStampVO
	 * @return
	 */
	@Override
	public ResponseWrapper companyRecordsDistrictExamine(ExamineStampVO examineStampVO) {


		ResponseWrapper rw = companyRecordsFeign.getCompanyRecordsInfoById(examineStampVO.getId());
		if(rw.getInfoCode() == 200 && rw.getData() != null) {
			//对象Mapper
			ObjectMapper objectMapper = new ObjectMapper();
			objectMapper.setSerializationInclusion(Include.ALWAYS);
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
			CompanyRecordsVO companyRecordsVO = objectMapper.convertValue(rw.getData(), CompanyRecordsVO.class);

			FlowAbleCompleteVO completeVO = new FlowAbleCompleteVO();
			completeVO.setProcessId(companyRecordsVO.getLcId());
			completeVO.setStatusKey(STATUS_KEY);
			Integer status = examineStampVO.getStatus();
			if(status == 0) {
				completeVO.setStatus("2");//驳回状态为2
			}else if(status == 1) {
				completeVO.setStatus("1");//通过状态为1
			}
			completeVO.setMessage(examineStampVO.getMessage());
			completeVO.setUserId(CurrentUtil.getUserId());
			ResponseWrapper flowResponse = flowAbleClient.complete(completeVO);
			if(flowResponse.getInfoCode() == 200) {
				if(status == 0) {
					companyRecordsVO.setSfba(FilingConstant.REJECTED.getValue());
				}else if(status == 1) {//通过已审批
					companyRecordsVO.setSfba(FilingConstant.FILING.getValue());
				}
				companyRecordsVO.setRefreshTime(new Date());
				companyRecordsVO.setRefresher(CurrentUtil.getUserName());
				companyRecordsVO.setRefresherCode(CurrentUtil.getUserId());
                ResponseWrapper companyRecordsUpdate = companyRecordsFeign.update(companyRecordsVO);
                if (companyRecordsUpdate.getInfoCode() == 200){
                    if (companyRecordsVO.getSfba().equals(FilingConstant.FILING.getValue())){
                        //更新主表数据
                        CompanyVO companyVO = new CompanyVO();
                        LsBeanUtils.copyAllProperties(companyRecordsVO,companyVO);
                        ResponseWrapper companyUpdate = companyFeign.update(companyVO);
                        if (companyUpdate.getInfoCode() != 200){
                            return companyUpdate;
                        }
                    }
                }

				return ResponseWrapper.success(HttpStatus.OK.value(), "区粮办审批成功",null);
			}else {
				return flowResponse;
			}
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"区粮办审批失败",null);
	}


}
