package com.sifang.modules.changes.service;

import cn.hutool.core.util.IdUtil;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.dao.CustomerEntryChangeRecordDao;
import com.sifang.modules.changes.dao.CustomerEntrySurveyChangeRecordDao;
import com.sifang.modules.changes.dao.CustomerEntrySurveyChangeRecordDetailDao;
import com.sifang.modules.changes.entity.CustomerEntrySurveyChangeRecord;
import com.sifang.modules.changes.entity.CustomerEntrySurveyChangeRecordDetail;
import com.sifang.modules.changes.vo.AddSurveyChangeRecordVo;
import com.sifang.modules.changes.vo.AnyProductSurveryChangeVo;
import com.sifang.modules.changes.vo.SurveyAuditVo;
import com.sifang.modules.customer.Service.CustomerEntryMsgService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.Service.GuangFaManagemnetService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.AddEntryReqSurveyDetail;
import com.sifang.modules.flowable.constants.ItemConstants;
import com.sifang.modules.flowable.dao.ItemManageDao;
import com.sifang.modules.flowable.dao.ItemTaskDetailDao;
import com.sifang.modules.flowable.entity.ItemManage;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.setting.constant.ProcessSetConstants;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.FormSetUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.taskdispatch.dao.CrmReviewDispatchDao;
import com.sifang.modules.taskdispatch.service.CrmPriorReviewSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author DQChen
 * @date 2024-03-27 9:33
 */
@Service
public class CustomerEntrySurveyChangeRecordService extends BaseService {

	@Autowired
	CustomerEntryDao entryDao;

	@Autowired
	CustomerEntrySurveyChangeRecordDao changeRecordDao;

	@Autowired
	CustomerEntryMsgService entryMsgService;

	@Autowired
	CustomerEntrySurveyRecordDao surveyRecordDao;

	@Autowired
	CustomerEntryService customerEntryService;

	@Autowired
	private CustomerEntryOrgFilesDao orgFilesDao;

	@Autowired
	private CrmCustomerIncomingApplicationDao applicationDao;

	@Autowired
	private ItemTaskDetailDao itemTaskDetailDao;

	@Autowired
	private ItemManageDao itemManageDao;
	@Autowired
	private CrmReviewDispatchDao reviewDispatchDao;
	@Autowired
	GuangFaManagemnetService guangFaManagemnetService;
	@Autowired
	private CustomerEntryChangeRecordDao customerEntryChangeRecordDao;

	@Autowired
	private CustomerEntrySurveyChangeRecordDetailDao surveyChangeRecordDetailDao;

	@Autowired
	private CrmCustomerEntrySurveyRecordDetailDao crmCustomerEntrySurveyRecordDetailDao;

	@Autowired
	private CrmPriorReviewSettingService crmPriorReviewSettingService;

	public CustomerEntrySurveyChangeRecord selectById(String id) {
		return changeRecordDao.get(id);
	}

	public CustomerEntrySurveyChangeRecord selectPre(String entryId, int num) {
		return changeRecordDao.selectPre(entryId, num);
	}

	public void listData(LayuiPage<Record> page, Map<String, String> reqMap, String flag,Operator operator) {
		page.setData(changeRecordDao.selectList(page, reqMap, flag, operator));
	}

	public long selectNoAudited(String entryId) {
		return changeRecordDao.selectNoAudited(entryId, null);
	}

