package com.sifang.modules.changes.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.changes.entity.CustomerEntrySurveyChangeRecord;
import com.sifang.modules.changes.entity.CustomerEntrySurveyChangeRecordDetail;
import com.sifang.modules.changes.service.CustomerEntrySurveyChangeRecordService;
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.CrmCustomerEntrySurveyRecordDetailService;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.Service.CustomerEntrySurveyRecordService;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.constant.UserConstants;
import com.sifang.modules.customer.entity.CrmCustomerEntrySurveyRecordDetail;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.entity.CustomerEntryOrgFiles;
import com.sifang.modules.customer.entity.CustomerEntrySurveyRecord;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmProjectSetting;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTrader;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmTraderEmploye;
import com.sifang.modules.sunshine.SystemSetting.service.FormSetService;
import com.sifang.modules.sunshine.SystemSetting.service.ProjectInfoSettingService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderEmployeService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.dao.PartnerDao;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
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.sys.web.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author DQChen
 * @date 2024-03-27 10:08
 */
@Controller
@RequestMapping("${adminPath}/customer/entry/change/survey")
public class CustomerEntrySurveyChangeRecordController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CustomerEntrySurveyChangeRecordController.class);
	@Autowired
	CustomerEntrySurveyChangeRecordService changeRecordService;

	@Autowired
	CustomerEntryService entryService;

	@Autowired
	CustomerEntrySurveyRecordService surveyRecordService;

	@Autowired
	ProjectInfoSettingService projectService;

	@Autowired
	private PartnerService partnerService;
	@Autowired
	private CrmCustomerEntrySurveyRecordDetailService recordDetailService;
	@Autowired
	TraderEmployeService traderEmployeService;
	@Autowired
	private FormSetService formSetService;
	@Autowired
	private PartnerDao partnerDao;
	@Autowired
	TraderService traderService;

	@RequestMapping("list")
	public String list(Model model){
		User user = UserUtils.getUser();
		model.addAttribute("user", user);
		return "modules/yangguang/changes/surveyChange/auditList";
	}


	/**
	 * 待审核列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "listData")
	public Object listData(HttpServletRequest request) {
		LayuiPage<Record> page = new LayuiPage<>(request);
		Map<String, String> params = getParams(request);
		User user = UserUtils.getUser();
		if(User.USER_TYPE_HZS.equals(user.getUserType())){
			String parId = CrmUtils.getPartnerId(user.getId());
			CrmPartner partner = partnerService.getById(parId);
			params.put("authorizedId", partner.getAuthorizedId());
		}else if(User.USER_TYPE_PARTNER.equals(user.getUserType())){
			CrmPartner partner = partnerService.findByUserId(user.getId());
			params.put("authorizedId", partner.getAuthorizedId());
		} else if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
			CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
			params.put("engineerId", employe.getId());
		}
		Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
		changeRecordService.listData(page, params, "0", operator);
		return page.renderJson();
	}

	@RequestMapping("changeList")
	public String record(Model model){
		User user = UserUtils.getUser();
		model.addAttribute("user", user);
		String partnerIds="";
		if(User.USER_TYPE_KJ.equals(user.getUserType()) || User.USER_TYPE_ADVISOR.equals(user.getUserType())){
			//获取关联资方
			partnerIds=traderService.getPartnerIdByTraderId(user.getTraderId());
		}
		model.addAttribute("partnerList",partnerDao.partnerList(partnerIds));
		return "modules/yangguang/changes/surveyChange/changeList";
	}


	/**
	 * 变更记录列表数据
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "recordData")
	public Object recordData(HttpServletRequest request) {
		LayuiPage<Record> page = new LayuiPage<>(request);
		Map<String, String> params = getParams(request);
		User user = UserUtils.getUser();
		if(User.USER_TYPE_HZS.equals(user.getUserType())){
			String parId = CrmUtils.getPartnerId(user.getId());
			CrmPartner partner = partnerService.getById(parId);
			params.put("authorizedId", partner.getAuthorizedId());
		}else if(User.USER_TYPE_PARTNER.equals(user.getUserType())){
			CrmPartner partner = partnerService.findByUserId(user.getId());
			params.put("authorizedId", partner.getAuthorizedId());
		} else if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
			CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
			params.put("engineerId", employe.getId());
		}
		Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
		changeRecordService.listData(page, params, "1", operator);
		return page.renderJson();
	}

	@RequestMapping("/toAddSurveyPage")
	public String toAddSurveyPage(HttpServletRequest request,Model model) {
		String partnerId = request.getParameter("partnerId");
		model.addAttribute("partnerId", partnerId);
		if (PartnerConstants.PARTNER_ID_HR.equals(partnerId)){
			return "modules/yangguang/changes/surveyChange/addSurveyHR";
		}else {
			return "modules/yangguang/changes/surveyChange/addSurvey";
		}
	}
	//选择资方页面
	@RequestMapping("/choosePartner")
	public String choosePartner(Model model) {
		// 获取代理商
		User user = UserUtils.getUser();
		CrmTrader trader;
		if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
			String traderId = CrmUtils.getUserRelId(user);
			trader = traderService.getById(traderId);
		} else {
			trader = traderService.getTraderBuserId(user.getId());
		}
		String traderId = trader.getId();
		if ("2".equals(trader.getType())) {
			traderId = trader.getParentId();
		}
		// 获取代理商对应资方
		model.addAttribute("capital", entryService.getCapital(traderId));
		model.addAttribute("type","2");//区分哪个变更
		return "modules/yangguang/changes/common/choosePartner";
	}


	/**
	 * 根据电站编号获取电站信息
	 * @param stationCode
	 * @return
	 */
	@ResponseBody
	@RequestMapping("selectNumber/{stationCode}")
	public Result selectNumber(@PathVariable("stationCode") String stationCode) {
		Result ret = Result.ok();
		Map<String, Object> resMap = Maps.newHashMap();
		CustomerEntry customerEntry = entryService.findCustomerEntryById(stationCode);
		if (customerEntry == null) {
			ret = Result.fail("未找到电站信息");
			return ret;
		}

		//判断电站与角色是否相符
		User user = UserUtils.getUser();
		Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
		if(StringUtil.equalsAny(operator.getUserType(), UserConstants.TYPE_TRADER, User.USER_TYPE_ADVISOR)){
			Record record= CrmUtils.getUserTrader(operator.getUserType(),operator.getUserId());
			String traderId =record.getStr("id");
			if(UserConstants.TYPE_TRADER.equals(operator.getUserType())){  //代理商
				if ("1".equals(record.getStr("type"))){  // 1.一级代理商 2.二级代理商
					if (!customerEntry.getDistributorId().equals(traderId)) {
						ret = Result.fail("未找到电站信息");
						return ret;
					}
				}else{  //二级代理商
					if (UserConstants.TYPE_TRADER.equals(operator.getUserType())) {
						//代理商只能查看自己的
						if (!traderId.equals(customerEntry.getCreateTraderId())) {
							ret = Result.fail("未找到电站信息");
							return ret;
						}
					}
				}
			}else { //代理商人员
				if (!traderId.equals(customerEntry.getCreateTraderId())) {
					ret = Result.fail("未找到电站信息");
					return ret;
				}
			}
		}
		//校验数据
		/*boolean checkResult = false;
		if (CustomerEntryConstants.ENTRY_STATUS_DSH.equals(customerEntry.getStatus()) && StringUtil.equalsAny(customerEntry.getDesignAuditFlag()
				, CustomerEntryConstants.DESIGN_AUDIT_FLAG_DZS, CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSBH, CustomerEntryConstants.DESIGN_AUDIT_FLAG_ZSTG
				, CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHBH, CustomerEntryConstants.DESIGN_AUDIT_FLAG_SJSHTG, CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHBH
				, CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHZ, CustomerEntryConstants.DESIGN_AUDIT_FLAG_JJSHTG)) {
			checkResult = true;
		} else if (StringUtil.equalsAny(customerEntry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_SHBTG, CustomerEntryConstants.ENTRY_STATUS_DXD
				, CustomerEntryConstants.ENTRY_STATUS_DAZ, CustomerEntryConstants.ENTRY_STATUS_DAZYS, CustomerEntryConstants.ENTRY_STATUS_AZYSTH
				, CustomerEntryConstants.ENTRY_STATUS_DBW, CustomerEntryConstants.ENTRY_STATUS_DYS, CustomerEntryConstants.ENTRY_STATUS_YSBH
				, CustomerEntryConstants.ENTRY_STATUS_AZYSTH)) {
			checkResult = true;
		} else if (StringUtil.equalsAny(customerEntry.getStatus(), CustomerEntryConstants.ENTRY_STATUS_KCZS, CustomerEntryConstants.ENTRY_STATUS_AZZS)) {
			checkResult = true;
		}

		if (!checkResult) {
			ret = Result.fail("操作失败，只有待踏勘之后并网验收之前的电站才可提交变更申请");
			return ret;
		}*/
		CustomerEntrySurveyRecord surveyRecord = surveyRecordService.findByEntryId(customerEntry.getId());
		resMap.put("customerEntry", customerEntry);
		if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
			List<Record> projectList = projectService.getEntryProjectByEntryId(customerEntry.getId());
			resMap.put("projectList",projectList);
			//华融多产品-勘测返回
			List<Record>  surveyDetail =  recordDetailService.getEntryDetail(customerEntry.getId());
			resMap.put("projectDetailList",surveyDetail);
		}else {
			resMap.put("surveyRecord", surveyRecord);
			resMap.put("project", projectService.getById(customerEntry.getProjectId()));
		}

		resMap.put("formSet", FormSetUtils.getFormPartSetByStep(null, "2", "07", customerEntry.getPartnerId(), false));
		ret.setData(resMap);
		return ret;
	}

	/**
	 * 去选择电站页面
	 */
	@RequestMapping("/toSelectEntry")
	public String toSelectEntry(HttpServletRequest request ,Model model) {
		User user = UserUtils.getUser();
		//地址信息
		List<Record> pros = AddressUtils.findProvinceListByTraderId(CrmUtils.getCurrentTraderId(user.getId()), null);
		model.addAttribute("province", pros);
		model.addAttribute("partnerId", request.getParameter("partnerId"));
		return "modules/yangguang/changes/surveyChange/selectEntry";
	}


	/**
	 * 添加变更记录/暂存变更记录/修改变更记录
	 * @param recordVo
	 * @return
	 */
	@ResponseBody
	@RequestMapping("addChangeRecord")
	public Result addChangeRecord(AddSurveyChangeRecordVo recordVo) {
		return changeRecordService.addChangeRecord(recordVo);
	}

	//添加变更记录，多产品
	@ResponseBody
	@RequestMapping("addAnyProductSurveyChangeRecord")
	public Result addAnyProductSurveyChangeRecord(@RequestBody AnyProductSurveryChangeVo anyProductChangeVo) {
		 return changeRecordService.addAnyProductChangeRecord(anyProductChangeVo);
	}

	/**
	 * 审核页面
	 *
	 * @return
	 */
	@RequestMapping("surveyAudit/{id}")
	public String toAuditPage(@PathVariable("id") String id, Model model) {
		CustomerEntrySurveyChangeRecord record = changeRecordService.selectById(id);
		CustomerEntrySurveyChangeRecord oldRecord = changeRecordService.selectPre(record.getEntryId(), record.getNum());
		CustomerEntry customerEntry = entryService.getById(record.getEntryId());
		CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());
		model.addAttribute("customerEntry", customerEntry);
		model.addAttribute("project", projectSetting);
		model.addAttribute("change", record);
		model.addAttribute("oldChange", oldRecord);
		model.addAttribute("formSet", JSONObject.toJSONString(FormSetUtils.getFormPartSetByStep(null, "2", "07", customerEntry.getPartnerId(), false)));
		model.addAttribute("info2",formSetService.getListByCondition("07", customerEntry.getPartnerId()) );
		if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
			model.addAttribute("info2",formSetService.getListByCondition("07", customerEntry.getPartnerId()) );
			List<Record> projectList = projectService.getEntryProjectByEntryId(customerEntry.getId());
			model.addAttribute("projectDetailList",projectList);
			//华融多产品--获取更新的记录
			List<CustomerEntrySurveyChangeRecordDetail> newList=changeRecordService.getBySurveyChangeId(record.getId());
			model.addAttribute("newList",newList);

			List<CustomerEntrySurveyChangeRecordDetail> oldList=changeRecordService.getBySurveyChangeId(oldRecord.getId());
			model.addAttribute("oldList",oldList);
			Map<String, CustomerEntrySurveyChangeRecordDetail> oldEntrySurveysMap = oldList.stream().collect(Collectors.toMap(e -> e.getProjectId(), e -> e, (a, b) -> a));
			model.addAttribute("oldListMap",oldEntrySurveysMap);
			model.addAttribute("from","audit");
			model.addAttribute("auditRemark",record.getAuditRemark());
			return "modules/yangguang/changes/surveyChange/surveryAuditHR";
		}
		return "modules/yangguang/changes/surveyChange/surveyAudit";
	}

	/**
	 * 暂存
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("temp")
	public Result temp(SurveyAuditVo auditVo) {
		Result ret = null;
		try {
			ret = changeRecordService.temp(auditVo);
		} catch (IllegalArgumentException e) {
			ret = Result.fail(e.getMessage());
			e.printStackTrace();
			logger.info("SurveyChangeController.pass error:{}", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			ret = Result.fail("操作失败");
		}
		return ret;
	}

	/**
	 * 审核通过
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("pass")
	public Result pass(SurveyAuditVo auditVo) {
		Result ret = null;
		try {
			ret = changeRecordService.pass(auditVo);
		} catch (IllegalArgumentException e) {
			ret = Result.fail(e.getMessage());
			e.printStackTrace();
			logger.info("SurveyChangeController.pass error:{}", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			ret = Result.fail("操作失败");
		}
		return ret;
	}
	@ResponseBody
	@RequestMapping("passHR")
	public Result passHR(SurveyAuditVo auditVo) {
		Result ret = null;
		try {
			ret = changeRecordService.passHR(auditVo);
		} catch (IllegalArgumentException e) {
			ret = Result.fail(e.getMessage());
			e.printStackTrace();
			logger.info("SurveyChangeController.passHR error:{}", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			ret = Result.fail("操作失败");
		}
		return ret;
	}


	/**
	 * 审核不通过
	 * @return
	 */
	@ResponseBody
	@RequestMapping("refuse")
	public Result refuse(SurveyAuditVo auditVo) {
		return changeRecordService.refuse(auditVo);
	}

	/**
	 * 撤回
	 * @return
	 */
	@ResponseBody
	@RequestMapping("cancel/{id}")
	public Result cancel(@PathVariable("id") String id) {
		return changeRecordService.back(id);
	}

	/**
	 * 变更详情
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toSurveyDetail/{id}")
	public String toSurveyDetail(@PathVariable("id") String id, Model model) {
		CustomerEntrySurveyChangeRecord record = changeRecordService.selectById(id);
		CustomerEntrySurveyChangeRecord oldRecord = changeRecordService.selectPre(record.getEntryId(), record.getNum());
		CustomerEntry customerEntry = entryService.getById(record.getEntryId());
		CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());
		model.addAttribute("customerEntry", customerEntry);
		model.addAttribute("project", projectSetting);
		model.addAttribute("change", record);
		model.addAttribute("oldChange", oldRecord);
		model.addAttribute("formSet", JSONObject.toJSONString(FormSetUtils.getFormPartSetByStep(null, "2", "07", customerEntry.getPartnerId(), false)));

		if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
			model.addAttribute("info2",formSetService.getListByCondition("07", customerEntry.getPartnerId()) );
			List<Record> projectList = projectService.getEntryProjectByEntryId(customerEntry.getId());
			model.addAttribute("projectDetailList",projectList);
			//华融多产品--获取更新的记录
			List<CustomerEntrySurveyChangeRecordDetail> newList=changeRecordService.getBySurveyChangeId(record.getId());
			model.addAttribute("newList",newList);

			List<CustomerEntrySurveyChangeRecordDetail> oldList=changeRecordService.getBySurveyChangeId(oldRecord.getId());
			model.addAttribute("oldList",oldList);
			Map<String, CustomerEntrySurveyChangeRecordDetail> oldEntrySurveysMap = oldList.stream().collect(Collectors.toMap(e -> e.getProjectId(), e -> e, (a, b) -> a));
			model.addAttribute("oldListMap",oldEntrySurveysMap);
            model.addAttribute("from","detail");
			return "modules/yangguang/changes/surveyChange/surveryAuditHR";
		}
		return "modules/yangguang/changes/surveyChange/surveyDetail";
	}

}