	/**
	 * 添加变更记录
	 * @param recordVo
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result addChangeRecord(AddSurveyChangeRecordVo recordVo) {
		if (StringUtil.isAnyBlank(recordVo.getEntryId())) {
			return Result.fail("缺少必要数据");
		}
		if (changeRecordDao.selectNoAudited(recordVo.getEntryId(), null) > 0) {
			return Result.fail("该电站有待审核的变更记录，请审核后再提交");
		}
		if (customerEntryChangeRecordDao.getIfHaveSurveyChange(recordVo.getEntryId()) > 0) {
			return Result.fail("该电站有待资方审核的变更记录，请审核后再提交");
		}

		CustomerEntry entry = entryDao.get(recordVo.getEntryId());
		CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(recordVo.getEntryId());

		if (StringUtil.equals(recordVo.getFlyImgs(), surveyRecord.getFlyImgs())
				&& StringUtil.equals(recordVo.getRoofPhotoOne(), surveyRecord.getRoofPhotoOne())
				&& StringUtil.equals(recordVo.getRoofPhotoTwo(), surveyRecord.getRoofPhotoTwo())
				&& StringUtil.equals(recordVo.getRoofPhotoThree(), surveyRecord.getRoofPhotoThree())
				&& StringUtil.equals(recordVo.getRoofPhotoFour(), surveyRecord.getRoofPhotoFour())
				&& StringUtil.equals(recordVo.getRoofPhotoFacade(), surveyRecord.getRoofPhotoFacade())
				&& StringUtil.equals(recordVo.getRoofPhotoInterior(), surveyRecord.getRoofPhotoInterior())
				&& StringUtil.equals(recordVo.getRoofPhotoFive(), surveyRecord.getRoofPhotoFive())
				&& StringUtil.equals(recordVo.getHouseSupplementOne(), surveyRecord.getHouseSupplementOne())
				&& StringUtil.equals(recordVo.getDetailSupplementOne(), surveyRecord.getDetailSupplementOne())
				&& StringUtil.equals(recordVo.getSurveyVideo(), surveyRecord.getSurveyVideo())
				&& StringUtil.equals(recordVo.getSurveyFiles(), surveyRecord.getSurveyFiles())
				&& StringUtil.equals(recordVo.getHouseOutlinePhoto(), surveyRecord.getHouseOutlinePhoto())
				&& StringUtil.equals(recordVo.getVrRoofOne(), surveyRecord.getVrRoofOne())
				&& StringUtil.equals(recordVo.getVrRoofTwo(), surveyRecord.getVrRoofTwo())
				&& StringUtil.equals(recordVo.getVrRoofThree(), surveyRecord.getVrRoofThree())
				&& StringUtil.equals(recordVo.getVrRoofFour(), surveyRecord.getVrRoofFour())
				&& StringUtil.equals(recordVo.getFwImg1(), surveyRecord.getFwImg1())
				&& StringUtil.equals(recordVo.getFwImg2(), surveyRecord.getFwImg2())
				&& StringUtil.equals(recordVo.getFwImg3(), surveyRecord.getFwImg3())
				&& StringUtil.equals(recordVo.getFwImg4(), surveyRecord.getFwImg4())
				&& StringUtil.equals(recordVo.getFwImg5(), surveyRecord.getFwImg5())
		) {
			return Result.fail("请至少修改一条数据");
		}

		//获取当前已变更次数
		User user = UserUtils.getUser();
		Date now = new Date();
		CustomerEntrySurveyChangeRecord record = new CustomerEntrySurveyChangeRecord();
		Integer maxNum = changeRecordDao.selectMaxNum(recordVo.getEntryId());
		if (maxNum == null) {
			record.setNum(1);
			//把第一次的存起来
			CustomerEntrySurveyChangeRecord zeroRecord = new CustomerEntrySurveyChangeRecord();
			zeroRecord.setId(IdGen.uuid());
			zeroRecord.setNum(0);
			zeroRecord.setNumber(PlantformUtils.getOrderNumber());
			zeroRecord.setEntryId(entry.getId());
			zeroRecord.setPowerStationCode(entry.getPowerStationCode());
			zeroRecord.setType("0");
			zeroRecord.setFlyImgs(surveyRecord.getFlyImgs());
			zeroRecord.setRoofPhotoOne(surveyRecord.getRoofPhotoOne());
			zeroRecord.setRoofPhotoTwo(surveyRecord.getRoofPhotoTwo());
			zeroRecord.setRoofPhotoThree(surveyRecord.getRoofPhotoThree());
			zeroRecord.setRoofPhotoFour(surveyRecord.getRoofPhotoFour());
			zeroRecord.setRoofPhotoFacade(surveyRecord.getRoofPhotoFacade());
			zeroRecord.setRoofPhotoInterior(surveyRecord.getRoofPhotoInterior());
			zeroRecord.setRoofPhotoFive(surveyRecord.getRoofPhotoFive());
			zeroRecord.setHouseSupplementOne(surveyRecord.getHouseSupplementOne());
			zeroRecord.setDetailSupplementOne(surveyRecord.getDetailSupplementOne());
			zeroRecord.setSurveyVideo(surveyRecord.getSurveyVideo());
			zeroRecord.setSurveyFiles(surveyRecord.getSurveyFiles());
			zeroRecord.setHouseOutlinePhoto(surveyRecord.getHouseOutlinePhoto());
			zeroRecord.setVrRoofOne(surveyRecord.getVrRoofOne());
			zeroRecord.setVrRoofTwo(surveyRecord.getVrRoofTwo());
			zeroRecord.setVrRoofThree(surveyRecord.getVrRoofThree());
			zeroRecord.setVrRoofFour(surveyRecord.getVrRoofFour());
			zeroRecord.setFwImg1(surveyRecord.getFwImg1());
			zeroRecord.setFwImg2(surveyRecord.getFwImg2());
			zeroRecord.setFwImg3(surveyRecord.getFwImg3());
			zeroRecord.setFwImg4(surveyRecord.getFwImg4());
			zeroRecord.setFwImg5(surveyRecord.getFwImg5());
			zeroRecord.setStatus("1");
			zeroRecord.setCreator(CrmUtils.getUserXM(user));
			zeroRecord.setCreateBy(user.getId());
			zeroRecord.setCreateTime(now);
			changeRecordDao.save(zeroRecord);
		} else {
			record.setNum(maxNum + 1);
		}
		record.setId(IdGen.uuid());
		record.setNumber(PlantformUtils.getOrderNumber());
		record.setEntryId(recordVo.getEntryId());
		record.setPowerStationCode(entry.getPowerStationCode());
		record.setType("0");
		record.setFlyImgs(recordVo.getFlyImgs());
		record.setRoofPhotoOne(recordVo.getRoofPhotoOne());
		record.setRoofPhotoTwo(recordVo.getRoofPhotoTwo());
		record.setRoofPhotoThree(recordVo.getRoofPhotoThree());
		record.setRoofPhotoFour(recordVo.getRoofPhotoFour());
		record.setRoofPhotoFacade(recordVo.getRoofPhotoFacade());
		record.setRoofPhotoInterior(recordVo.getRoofPhotoInterior());
		record.setRoofPhotoFive(recordVo.getRoofPhotoFive());
		record.setHouseSupplementOne(recordVo.getHouseSupplementOne());
		record.setDetailSupplementOne(recordVo.getDetailSupplementOne());
		record.setSurveyVideo(recordVo.getSurveyVideo());
		record.setSurveyFiles(recordVo.getSurveyFiles());
		record.setHouseOutlinePhoto(recordVo.getHouseOutlinePhoto());
		record.setVrRoofOne(recordVo.getVrRoofOne());
		record.setVrRoofTwo(recordVo.getVrRoofTwo());
		record.setVrRoofThree(recordVo.getVrRoofThree());
		record.setVrRoofFour(recordVo.getVrRoofFour());
		record.setFwImg1(recordVo.getFwImg1());
		record.setFwImg2(recordVo.getFwImg2());
		record.setFwImg3(recordVo.getFwImg3());
		record.setFwImg4(recordVo.getFwImg4());
		record.setFwImg5(recordVo.getFwImg5());
		record.setReason(recordVo.getReason());
		record.setStatus("0");
		record.setCreator(CrmUtils.getUserXM(user));
		record.setCreateBy(user.getId());
		record.setCreateTime(now);
		record.setAuditRemark("");
		changeRecordDao.save(record);

		entryMsgService.saveCustomerEntryMsg(Operator.of(user), entry.getId(), CustomerEntryConstants.ENTRY_ADD_CHANGE
				, String.format("第%d次提交电站勘测信息变更申请", record.getNum()), null);

		//所有的变更审核 要走待办事项审批流程，默认审批人为原审核人员  勘测信息变更审核 查询的是设计审核/勘测信息变更审核人；
		String stationName = CrmUtils.getStationName(entry);
		ItemManage itemManage=itemManageDao.addItemChange(FormUtils.ENTRY_CHANGE_KCBG,record.getEntryId(),record.getId(),"勘测信息变更("+stationName+"-"+entry.getPowerStationCode()+")-"+ DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,user.getUserName());
		//获取最近一次 档案审核/客户信息变更审核人
		String userId=itemManageDao.getLastAuditUserId("91,95",record.getEntryId());
		if(StringUtil.isNotBlank(userId)){
//			itemManage.setAssignAuditUserId(userId);
			itemManage.setPreferUserId(userId);
		}
		itemManageDao.save(itemManage);
		//大代理商优先审核
		String groupName = "设计审核";
		crmPriorReviewSettingService.traderPriorityReview(entry.getCreateTraderId(),itemManage.getId(),groupName);
		return Result.ok();
	}

	public List<CustomerEntrySurveyChangeRecordDetail> getBySurveyChangeId(String id){
		return surveyChangeRecordDetailDao.findByChangeRecord(id);
	}


	/**
	 * 添加变更记录---多产品
	 * @param recordVo
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result addAnyProductChangeRecord(AnyProductSurveryChangeVo recordVo) {
		if (StringUtil.isAnyBlank(recordVo.getEntryId())) {
			return Result.fail("缺少必要数据");
		}
		if (changeRecordDao.selectNoAudited(recordVo.getEntryId(), null) > 0) {
			return Result.fail("该电站有待审核的变更记录，请审核后再提交");
		}
		if (customerEntryChangeRecordDao.getIfHaveSurveyChange(recordVo.getEntryId()) > 0) {
			return Result.fail("该电站有待资方审核的变更记录，请审核后再提交");
		}

		CustomerEntry entry = entryDao.get(recordVo.getEntryId());
		CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(recordVo.getEntryId());
        //华融多产品-勘测信息（历史信息）
		List<CrmCustomerEntrySurveyRecordDetail> oldEntrySurveys = crmCustomerEntrySurveyRecordDetailDao.findByEntryId(entry.getId());
		Map<String,CrmCustomerEntrySurveyRecordDetail> oldEntrySurveysMap = oldEntrySurveys.stream().collect(Collectors.toMap(e -> e.getProjectId(), e -> e, (a, b) -> a));
		List<AddEntryReqSurveyDetail> recordDetails=recordVo.getAddEntryReqSurveyDetails();
		int sameCount=0;
		for(AddEntryReqSurveyDetail detail:recordDetails){
			CrmCustomerEntrySurveyRecordDetail oldEntrySurve=oldEntrySurveysMap.get(detail.getProjectId());

			if (StringUtil.equals(detail.getFlyImgs(), oldEntrySurve.getFlyImgs())
					&& StringUtil.equals(detail.getRoofPhotoOne(), oldEntrySurve.getRoofPhotoOne())
					&& StringUtil.equals(detail.getRoofPhotoTwo(), oldEntrySurve.getRoofPhotoTwo())
					&& StringUtil.equals(detail.getRoofPhotoThree(), oldEntrySurve.getRoofPhotoThree())
					&& StringUtil.equals(detail.getRoofPhotoFour(), oldEntrySurve.getRoofPhotoFour())
					&& StringUtil.equals(detail.getRoofPhotoFacade(), oldEntrySurve.getRoofPhotoFacade())
					&& StringUtil.equals(detail.getRoofPhotoInterior(), oldEntrySurve.getRoofPhotoInterior())
					&& StringUtil.equals(detail.getRoofPhotoFive(), oldEntrySurve.getRoofPhotoFive())
					&& StringUtil.equals(detail.getHouseSupplementOne(), oldEntrySurve.getHouseSupplementOne())
					&& StringUtil.equals(detail.getDetailSupplementOne(), oldEntrySurve.getDetailSupplementOne())
					&& StringUtil.equals(detail.getSurveyVideo(), oldEntrySurve.getSurveyVideo())
					&& StringUtil.equals(detail.getSurveyFiles(), oldEntrySurve.getSurveyFiles())
					&& StringUtil.equals(detail.getHouseOutlinePhoto(), oldEntrySurve.getHouseOutlinePhoto())
					&& StringUtil.equals(detail.getVrRoofOne(), oldEntrySurve.getVrRoofOne())
					&& StringUtil.equals(detail.getVrRoofTwo(), oldEntrySurve.getVrRoofTwo())
					&& StringUtil.equals(detail.getVrRoofThree(), oldEntrySurve.getVrRoofThree())
					&& StringUtil.equals(detail.getVrRoofFour(), oldEntrySurve.getVrRoofFour())
					&& StringUtil.equals(detail.getFwImg1(), oldEntrySurve.getFwImg1())
					&& StringUtil.equals(detail.getFwImg2(), oldEntrySurve.getFwImg2())
					&& StringUtil.equals(detail.getFwImg3(), oldEntrySurve.getFwImg3())
					&& StringUtil.equals(detail.getFwImg4(), oldEntrySurve.getFwImg4())
					&& StringUtil.equals(detail.getFwImg5(), oldEntrySurve.getFwImg5())
			) {
				sameCount++;
			}
		}
		if(sameCount==recordDetails.size()){
			return Result.fail("请至少修改一条数据");
		}

		//获取当前已变更次数
		User user = UserUtils.getUser();
		Date now = new Date();
		CustomerEntrySurveyChangeRecord record = new CustomerEntrySurveyChangeRecord();
		Integer maxNum = changeRecordDao.selectMaxNum(recordVo.getEntryId());
		List<CustomerEntrySurveyChangeRecordDetail> changeRecordDetails=new ArrayList<>();
		if (maxNum == null) {
			record.setNum(1);
			//把第一次的存起来
			CustomerEntrySurveyChangeRecord zeroRecord = new CustomerEntrySurveyChangeRecord();
			zeroRecord.setId(IdGen.uuid());
			zeroRecord.setNum(0);
			zeroRecord.setNumber(PlantformUtils.getOrderNumber());
			zeroRecord.setEntryId(entry.getId());
			zeroRecord.setPowerStationCode(entry.getPowerStationCode());
			zeroRecord.setType("0");

            for(CrmCustomerEntrySurveyRecordDetail surveyRecordDetail:oldEntrySurveys){
				CustomerEntrySurveyChangeRecordDetail surveyChangeRecordDetail=new CustomerEntrySurveyChangeRecordDetail();
				surveyChangeRecordDetail.setNumber(zeroRecord.getNumber());
				surveyChangeRecordDetail.setEntryId(zeroRecord.getEntryId());
				surveyChangeRecordDetail.setPowerStationCode(zeroRecord.getPowerStationCode());
				surveyChangeRecordDetail.setChangeRecordId(zeroRecord.getId());
				surveyChangeRecordDetail.setProjectId(surveyRecordDetail.getProjectId());
				surveyChangeRecordDetail.setFlyImgs(surveyRecordDetail.getFlyImgs());
				surveyChangeRecordDetail.setRoofPhotoOne(surveyRecordDetail.getRoofPhotoOne());
				surveyChangeRecordDetail.setRoofPhotoTwo(surveyRecordDetail.getRoofPhotoTwo());
				surveyChangeRecordDetail.setRoofPhotoThree(surveyRecordDetail.getRoofPhotoThree());
				surveyChangeRecordDetail.setRoofPhotoFour(surveyRecordDetail.getRoofPhotoFour());
				surveyChangeRecordDetail.setRoofPhotoFacade(surveyRecordDetail.getRoofPhotoFacade());
				surveyChangeRecordDetail.setRoofPhotoInterior(surveyRecordDetail.getRoofPhotoInterior());
				surveyChangeRecordDetail.setRoofPhotoFive(surveyRecordDetail.getRoofPhotoFive());
				surveyChangeRecordDetail.setHouseSupplementOne(surveyRecordDetail.getHouseSupplementOne());
				surveyChangeRecordDetail.setDetailSupplementOne(surveyRecordDetail.getDetailSupplementOne());
				surveyChangeRecordDetail.setSurveyVideo(surveyRecordDetail.getSurveyVideo());
				surveyChangeRecordDetail.setSurveyFiles(surveyRecordDetail.getSurveyFiles());
				surveyChangeRecordDetail.setHouseOutlinePhoto(surveyRecordDetail.getHouseOutlinePhoto());
				surveyChangeRecordDetail.setVrRoofOne(surveyRecordDetail.getVrRoofOne());
				surveyChangeRecordDetail.setVrRoofTwo(surveyRecordDetail.getVrRoofTwo());
				surveyChangeRecordDetail.setVrRoofThree(surveyRecordDetail.getVrRoofThree());
				surveyChangeRecordDetail.setVrRoofFour(surveyRecordDetail.getVrRoofFour());
				surveyChangeRecordDetail.setFwImg1(surveyRecordDetail.getFwImg1());
				surveyChangeRecordDetail.setFwImg2(surveyRecordDetail.getFwImg2());
				surveyChangeRecordDetail.setFwImg3(surveyRecordDetail.getFwImg3());
				surveyChangeRecordDetail.setFwImg4(surveyRecordDetail.getFwImg4());
				surveyChangeRecordDetail.setFwImg5(surveyRecordDetail.getFwImg5());
				changeRecordDetails.add(surveyChangeRecordDetail);
			}

			zeroRecord.setStatus("1");
			zeroRecord.setCreator(CrmUtils.getUserXM(user));
			zeroRecord.setCreateBy(user.getId());
			zeroRecord.setCreateTime(now);
			changeRecordDao.save(zeroRecord);
		} else {
			record.setNum(maxNum + 1);
		}

		record.setId(IdGen.uuid());
		record.setNumber(PlantformUtils.getOrderNumber());
		record.setEntryId(recordVo.getEntryId());
		record.setPowerStationCode(entry.getPowerStationCode());
		record.setType("0");

		for(AddEntryReqSurveyDetail newDetail:recordDetails){
			CustomerEntrySurveyChangeRecordDetail newChangeRecordDetail=new CustomerEntrySurveyChangeRecordDetail();
			newChangeRecordDetail.setNumber(record.getNumber());
			newChangeRecordDetail.setEntryId(record.getEntryId());
			newChangeRecordDetail.setPowerStationCode(record.getPowerStationCode());
			newChangeRecordDetail.setChangeRecordId(record.getId());
			newChangeRecordDetail.setProjectId(newDetail.getProjectId());
			newChangeRecordDetail.setFlyImgs(newDetail.getFlyImgs());
			newChangeRecordDetail.setRoofPhotoOne(newDetail.getRoofPhotoOne());
			newChangeRecordDetail.setRoofPhotoTwo(newDetail.getRoofPhotoTwo());
			newChangeRecordDetail.setRoofPhotoThree(newDetail.getRoofPhotoThree());
			newChangeRecordDetail.setRoofPhotoFour(newDetail.getRoofPhotoFour());
			newChangeRecordDetail.setRoofPhotoFacade(newDetail.getRoofPhotoFacade());
			newChangeRecordDetail.setRoofPhotoInterior(newDetail.getRoofPhotoInterior());
			newChangeRecordDetail.setRoofPhotoFive(newDetail.getRoofPhotoFive());
			newChangeRecordDetail.setHouseSupplementOne(newDetail.getHouseSupplementOne());
			newChangeRecordDetail.setDetailSupplementOne(newDetail.getDetailSupplementOne());
			newChangeRecordDetail.setSurveyVideo(newDetail.getSurveyVideo());
			newChangeRecordDetail.setSurveyFiles(newDetail.getSurveyFiles());
			newChangeRecordDetail.setHouseOutlinePhoto(newDetail.getHouseOutlinePhoto());
			newChangeRecordDetail.setVrRoofOne(newDetail.getVrRoofOne());
			newChangeRecordDetail.setVrRoofTwo(newDetail.getVrRoofTwo());
			newChangeRecordDetail.setVrRoofThree(newDetail.getVrRoofThree());
			newChangeRecordDetail.setVrRoofFour(newDetail.getVrRoofFour());
			newChangeRecordDetail.setFwImg1(newDetail.getFwImg1());
			newChangeRecordDetail.setFwImg2(newDetail.getFwImg2());
			newChangeRecordDetail.setFwImg3(newDetail.getFwImg3());
			newChangeRecordDetail.setFwImg4(newDetail.getFwImg4());
			newChangeRecordDetail.setFwImg5(newDetail.getFwImg5());
			changeRecordDetails.add(newChangeRecordDetail);
		}
		record.setReason(recordVo.getReason());
		record.setStatus("0");
		record.setCreator(CrmUtils.getUserXM(user));
		record.setCreateBy(user.getId());
		record.setCreateTime(now);
		record.setAuditRemark("");
		changeRecordDao.save(record);

		surveyChangeRecordDetailDao.save(changeRecordDetails);

		entryMsgService.saveCustomerEntryMsg(Operator.of(user), entry.getId(), CustomerEntryConstants.ENTRY_ADD_CHANGE
				, String.format("第%d次提交电站勘测信息变更申请", record.getNum()), null);

		//所有的变更审核 要走待办事项审批流程，默认审批人为原审核人员  勘测信息变更审核 查询的是设计审核/勘测信息变更审核人；
		String stationName = CrmUtils.getStationName(entry);
		ItemManage itemManage=itemManageDao.addItemChange(FormUtils.ENTRY_CHANGE_KCBG,record.getEntryId(),record.getId(),"勘测信息变更("+stationName+"-"+entry.getPowerStationCode()+")-"+ DateUtils.formatDate(now,"yyyy-MM-dd HH:mm:ss"),now,user.getUserName());
		//获取最近一次 档案审核/客户信息变更审核人
		String userId=itemManageDao.getLastAuditUserId("91,95",record.getEntryId());
		if(StringUtil.isNotBlank(userId)){
//			itemManage.setAssignAuditUserId(userId);
			itemManage.setPreferUserId(userId);
		}
		itemManageDao.save(itemManage);
		//大代理商优先审核
		String groupName = "设计审核";
		crmPriorReviewSettingService.traderPriorityReview(entry.getCreateTraderId(),itemManage.getId(),groupName);
		return Result.ok();
	}

	@Transactional(rollbackFor = Exception.class)
	public Result pass(SurveyAuditVo auditVo) {
		CustomerEntrySurveyChangeRecord surveyChangeRecord = changeRecordDao.get(auditVo.getId());
		if (!"0".equals(surveyChangeRecord.getStatus())) {
			return Result.fail("状态已改变,刷新后重试");
		}
		User user = UserUtils.getUser();
		surveyChangeRecord.setStatus("1");
		surveyChangeRecord.setAuditor(CrmUtils.getUserXM(user));
		surveyChangeRecord.setAuditBy(user.getId());
		surveyChangeRecord.setAuditTime(new Date());
		surveyChangeRecord.setAuditRemark(auditVo.getAuditRemark());
		changeRecordDao.save(surveyChangeRecord);

		//变更记录
		CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(surveyChangeRecord.getEntryId());
		surveyRecord.setFlyImgs(surveyChangeRecord.getFlyImgs());
		surveyRecord.setRoofPhotoOne(surveyChangeRecord.getRoofPhotoOne());
		surveyRecord.setRoofPhotoTwo(surveyChangeRecord.getRoofPhotoTwo());
		surveyRecord.setRoofPhotoThree(surveyChangeRecord.getRoofPhotoThree());
		surveyRecord.setRoofPhotoFour(surveyChangeRecord.getRoofPhotoFour());
		surveyRecord.setRoofPhotoFacade(surveyChangeRecord.getRoofPhotoFacade());
		surveyRecord.setRoofPhotoInterior(surveyChangeRecord.getRoofPhotoInterior());
		surveyRecord.setRoofPhotoFive(surveyChangeRecord.getRoofPhotoFive());
		surveyRecord.setHouseSupplementOne(surveyChangeRecord.getHouseSupplementOne());
		surveyRecord.setDetailSupplementOne(surveyChangeRecord.getDetailSupplementOne());
		surveyRecord.setSurveyVideo(surveyChangeRecord.getSurveyVideo());
		surveyRecord.setSurveyFiles(surveyChangeRecord.getSurveyFiles());
		surveyRecord.setHouseOutlinePhoto(surveyChangeRecord.getHouseOutlinePhoto());
		surveyRecord.setVrRoofOne(surveyChangeRecord.getVrRoofOne());
		surveyRecord.setVrRoofTwo(surveyChangeRecord.getVrRoofTwo());
		surveyRecord.setVrRoofThree(surveyChangeRecord.getVrRoofThree());
		surveyRecord.setVrRoofFour(surveyChangeRecord.getVrRoofFour());
		surveyRecord.setFwImg1(surveyChangeRecord.getFwImg1());
		surveyRecord.setFwImg2(surveyChangeRecord.getFwImg2());
		surveyRecord.setFwImg3(surveyChangeRecord.getFwImg3());
		surveyRecord.setFwImg4(surveyChangeRecord.getFwImg4());
		surveyRecord.setFwImg5(surveyChangeRecord.getFwImg5());
		surveyRecordDao.save(surveyRecord);

		CustomerEntry entry = entryDao.get(surveyChangeRecord.getEntryId());

		//过程记录
		String msg = (StringUtil.isNotBlank(auditVo.getAuditRemark()) ? ","+ auditVo.getAuditRemark() : "");
		entryMsgService.saveCustomerEntryMsg(Operator.of(user), surveyChangeRecord.getEntryId()
				, CustomerEntryConstants.ENTRY_CHANGE_PASS, String.format("第%d次勘测信息变更申请，审核通过"+msg, surveyChangeRecord.getNum()), null);

		//判断状态是否需要重新推送农户投放审查附件
		if(FormSetUtils.processSetEnable(entry.getPartnerId(), ProcessSetConstants.NODE_KEY_NAME_ZFSH)) {
			CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entry.getId());
			switch (entry.getPartnerId()){
				case "01":
					if (StringUtil.equalsAny(entry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_DBW, CustomerEntryConstants.ENTRY_STATUS_DYS, CustomerEntryConstants.ENTRY_STATUS_YSBH)) {

						Result result = customerEntryService.updateSecoundFile(entry, application.getPartnersContractNumber());
						if (!"200".equals(result.getCode())) {
							logger.error("勘测信息变更推送农户投放审查附件失败：", result.getErrMsg());
							throw new IllegalArgumentException(result.getErrMsg());
						}
					}
					break;
				case "03":
					if (Double.parseDouble(entry.getApplyStatus())>5&&!StringUtil.equalsAny(entry.getApplyStatus(),
							CustomerEntryConstants.APPLY_STATUS_WGSH,CustomerEntryConstants.APPLY_STATUS_WGSHTG,CustomerEntryConstants.APPLY_STATUS_WGSHBH
							,CustomerEntryConstants.APPLY_STATUS_BWSHZ,CustomerEntryConstants.APPLY_STATUS_BWSHTG,CustomerEntryConstants.APPLY_STATUS_BWSHBH)) {
						try {
							if (!CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH.equals(entry.getApplyStatus())){
								guangFaManagemnetService.prospectInfoUpdate(entry,surveyChangeRecord,application.getInputPieceId());
							}
						}catch (Exception e) {
							throw new IllegalArgumentException("提交勘测变更失败," + e.getMessage());
						}
					}
			}

		}

		ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(surveyChangeRecord.getId(),FormUtils.ENTRY_CHANGE_KCBG);
		if (itemManage != null) {
			Operator operator=Operator.of(user);
			itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_KCBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_OK, surveyChangeRecord.getAuditTime(), operator, "勘测信息变更");
			itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
			itemManage.setEndTime(surveyChangeRecord.getAuditTime());
			itemManageDao.save(itemManage);
			reviewDispatchDao.markDispatchFinish(itemManage);
		}
		return Result.ok();
	}

	/**
	 * 审核通过
	 *
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result temp(SurveyAuditVo auditVo) {
		CustomerEntrySurveyChangeRecord surveyChangeRecord = changeRecordDao.get(auditVo.getId());
		if (!"0".equals(surveyChangeRecord.getStatus())) {
			return Result.fail("状态已改变,刷新后重试");
		}
		surveyChangeRecord.setAuditRemark(auditVo.getAuditRemark());
		changeRecordDao.save(surveyChangeRecord);
		return Result.ok();
	}

	@Transactional(rollbackFor = Exception.class)
	public Result passHR(SurveyAuditVo auditVo) {
		CustomerEntrySurveyChangeRecord surveyChangeRecord = changeRecordDao.get(auditVo.getId());
		if (!"0".equals(surveyChangeRecord.getStatus())) {
			return Result.fail("状态已改变,刷新后重试");
		}
		User user = UserUtils.getUser();
		surveyChangeRecord.setStatus("1");
		surveyChangeRecord.setAuditor(CrmUtils.getUserXM(user));
		surveyChangeRecord.setAuditBy(user.getId());
		surveyChangeRecord.setAuditTime(new Date());
		surveyChangeRecord.setAuditRemark(auditVo.getAuditRemark());
		changeRecordDao.save(surveyChangeRecord);
		CustomerEntry entry = entryDao.get(surveyChangeRecord.getEntryId());
		//变更记录
		List<CustomerEntrySurveyChangeRecordDetail> recordDetailList = surveyChangeRecordDetailDao.findByChangeRecord(auditVo.getId());
		List<CrmCustomerEntrySurveyRecordDetail> oldEntrySurveys = crmCustomerEntrySurveyRecordDetailDao.findByEntryId(entry.getId());

		for (CustomerEntrySurveyChangeRecordDetail recordDetail : recordDetailList) {
			String projectId = recordDetail.getProjectId();
			CrmCustomerEntrySurveyRecordDetail surveyRecordDetail = oldEntrySurveys.stream().filter(oldEntrySurvey -> projectId.equals(oldEntrySurvey.getProjectId())).findFirst().get();
			surveyRecordDetail.setFlyImgs(recordDetail.getFlyImgs());
			surveyRecordDetail.setRoofPhotoOne(recordDetail.getRoofPhotoOne());
			surveyRecordDetail.setRoofPhotoTwo(recordDetail.getRoofPhotoTwo());
			surveyRecordDetail.setRoofPhotoThree(recordDetail.getRoofPhotoThree());
			surveyRecordDetail.setRoofPhotoFour(recordDetail.getRoofPhotoFour());
			surveyRecordDetail.setRoofPhotoFacade(recordDetail.getRoofPhotoFacade());
			surveyRecordDetail.setRoofPhotoInterior(recordDetail.getRoofPhotoInterior());
			surveyRecordDetail.setRoofPhotoFive(recordDetail.getRoofPhotoFive());
			surveyRecordDetail.setHouseSupplementOne(recordDetail.getHouseSupplementOne());
			surveyRecordDetail.setDetailSupplementOne(recordDetail.getDetailSupplementOne());
			surveyRecordDetail.setSurveyVideo(recordDetail.getSurveyVideo());
			surveyRecordDetail.setSurveyFiles(recordDetail.getSurveyFiles());
			surveyRecordDetail.setHouseOutlinePhoto(recordDetail.getHouseOutlinePhoto());
			surveyRecordDetail.setVrRoofOne(recordDetail.getVrRoofOne());
			surveyRecordDetail.setVrRoofTwo(recordDetail.getVrRoofTwo());
			surveyRecordDetail.setVrRoofThree(recordDetail.getVrRoofThree());
			surveyRecordDetail.setVrRoofFour(recordDetail.getVrRoofFour());
			surveyRecordDetail.setFwImg1(recordDetail.getFwImg1());
			surveyRecordDetail.setFwImg2(recordDetail.getFwImg2());
			surveyRecordDetail.setFwImg3(recordDetail.getFwImg3());
			surveyRecordDetail.setFwImg4(recordDetail.getFwImg4());
			surveyRecordDetail.setFwImg5(recordDetail.getFwImg5());
			crmCustomerEntrySurveyRecordDetailDao.save(surveyRecordDetail);
		}
		//过程记录
		String msg = (StringUtil.isNotBlank(auditVo.getAuditRemark()) ? ","+ auditVo.getAuditRemark() : "");
		entryMsgService.saveCustomerEntryMsg(Operator.of(user), surveyChangeRecord.getEntryId()
				, CustomerEntryConstants.ENTRY_CHANGE_PASS, String.format("第%d次勘测信息变更申请，审核通过"+msg, surveyChangeRecord.getNum()), null);

		ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(surveyChangeRecord.getId(),FormUtils.ENTRY_CHANGE_KCBG);
		if (itemManage != null) {
			Operator operator=Operator.of(user);
			itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_KCBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_OK, surveyChangeRecord.getAuditTime(), operator, "勘测信息变更");
			itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
			itemManage.setEndTime(surveyChangeRecord.getAuditTime());
			itemManageDao.save(itemManage);
			reviewDispatchDao.markDispatchFinish(itemManage);
		}
		return Result.ok();
	}

	/**
	 * 审核拒绝
	 *
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result refuse(SurveyAuditVo auditVo) {
		CustomerEntrySurveyChangeRecord surveyChangeRecord = changeRecordDao.get(auditVo.getId());
		if (!"0".equals(surveyChangeRecord.getStatus())) {
			return Result.fail("状态已改变,刷新后重试");
		}
		User user = UserUtils.getUser();
		surveyChangeRecord.setStatus("2");
		surveyChangeRecord.setAuditor(CrmUtils.getUserXM(user));
		surveyChangeRecord.setAuditBy(user.getId());
		surveyChangeRecord.setAuditTime(new Date());
		surveyChangeRecord.setAuditRemark(auditVo.getAuditRemark());
		changeRecordDao.save(surveyChangeRecord);
		String msg = (StringUtil.isNotBlank(auditVo.getAuditRemark()) ? ","+ auditVo.getAuditRemark() : "");
		String content = String.format("第%d次勘测信息变更申请，审核驳回" + msg, surveyChangeRecord.getNum());
		entryMsgService.saveCustomerEntryMsg(Operator.of(user), surveyChangeRecord.getEntryId()
				, CustomerEntryConstants.ENTRY_CHANGE_REFUSE, content, null);

		ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(surveyChangeRecord.getId(),FormUtils.ENTRY_CHANGE_KCBG);
		if (itemManage != null) {
			Operator operator=Operator.of(user);
			itemTaskDetailDao.addItemTaskDetail2(FormUtils.ENTRY_CHANGE_KCBG,itemManage.getApplicationId(), itemManage.getProcessInstanceId(), itemManage.getProcessInstanceId(), ItemConstants.RESULT_BACK, surveyChangeRecord.getAuditTime(), operator, "勘测信息变更");
			itemManage.setStatus(ItemConstants.ITEM_STATUS_FINISH);
			itemManage.setEndTime(surveyChangeRecord.getAuditTime());
			itemManageDao.save(itemManage);
			reviewDispatchDao.markDispatchFinish(itemManage);
		}
		return Result.ok();
	}


	@Transactional(rollbackFor = Exception.class)
	public Result back(String id) {
		CustomerEntrySurveyChangeRecord surveyChangeRecord = changeRecordDao.get(id);
		if (!"0".equals(surveyChangeRecord.getStatus())) {
			return Result.fail("状态已改变,刷新后重试");
		}
		User user = UserUtils.getUser();
		surveyChangeRecord.setStatus("3");
		surveyChangeRecord.setAuditor(CrmUtils.getUserXM(user));
		surveyChangeRecord.setAuditBy(user.getId());
		changeRecordDao.save(surveyChangeRecord);

		entryMsgService.saveCustomerEntryMsg(Operator.of(user), surveyChangeRecord.getEntryId()
				, CustomerEntryConstants.ENTRY_CHANGE_CANCEL, String.format("第%d次勘测信息变更申请，撤回", surveyChangeRecord.getNum()), null);

		ItemManage itemManage= itemManageDao.getItemManagementByProcessInstanceId(surveyChangeRecord.getId(),FormUtils.ENTRY_CHANGE_KCBG);
		if(itemManage !=null){
			itemManage.setStatus(ItemConstants.ITEM_STATUS_CANCEL);
			itemManage.setEndTime(new Date());
			itemManageDao.save(itemManage);
		}
		return Result.ok();
	}



}
