package com.sifang.modules.sys.web;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.changes.service.CustomerEntrySupplementService;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.customer.Service.*;
import com.sifang.modules.customer.constant.YueXiuConstants;
import com.sifang.modules.customer.dao.CustomerDao;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.form.PrjDocumentStatusDto;
import com.sifang.modules.customer.form.QueryDocumentRes;
import com.sifang.modules.customer.pdf.PdfReport;
import com.sifang.modules.customer.utils.MergeImageUtil;
import com.sifang.modules.esign.cn.tsign.hz.comm.EsignHttpResponse;
import com.sifang.modules.esign.cn.tsign.hz.exception.EsignDemoException;
import com.sifang.modules.esign.service.ESignAuthService;
import com.sifang.modules.esign.service.ESignSignService;
import com.sifang.modules.esign.service.PartnerContractESignSignService;
import com.sifang.modules.esign.service.RedSunAskAuthContractService;
import com.sifang.modules.flowable.service.ApplicationDetailService;
import com.sifang.modules.monitor.vo.ThreeDaysPowerVo;
import com.sifang.modules.order.dao.SiteOrderDispatchDao;
import com.sifang.modules.order.entity.CrmOrder;
import com.sifang.modules.order.entity.SiteOrderDispatch;
import com.sifang.modules.order.service.CustomerTelephoneIncomeService;
import com.sifang.modules.order.service.OrderFeedbackService;
import com.sifang.modules.order.service.OrderService;
import com.sifang.modules.order.service.TelNotifyOrderService;
import com.sifang.modules.order.utils.OrderUtils;
import com.sifang.modules.order.utils.Target;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.service.RecevierAddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.platform.utils.QRCodeUtil;
import com.sifang.modules.q7link.utils.OpenapiTemplate;
import com.sifang.modules.quality.dao.CrmEntryQualitySeekEntryDao;
import com.sifang.modules.setting.constant.EmpRoleConstants;
import com.sifang.modules.setting.dao.MemberDao;
import com.sifang.modules.sunshine.SystemSetting.entity.SiteReceiptInformation;
import com.sifang.modules.sunshine.SystemSetting.service.SiteReceiptInformationService;
import com.sifang.modules.sunshine.SystemSetting.utils.*;
import com.sifang.modules.supply.order.dao.SupplyOrderAuditDao;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.service.DeliverOrderService;
import com.sifang.modules.supply.stock.dao.CrmSupplyAlarmDao;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.persistence.Page;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.dao.CustomerNoticeDao;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.entity.CustomerNotice;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.service.CrmPlatformAnnouncementService;
import com.sifang.modules.sys.service.SupplementUploadService;
import com.sifang.modules.sys.util.*;
import com.sifang.modules.task.*;
import com.sifang.modules.youkua.service.NhPowerStationService;
import com.sifang.modules.youkua.vo.PowerStationVo;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
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.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

@Controller
@RequestMapping(value = "${adminPath}/main/redirect")
public class RedirectController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(RedirectController.class);
	@Autowired
	private  UserDao userDao;
	@Autowired
	private OrderService orderService;
	@Autowired
	private DeliverOrderService deliverOrderService;
	@Autowired
	private CustomerTelephoneIncomeService customerTelephoneIncomeService;
	@Autowired
	private SiteReceiptInformationService receService;
	@Autowired
	private RecevierAddressService recevierAddressService;
	@Autowired
	private TelNotifyOrderService telNotifyOrderService;
	@Autowired
	private SiteOrderDispatchDao siteOrderDispatchDao;
	@Autowired
	private OrderFeedbackService feedbackService;
    @Autowired
	private MemberDao memberDao;
    @Autowired
	private CustomerDao customerDao;
	@Autowired
	private CustomerNoticeDao customerNoticeDao;
	@Autowired
    private CrmSupplyAlarmDao supplyAlarmDao;


	@Autowired
	private CustomerEntryExtraService entryExtraService;

	@Autowired
	AddressService addressService;

	@Autowired
	private SfCacheService cacheService;

	@Autowired
	private SupplementUploadService supplementUploadService;


	@Autowired
	private CrmPlatformAnnouncementService announcementService;

	@Autowired
	private RedSunAskAuthContractService redSunAskAuthContractService;

	@Autowired
	private YueXiuContractService yueXiuContractService;

	@Autowired
	private OperatingLeaseService operatingLeaseService;

	@Autowired
	CustomerEntryService customerService;

	@Autowired
	private YWTask ywTask;
	@Autowired
	private NHTask nhTask;

	@Autowired
	private YueXiuProjectOperatingService yueXiuProjectOperatingService;

	@Autowired
	private PartnerContractESignSignService partnerContractESignSignService;

	@Value("${yx.setting}")
	private String YX;

	@Value("${yx.contract.jump.url}")
	private String JUMP_URL;

	@Autowired
	private HuaRongGetStatusTask huaRongGetStatusTask;

	@RequestMapping(value = "eSignSuccess")
	public String contractSign(HttpServletRequest request){
		return "modules/base/esignSuccess";
	}

	@RequestMapping(value = {"mainIndex", ""})
	public String mainIndex(HttpServletRequest request) {
		Map<String, String> params = getParams(request);

		return "modules/base/login";
		//return "modules/setting/member/index";
	}

	@RequestMapping(value = "indexHistory")
	public String indexHistory(HttpServletRequest request) {
		Map<String, String> params = getParams(request);

		return "modules/base/index_history";
	}

	@RequestMapping(value = "ajaxTest")
	@ResponseBody
	public String ajaxTest(HttpServletRequest request) {

		return "modules/sifang/pageAuth";
	}

	@RequestMapping(value = {"forgetPwd"})
	public String crmForgetPwd() {
		return "modules/base/forgetpwd";
	}

	@RequestMapping(value = "resertMsg")
	public void resertMsg(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().setAttribute("confirmCode", "");
	}


	@ResponseBody
	@RequestMapping(value = "getProvinceList")
	public Object getProvinceList(HttpServletRequest request) {
		String traderId = request.getParameter("traderId");
		List<Record> list;
		if (StringUtil.isBlank(traderId)) {
			list = addressService.getProvinces();
		} else {
			list = AddressUtils.findProvinceListByTraderId(traderId, null);
		}
		return  list;

	}

	/***
	 * 合作商下的首页
	 */
	@RequestMapping(value = "changeConsole")
	public String changeConsole(HttpServletRequest request, Model model){
		User user = UserUtils.getUser();

		String type = CrmUtils.getPlatEmployeRole(user.getId());
		model.addAttribute("type",type);

		//获取所有省市
		//地址信息
		List<Record> pros = addressService.getProvinces();
		model.addAttribute("pros", pros);
		List<Record> citys = addressService.getCityList();
		model.addAttribute("citys", citys);
		model.addAttribute("timelist",DateUtils.getMonthBetweenDate("2023-01-01",DateUtils.getDateTime()));


		return "modules/base/change/changeHomepage";
	}


	/**
	 * 根据省查询市
	 */
	@ResponseBody
	@RequestMapping(value = "getCitysByProId")
	public Object getCitysByProId(HttpServletRequest request) {
		String provinceId = request.getParameter("province");
		String traderId = request.getParameter("traderId");
		List<Record> list;
		if (StringUtil.isBlank(traderId)) {
			list = AddressUtils.getCitysByProId(provinceId);
		} else {
			list = AddressUtils.findCityListByTraderId(traderId, provinceId, null, null);
		}
		return  list;

	}

	/**
	 * 获取代理商授权城市
	 */
	@ResponseBody
	@RequestMapping(value = "getCityListByTraderId")
	public Object getCityListByTraderId(HttpServletRequest request) {
		String traderId = request.getParameter("traderId");
		String provinceId = request.getParameter("province");
		return AddressUtils.findCityListByTraderId(traderId, provinceId, null, null);
	}

	@ResponseBody
	@RequestMapping(value = "getAreaByCityId")
	public Object getAreaByCityId(HttpServletRequest request) {
		String city = request.getParameter("city");
		String traderId = request.getParameter("traderId");
		List<Record> list;
		if (StringUtil.isBlank(traderId)) {
			list = AddressUtils.getAreaByCityId(city);
		} else {
			list = AddressUtils.findAreaListByTraderId(traderId, null, city, null, null);
		}
		return list;
	}

	@ResponseBody
	@RequestMapping(value = "getAreaListByTraderId")
	public Object getAreaListByTraderId(HttpServletRequest request) {
		String traderId = request.getParameter("traderId");
		String city = request.getParameter("city");
		return AddressUtils.findAreaListByTraderId(traderId, null, city, null, null);
	}

	@ResponseBody
	@RequestMapping(value = "getStreetByAreaId")
	public Object getStreetByAreaId(HttpServletRequest request) {
		String area = request.getParameter("area");
		return AddressUtils.getStreetByAreaId(area);
	}

	/**
	 * cities = AddressUtils.getCityByProName(order.getProvince());
	 * districts = AddressUtils.getAreaByCityName(order.getCity());
	 */

	@ResponseBody
	@RequestMapping(value = "getCitysByProName")
	public Object getCitysByProName(HttpServletRequest request) {
		String province = request.getParameter("province");
		List<Record> list = AddressUtils.getCityByProName(province);
		return  list;

	}


	@ResponseBody
	@RequestMapping(value = "getCityListByProName")
	public Object getCityListByProName(HttpServletRequest request) {
		String province = request.getParameter("province");
		List<Record> list = AddressUtils.getCityListByProName(province);
		return  list;

	}

	@ResponseBody
	@RequestMapping(value = "getAreaByCityName")
	public Object getAreaByCityName(HttpServletRequest request) {
		String city = request.getParameter("city");
		return AddressUtils.getAreaByCityName(city);
	}

	@ResponseBody
	@RequestMapping(value = "getAreaListByCityName")
	public Object getAreaListByCityName(HttpServletRequest request) {
		String city = request.getParameter("city");
		return AddressUtils.getAreaListByProName(city);
	}

	/**
	 * 解析字符串
	 */
	@ResponseBody
	@RequestMapping(value = "analysis")
	public  Object analysisString(HttpServletRequest request){
		String model = request.getParameter("model");
		return StringUtil.splitStr(model,",");
	}

	/**
	 * 服务商获取当前全部工单列表
	 */
	@ResponseBody
	@RequestMapping(value = "getSiteOrderList/{siteId}")
	public Object getSiteOrderList(@PathVariable String siteId, HttpServletRequest request){
		Map<String,String> map = getParams(request);
		String pageNo= map.get("page");
		String pageSize= map.get("rows");
		LayuiPage<Record> page = new LayuiPage<>(request);
		if(StringUtil.isNotBlank(pageNo)){
			page.setPage(Integer.parseInt(pageNo));
		}
		if(StringUtil.isNotBlank(pageSize)){
			page.setLimit(Integer.parseInt(pageSize));
		}

		return orderService.getSiteOrderList(map,siteId,page);
	}

	/**
	 * 服务商获取当前服务中工单列表
	 */
	@ResponseBody
	@RequestMapping(value = "getInServiceOrderBySiteId/{siteId}")
	public Object getInServiceOrderBySiteId(@PathVariable String siteId, HttpServletRequest request){
		Map<String,String> map = getParams(request);
		String pageNo= map.get("page");
		String pageSize= map.get("rows");
		LayuiPage<Record> page = new LayuiPage<>(request);
		if(StringUtil.isNotBlank(pageNo)){
			page.setPage(Integer.parseInt(pageNo));
		}
		if(StringUtil.isNotBlank(pageSize)){
			page.setLimit(Integer.parseInt(pageSize));
		}

		return orderService.getInServiceOrderBySiteId(map,siteId,page);
	}

	/**
	 * 平台下的首页
	*/
	@RequestMapping(value = "systemConsole")
	public String systemConsole(HttpServletRequest request, Model model){
		User user = UserUtils.getUser();

		String type = CrmUtils.getPlatEmployeRole(user.getId());
		model.addAttribute("type",type);
		LayuiPage page = new LayuiPage(request);
		page.setPage(1);
		page.setLimit(4);
		Map<String, String> map = new HashMap<>();
        List<Record> announce=announcementService.indexGetAnnounceList(user.getId());
        model.addAttribute("announce",announce);

		//获取所有省市
		//地址信息
		List<Record> pros = addressService.getProvinces();
		model.addAttribute("pros", pros);
		List<Record> citys = addressService.getCityList();
		model.addAttribute("citys", citys);
		model.addAttribute("timelist",DateUtils.getMonthBetweenDate("2023-01-01",DateUtils.getDateTime()));
/*
		if(EmpRoleConstants.SYSTEM_EMGINEER.equals(type) || EmpRoleConstants.PROJECT_EMGINEER.equals(type)){
			return "modules/base/employeHomepage";
		} else if (EmpRoleConstants.SUPERVISOR.equals(type)) {// 4.监造人员
			String userRelId=CrmUtils.getUserRelId(user);  //
			List<String>  lists = MaterialUtils.findSupplierIdsList(userRelId);
			List<Record> retList = supplyAlarmDao.listAlarmByascrIds(lists);
			model.addAttribute("alarmList", retList);
		    return "modules/base/supplyHomepage";
        }else if(EmpRoleConstants.TREASURER.equals(type) || EmpRoleConstants.BUYER.equals(type)
                || EmpRoleConstants.MATERIAL_CLERK.equals(type)
                || EmpRoleConstants.TRANSPORTATION_MANAGEMENT_DEPT.equals(type)
                || EmpRoleConstants.SALEAMAN.equals(type)
				||EmpRoleConstants.SUPPLY_CHAIN.equals(type)
				||EmpRoleConstants.SUPPLY_SHGCS.equals(type)
				||EmpRoleConstants.SUPPLY_GFXTZG.equals(type)
				||EmpRoleConstants.SUPPLY_XMYSGCS.equals(type)){
			//5.业务人员 6.运管部 7.物资专员 8.采购员 9.财务员 a.供应链 b.审核工程师 c.光伏系统主管

            Ascription ascription = CrmUtils.getAscription();
            map.put("ascriptionId", ascription.getAscriptionId());
            List<Record> retList = supplyAlarmDao.listAlarm(page, map);
            model.addAttribute("alarmList", retList);
			return "modules/base/supplyChainHomePage";
		}*/
		return "modules/base/employeHomepage";
		//return "modules/base/sys/homepage";
	}

	/***
	 * 服务商下的首页
	 */
	@RequestMapping(value = "serviceConsole")
	public String serviceConsole(HttpServletRequest request, Model model){
		return "modules/site/homepage";
	}

	/**
	 * 代理商的首页
	 */
	@RequestMapping(value = "traderConsole")
	public String traderConsole(HttpServletRequest request, Model model){
		User user = UserUtils.getUser();
		model.addAttribute("user",user);
		Map<String, String> map = new HashMap<>();
		LayuiPage page = new LayuiPage(request);
		page.setPage(1);
		page.setLimit(4);
		List<Record> announce=announcementService.indexGetAnnounceList(user.getId());
		model.addAttribute("announce",announce);
		Ascription ascription = CrmUtils.getAscription();
		map.put("ascriptionId", ascription.getAscriptionId());
		model.addAttribute("order",deliverOrderService.findOrderCount(ascription.getAscriptionId()));

		List<Record> pros = addressService.getProvinces();
		model.addAttribute("pros", pros);
		List<Record> citys = addressService.getCityList();
		model.addAttribute("citys", citys);
		model.addAttribute("timelist",DateUtils.getMonthBetweenDate("2023-01-01",DateUtils.getDateTime()));
		return "modules/base/traderHomepage";
	}

	/**
	 * 供应商的首页
	 */
	@RequestMapping(value = "supplyConsole")
	public String supplyConsole(HttpServletRequest request, Model model) {
		User user = UserUtils.getUser();
		model.addAttribute("user",user);
        LayuiPage page = new LayuiPage(request);
        page.setPage(1);
        page.setLimit(5);
		Map<String, String> map = new HashMap<>();
		String ascriptionId = "";
		String type = CrmUtils.getPlatEmployeRole(user.getId());
		if (EmpRoleConstants.SUPERVISOR.equals(type)){
			/*CrmPlatformEmployee emp = platformEmpDao.findByUserId(user.getId());
			CrmSupplySupplier supplier = supplierDao.findBySupervisorId(emp.getId());
			ascriptionId = supplier.getId();*/
		} else {
			ascriptionId = CrmUtils.getAscription(user).getAscriptionId();
		}
		map.put("ascriptionId", ascriptionId);
        List<Record> retList = supplyAlarmDao.listAlarm(page, map);
        model.addAttribute("alarmList", retList);
		return "modules/base/supplyHomepage";
	}


	/**
	 * 服务商修改工单
	*/
	@ResponseBody
	@RequestMapping(value = "siteUpdateOrder")
	public Object siteUpdateOrder(HttpServletRequest request){
		Map<String,String> map = getParams(request);
		return orderService.siteUpdateOrder(map);
	}


	/**
	 * 服务商端根据服务类型获取服务措施
	 */
	@ResponseBody
	@RequestMapping(value = "getOrderServiceMeasures")
	public Object getOrderServiceMeasures(HttpServletRequest request){
		String orderId= request.getParameter("orderId");
		Map<String ,Object> map  = Maps.newHashMap();
		CrmOrder or= orderService.getOrderById(orderId);
		List<Record> list = OrderUtils.getOrderServiceMeasures(or.getServiceType());
		map.put("list",list) ;
		return  map ;
	}


	@ResponseBody
	@RequestMapping(value = "getSiteOrderList")
	public Object getSiteOrderList(HttpServletRequest request){
		String ids = request.getParameter("ids");
		String siteId = request.getParameter("siteId");
		List<Record> list = orderService.getSiteOrderList(ids,siteId);
		Map<String,Object> map = Maps.newHashMap();

		String empName = "";
		if(list.size() > 0){
			for(Record rd : list){
				String employe = rd.getStr("employe_name");
				if(StringUtil.isBlank(empName)){
					empName = employe;
				}else{
					empName = empName+","+employe;
				}
			}
		}
		List<Map<String,Object>> mapx = CrmUtils.returnListMap(list);
		map.put("empName",empName);
		map.put("orderlist",mapx);
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "getSiteReceipt")
	public Object getSiteReceipt(HttpServletRequest request,HttpServletResponse response){
		String siteId = request.getParameter("siteId");
		SiteReceiptInformation rece = receService.getBySiteId(siteId);
		return rece;
	}

	@ResponseBody
	@RequestMapping(value = "saveSiteReceipt")
	public Object saveSiteReceipt(HttpServletRequest request, SiteReceiptInformation siterece) {
		String siteId = request.getParameter("siteId");
		if (StringUtil.isBlank(siteId)) {
			Result.fail("205", "服务商ID为空");
		}
		String code = "200";
		try {
			siterece.setSiteId(siteId);
			receService.saveSiteReceipt(siterece);
		} catch (Exception e) {
			e.printStackTrace();
			code = "205";
			throw e;
		}

		return Result.fail(code, "site");
	}

	@ResponseBody
	@RequestMapping(value = "getDataListAddress")
	public Object getDataListAddress(HttpServletRequest request) {
		Map<String, Object> map = Maps.newHashMap();
		String id = request.getParameter("id");
		if (StringUtil.isBlank(id)) {
			return null;
		}
		Record rd = recevierAddressService.getDataList(id);
		if(rd != null){
			map.put("address",rd);
			map.put("province",rd.getStr("province"));
			map.put("city",rd.getStr("city"));
		};

		return map;
	}


	@ResponseBody
	@RequestMapping(value = "getServiceMeasures")
	public List<Record> getServiceType(HttpServletRequest request) {
		String serviceType = request.getParameter("serviceType");
		return OrderUtils.getOrderServiceMeasures(serviceType);
	}

	@RequestMapping(value = "/minicode", method = RequestMethod.GET, produces = "image/jpg")
	@ResponseBody
	public byte[] miniCode(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		if (StringUtil.isBlank(id)) {
			id = "测试";
		}
		//	id="122121212";
		/** 1.创建临时文件夹  */
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		String name = rootPath + "employe/" + id;
		File temDir = new File(name);
		if (!temDir.exists()) {
			temDir.mkdirs();
		}
		String fileName = id + ".jpg";
		String realPath = name + File.separator + fileName;
		System.out.println(realPath);
		File downloadFile = null;
		try {
			String longUrl = String.format("/main/redirect/employeCard?id=%s", id);
			QRCodeUtil.encode(longUrl, "", realPath, true);
			//文件的目录
			downloadFile = new File(realPath);
			return FileUtils.readFileToByteArray(downloadFile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (!downloadFile.exists()) {
				return null;
			}
			QRCodeUtil.deleteFile(downloadFile);
		}
		return null;
	}

	@RequestMapping(value = "employeCard")
	public String employeCard(HttpServletRequest request, Model model) {
		String userId = request.getParameter("id");
		Record employe = CrmUtils.getEmployeId(userId);
		model.addAttribute("employe", employe);
		if (employe != null) {
			model.addAttribute("imgs", StringUtil.isNotBlank(employe.getStr("license_img")) ? employe.getStr("license_img").split(",") : "");
			model.addAttribute("site", CrmSiteUtils.getSiteById(employe.getStr("site_id")));
		}
		return "modules/site/siteInfo/employeCard";
	}

	/**
	 * 来电弹屏
	 */
///main/redirect/ajaxTelephoneOrder
	@RequestMapping(value = "ajaxTelephoneOrder", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject ajaxTelephoneOrder(HttpServletRequest req) {
		String telephone = req.getParameter("tel");
		String serialNo = req.getParameter("serialNo");
		logger.info("ajax tel order,tel=" + telephone + "serial.no=" + serialNo);

		Map<String, Object> result = Maps.newHashMap();
		result.put("result", 0);
		if (StringUtil.isNotBlank(telephone)) {
			customerTelephoneIncomeService.save(telephone);
			long count = orderService.getTelephoneDeviceOrderCount(telephone);
			logger.info("电话进入,手机号为  mobile :{} , 查询工单数量 count : {}",telephone,count);
			if (count > 0) {
				result.put("result", count);
				result.put("p", String.format("/main/redirect/telephoneNotifyOrder?tel=%s&serialNo=%s", telephone, serialNo));
			} else {
				result.put("result", 0);
				result.put("p", String.format("/main/redirect/newBuildOrderWhenNull?tel=%s&serialNo=%s", telephone, serialNo));
			}
		}
		return JSONObject.fromObject(result);
	}

	@RequestMapping(value = "telephoneNotifyOrder")
	public String telephoneNotifyOrder(HttpServletRequest req, HttpServletResponse response, Model model) {
		String telephone = req.getParameter("tel");

		if (telephone.length() > 11) {
			telephone = telephone.replace("-", "");
		}
		logger.info(String.format("telephoneNotifyOrder::tel=%s", telephone));

		String page = req.getParameter("pageNo");
		if (!org.apache.commons.lang.StringUtils.isNumeric(page)) {
			page = "1";
		}
		int pageNo = StringUtil.isBlank(page) ? 1 : Integer.valueOf(page);
		long prevPageNo = pageNo > 1 ? pageNo - 1 : 1;
		if (StringUtil.isNotBlank(telephone)) {
			OrderDetailsVo orderDetail = telNotifyOrderService.getTelephoneDeviceOrderList(telephone, pageNo);
			LayuiPage  page1 = orderDetail.getPage();
			long count =page1.getCount();
			long nextPageNo = pageNo >= count ? count : pageNo + 1;
			req.setAttribute("page", page1);// 历史工单信息
			req.setAttribute("img", orderDetail.getFeedbackImgs());// 图片信息
			CrmOrder order = orderDetail.getOrder();//
			req.setAttribute("order", order);
			req.setAttribute("unfinished", orderDetail.getUnfinishedOrderCount());
			req.setAttribute("finished", orderDetail.getFinishedOrderCount());
			req.setAttribute("cal", orderDetail.getCallback());
			req.setAttribute("fitti", orderDetail.getFittings());
			req.setAttribute("listdis", orderDetail.getDispatchList());
			req.setAttribute("settlement", orderDetail.getSettlement());
			req.setAttribute("callTimes", orderDetail.getCallTimes());
			req.setAttribute("details", orderDetail);
			req.setAttribute("feedback", orderDetail.getFeedback());
			req.setAttribute("feedbacks", orderDetail.getFeedbacks());
			req.setAttribute("prevPageNo", prevPageNo);
			req.setAttribute("nextPageNo", nextPageNo);
			req.setAttribute("tel", telephone);
			req.setAttribute("count", page1.getCount());

			if (order != null) {
				if (StringUtil.isNotBlank(order.getId()) && StringUtil.isNotBlank(order.getSiteId())) {
					SiteOrderDispatch rds = siteOrderDispatchDao.getByOrderId(order.getId());
					model.addAttribute("disOrder", rds);
					Map<String, Object> feedbackInfo = feedbackService.getOrderFeedbackRecords(order.getId());
					req.setAttribute("feedbackInfo", feedbackInfo);
				}
			}
		}
		return "modules/order/platform/callShow";
	}

	// 新建工单(无工单时)
	@RequestMapping(value = "newBuildOrderWhenNull")
	public String newBuildOrderWhenNull(HttpServletRequest request, Model model) {
		CrmOrder order = new CrmOrder();
		String telephone = request.getParameter("tel");
		String serialNo = request.getParameter("serialNo");
		logger.info("....new build order when null called, telephone is:" + telephone + ";serial.no=" + serialNo);
		order.setCustomerMobile(telephone);

		if ("0".equals(telephone.substring(0, 1))) {
			model.addAttribute("telorMob", "tel");
		} else {
			model.addAttribute("telorMob", "mob");
		}
		Map<String, String> brand = null;
		List<Record> category = null;
		Date curDate = new Date();
		//地址信息
		List<Record> pros = addressService.getProvinces();
		model.addAttribute("pros",pros);
		List<String> promiseLimit = PlantformUtils.getPromiseLimit();
		model.addAttribute("promiseLimit",promiseLimit);
		model.addAttribute("data", DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		// 获取来源
		model.addAttribute("curDate", curDate);
		model.addAttribute("category", category);
		model.addAttribute("brand", brand);
		model.addAttribute("order", order);
		model.addAttribute("seriNo", serialNo);
		model.addAttribute("telephone", telephone);
		model.addAttribute("returnModel", 1);
		model.addAttribute("employes",memberDao.getPlatformEmploye());
		Page<Record> pages = new Page<Record>();
		pages.setPageNo(1);
		pages.setPageSize(100);
		return "modules/" + "sys/callShowDatail/buildNewOrder";
	}


	// 新建工单（有工单时新建工单）
	@RequestMapping(value = "newBuildOrder")
	public String newBuildOrder(HttpServletRequest request, Model model) {
		String orId = request.getParameter("id");
		String telephone = request.getParameter("tel");


		List<Record> provincelist = addressService.getProvinces();
		List<Record> cities = null;
		List<Record> districts = null;

		CrmOrder order = orderService.getOrderById(orId);
		model.addAttribute("order", order);
		//	model.addAttribute("Username", order.getMessengerName());
		// 信息员
		Page<Record> pages = new Page<Record>();
		pages.setPageNo(1);
		pages.setPageSize(100);
		List<Record> infomans = null;
		model.addAttribute("infomans", infomans);
		if (StringUtil.isNotBlank(order.getProvince()) && StringUtil.isNotBlank(order.getCity()) && StringUtil.isNotBlank(order.getArea())) {
			cities = AddressUtils.getCityByProName(order.getProvince());
			districts = AddressUtils.getAreaByCityName(order.getCity());
		}
		Map<String, String> brand =null;
		List<Record> category = null;
		model.addAttribute("category", category);
		model.addAttribute("brand", brand);


		Date curDate = new Date();

		model.addAttribute("curDate", curDate);
		model.addAttribute("telephone", telephone);

		String[] arrImages= StringUtil.isBlank(order.getBdImgs())?  null:order.getBdImgs().split(",");
		model.addAttribute("images",arrImages);
		model.addAttribute("imgNumber", StringUtil.isBlank(order.getBdImgs())? "0":arrImages.length);
		//地址信息
		List<Record> pros = addressService.getProvinces();
		model.addAttribute("pros",pros);
		List<String> promiseLimit = PlantformUtils.getPromiseLimit();
		model.addAttribute("promiseLimit",promiseLimit);
		model.addAttribute("data",DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
		// 获取服务类型
		List<Record> rds = null;
		model.addAttribute("ServiceType", rds);
		// 服务方式
		List<Record> rds2 = null;
		model.addAttribute("getServiceMode", rds2);
		model.addAttribute("provincelist", provincelist);
		model.addAttribute("cities", cities);
		model.addAttribute("districts", districts);
		model.addAttribute("employes",memberDao.getPlatformEmploye());

		if ("0".equals(telephone.substring(0, 1))) {
			model.addAttribute("telorMob", "tel");
		} else {
			model.addAttribute("telorMob", "mob");
		}
		return "modules/" + "sys/callShowDatail/buildNewOrder";
	}

	/**
	 * 保存工单信息
	 *
	 */
	@ResponseBody
	@RequestMapping(value="saveNewOrder")
	public Object saveNewOrder(@RequestBody String str, HttpServletRequest request){
		logger.info("保存新建工单  saveNewOrder");
		Result result = new Result();
		com.alibaba.fastjson.JSONObject object=com.alibaba.fastjson.JSONObject.parseObject(str);
		CrmOrder order=com.alibaba.fastjson.JSONObject.toJavaObject(object,CrmOrder.class);
		Boolean flag=orderService.checkBlack(order);
        String createNameId=order.getCreateBy();
		User user=userDao.getById(createNameId);
		if(!flag){
			result.setCode("202");
			return  result;
		}
		try{
			return orderService.SaveOrder(order,user);
		} catch (CustomException m) {
			m.printStackTrace();
			result.setCode(m.getCode());
			result.setMsg(m.getMessage());
		}catch (Exception e){
			e.printStackTrace();
			result.setCode("505");
			throw e;
		}
		return result;
	}


	/***
	 * 手机端一键报修
	 */
	@ResponseBody
   	@RequestMapping(value="savePhoneAddOrder")
	public Object savePhoneAddOrder(HttpServletRequest request){
		logger.info("手机端一键报修  savePhoneAddOrder");
		Map<String,String> map = getParams(request);
		return orderService.savePhoneAddOrder(map);
	}

	/***
	 * 手机端获取服务记录（已完成/未完成）
	 */
	@ResponseBody
	@RequestMapping(value="getServiceList")
	public Object getServiceList(HttpServletRequest request){
		Map<String,String> map = getParams(request);
		LayuiPage page = new LayuiPage(request);
		Map<String,Object> resultmap=Maps.newHashMap();
		try {
			List<Record> list=orderService.serviceList(page,map);
			List<Object> ret = new ArrayList<>();
			for(Record r: list) {
				ret.add(r.getColumns());
			}
			resultmap.put("code","200");
			resultmap.put("msg","获取成功！");
			resultmap.put("data",ret);
		}catch (Exception e){
			e.printStackTrace();
			resultmap.put("code","202");
			resultmap.put("msg",e.getMessage());
		}
		return resultmap;
	}
	/***
	 * 手机端查询工单详情
	 */
	@ResponseBody
	@RequestMapping(value="getOrderDetail")
	public Map<String,Object> getOrderDetail(HttpServletRequest request){
		Map<String,Object> resultmap=Maps.newHashMap();
		Map<String,Object> map=Maps.newHashMap();
		String orderId=request.getParameter("orderId");
		try{
			CrmOrder order = orderService.getOrderById(orderId);
			List<Target> list=getOrderDetail(orderId,order.getStatus());
			map.put("order",order);
			map.put("guochen",list);
			resultmap.put("code","200");
			resultmap.put("msg","获取成功！");
			resultmap.put("data",map);
		}catch (Exception e){
			e.printStackTrace();
			resultmap.put("code","202");
			resultmap.put("msg",e.getMessage());
		}
		return resultmap;
	}
	private List<Target> getOrderDetail(String orderId,String status){
		String sql = "SELECT process_detail FROM crm_order_operation_info WHERE order_id=? ";
		String detail = Db.queryStr(sql,orderId);
		List<Target> list = WebPageFunUtils.getOrderProcess(detail);
		List<Target> resultList=new ArrayList<>();
		for(int i=0;i<list.size();i++){
			Target target=list.get(i);
			int t=target.getT();
			if(Target.DIRECTLY_CLOSE == t || Target.FEEDBACK_CLOSE == t || Target.COMPLETE_ORDER==t || 21==t){
				continue;
			}else {
				resultList.add(target);
			}
		}
		return resultList;
	}
	/***
	 * 手机端查询未完成工单数量
	 */
	@ResponseBody
	@RequestMapping(value="countWwcOrder")
	public Object getWwcOrderNumber(HttpServletRequest request){
		Map<String,Object> resultmap=Maps.newHashMap();
		Map<String,String> map = getParams(request);
		try{
			Long count=orderService.getWwcOrderNumber(map);
			resultmap.put("code","200");
			resultmap.put("msg","获取成功！");
			resultmap.put("data",count);
		}catch (Exception e){
			e.printStackTrace();
			resultmap.put("code","202");
			resultmap.put("msg",e.getMessage());
		}
		return resultmap;
	}


	/**
	 * 手动更新表数据
	*/
	@ResponseBody
	@RequestMapping(value = "updateTable")
	public Object updateTable(HttpServletRequest request){
		try {
			String sql = request.getParameter("sql");
			if(StringUtil.isBlank(sql)){
				return Result.fail("505","SQL语句为空");
			}
			int count= Db.update(sql);
			if(count<1){
				return Result.fail("505","SQL执行成功数量0条");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.fail("501","Exception : " +e);
		}
		return Result.ok();
	}

	@ResponseBody
	@RequestMapping(value = "getMysqlObject")
	public Object getMysqlObject(HttpServletRequest request){
		String sql = request.getParameter("sql");
		if(StringUtil.isNotEmpty(sql)){
			return Db.find(sql);
		}
		return "500";
	}

	@RequestMapping("/toMergeAccept")
	public String toMergeAccept( Model model,HttpServletRequest request){

		String img = request.getParameter("img");


		return "modules/yangguang/customer/entry/testreport";
	}

	@RequestMapping(value = "forgetPasswork")
	public String forgetPasswork(HttpServletRequest request, Model model){

		return "modules/sys/forgetPasswork";
	}


	@ResponseBody
	@RequestMapping(value = "getAnnouncement")
	public Object getAnnouncement(HttpServletRequest request){
		String id = request.getParameter("id");
		if(StringUtil.isNotEmpty(id)){
			String sql = "SELECT * FROM crm_platform_announcement WHERE  id=?";
			Record rd = Db.findFirst(sql,id);
			Map<String,String> map = Maps.newHashMap();

			if(StringUtil.isNotEmpty(rd.getStr("customer_id"))){
				map.put("customerId",rd.getStr("customer_id"));
			}
			if(StringUtil.isNotEmpty(rd.getStr("province"))){
				map.put("province",rd.getStr("province"));
			}
			if("2".equals(rd.getStr("is_many"))&&StringUtil.isNotEmpty(rd.getStr("city"))){
				//多市
				map.put("city",rd.getStr("city"));
			}
			if(StringUtil.checkParamsValid(rd.getStr("station_building_start"))){
				map.put("stationBuildingStart", DateUtils.formatDate(rd.getDate("station_building_start"),""));
			}
			if(StringUtil.checkParamsValid(rd.getDate("station_building_end"))){
				map.put("stationBuildingEnd",DateUtils.formatDate(rd.getDate("station_building_end"),""));
			}
			if (StringUtil.checkParamsValid(rd.getInt("login_num_min"))&&rd.getInt("login_num_min")>0) {
				map.put("loginNumMin",rd.getInt("login_num_min").toString());
			}
			if (StringUtil.checkParamsValid(rd.getInt("login_num_max"))&&rd.getInt("login_num_max")>0) {
				map.put("loginNumMax",rd.getInt("login_num_max").toString());
			}

			//删除当前所有用户
			Db.update(" DELETE  FROM crm_customer_notice WHERE announcement_id=?",id);
			List<Record> list = customerDao.getCustomerList(null,map);

			List<CustomerNotice> ices = Lists.newArrayList();
			for(Record crd:list){
				String cusid = crd.getStr("cuId");
				CustomerNotice notice = new CustomerNotice();
				notice.setCustomerId(cusid);
				notice.setAnnouncementId(id);
				ices.add(notice);
			}
			customerNoticeDao.save(ices);
			return "200";
		}
		return "500";
	}

	/**
	 * 个人中心--获取信息
	*/
	@ResponseBody
	@RequestMapping("findUserDetail")
	public Object findUserDetail(HttpServletRequest request){
		Map<String,String> map = Maps.newHashMap();
		String userId = request.getParameter("userId");
		if (StrKit.isBlank(userId)) {
			throw new BusinessException("userId不能为空");
		}
		User user = userDao.get(userId);
		if (user == null) {
			user = userDao.getById(userId);
		}
		if (user == null) {
			throw new BusinessException("用户不存在");
		}
		if(!"0".equals(user.getStatus())){
			throw new BusinessException("当前账号已禁用或已删除，不可操作！");
		}
		String userType = user.getUserType();
		if (User.USER_TYPE_WXG.equals(userType)) {
			Record rec = Db.findFirst("select * from crm_platform_employee where user_id=?", user.getId());
			map.put("name",rec.getStr("name"));
			map.put("mobile",rec.getStr("mobile"));
			map.put("hiredate",rec.getDate("hiredate")!=null?DateUtils.formatDate(rec.getDate("hiredate")):"");
			map.put("img",rec.getStr("img"));
			map.put("jobNumber",user.getLoginName());

		}else if(User.USER_TYPE_ADVISOR.equals(userType)){
			StringBuilder sf = new StringBuilder();
			sf.append("SELECT a.id,a.user_id,a.name,a.mobile,a.img,b.name AS traderName,b.province,b.city,b.area,b.address ");
			sf.append(" FROM crm_trader_employe a  ");
			sf.append(" LEFT JOIN crm_trader b ON b.id=a.trader_id ");
			sf.append(" WHERE a.user_id= ? ");
			Record rec = Db.findFirst(sf.toString(), user.getId());

			map.put("name",rec.getStr("traderName"));
			map.put("mobile",rec.getStr("mobile"));
			map.put("contacts",rec.getStr("name"));//联系人
			map.put("img",rec.getStr("img"));
			map.put("address",rec.getStr("province")+rec.getStr("city")+rec.getStr("area")+rec.getStr("address"));

		}else if(User.USER_TYPE_KJ.equals(userType)){
			Record rec = Db.findFirst("select * from crm_trader where user_id=?", user.getId());
			map.put("name",rec.getStr("name"));
			map.put("mobile",rec.getStr("mobile"));
			map.put("contacts",rec.getStr("contacts"));//联系人
			map.put("img",rec.getStr("img"));
			map.put("address",rec.getStr("province")+rec.getStr("city")+rec.getStr("area")+rec.getStr("address"));

		}

		return map;
	}

	/**
	 * 修改头像
	*/
	@ResponseBody
	@RequestMapping("updateImg")
	public Result updateImg(HttpServletRequest request){
		String userId = request.getParameter("userId");

		String img = request.getParameter("img");
		if (StrKit.isBlank(userId)) {
			throw new BusinessException("userId不能为空");
		}
		if (StrKit.isBlank(img)) {
			throw new BusinessException("图片img不能为空");
		}
		User user = userDao.get(userId);
		if (user == null) {
			user = userDao.getById(userId);
		}
		if (user == null) {
			throw new BusinessException("用户不存在");
		}
		if(!"0".equals(user.getStatus())){
			throw new BusinessException("当前账号已禁用或已删除，不可操作！");
		}

		String userType = user.getUserType();
		if (User.USER_TYPE_WXG.equals(userType)) {
			int cous = Db.update("UPDATE crm_platform_employee SET img = ?  WHERE user_id = ?",img,userId);
			if(cous<1){
				throw new BusinessException("修改保存失败");
			}
		}else if(User.USER_TYPE_ADVISOR.equals(userType)){
			int rmpcou =Db.update("UPDATE crm_trader_employe SET img = ?  WHERE user_id = ?",img,userId);
			if(rmpcou<1){
				throw new BusinessException("修改保存失败");
			}
		}else if(User.USER_TYPE_KJ.equals(userType)){
			int tracou =Db.update("UPDATE crm_trader SET img = ?  WHERE user_id = ?",img,userId);
			if(tracou<1){
				throw new BusinessException("修改保存失败");
			}
		}
		return Result.ok();
	}

	/**
	 * APP 修改密码
	*/
	@ResponseBody
	@RequestMapping("updatePasswork")
	public Result updatePasswork(HttpServletRequest request){
		String userId = request.getParameter("userId");

		String password = request.getParameter("password");

		String oldPassword = request.getParameter("oldPassword");//原密码
		if (StrKit.isBlank(userId)) {
			throw new BusinessException("userId不能为空");
		}
		if (StrKit.isBlank(password)) {
			throw new BusinessException("密码不能为空");
		}
		if (StrKit.isBlank(oldPassword)) {
			throw new BusinessException("原密码不能为空");
		}
		User user = userDao.get(userId);
		if (user == null) {
			user = userDao.getById(userId);
		}
		if (user == null) {
			throw new BusinessException("用户不存在");
		}
		if(!"0".equals(user.getStatus())){
			throw new BusinessException("当前账号已禁用或已删除，不可操作！");
		}
		String userPassword = user.getPassword();
		String oldpass = RandomUtil.entryptPassword(oldPassword);//用户输入的原密码进行加密
		if(userPassword.equals(oldpass)){//校验原密码是否匹配
			user.setPassword(RandomUtil.entryptPassword(password));
			userDao.save(user);
			logger.info("校验用户输入的密码和数据库对应记录的密码相同"+" "+",校验用户输入的密码:"+oldpass+",数据库对应记录的密码:"+userPassword);
		}else{
			logger.info("校验用户输入的密码和数据库对应记录的密码不匹配"+" "+",校验用户输入的密码:"+oldpass+",数据库对应记录的密码:"+userPassword);
			return Result.fail("2002","原密码错误");
		}



		return Result.ok();
	}

	@ResponseBody
	@RequestMapping("generatePdf")
	public Object generatePdf(HttpServletRequest request){
		long begin = System.currentTimeMillis();
		String number = request.getParameter("number");
		if(StringUtil.isBlank(number)){
			return Result.fail("参数为空");
		}
		String codes[] = number.split(",");
		List<Record> list = Db.find("SELECT * FROM crm_customer_entry WHERE power_station_code IN("+StringUtil.joinInSql(codes)+") AND STATUS IN('a','8','9','11') AND (check_accept_imgs ='' OR check_accept_imgs IS NULL) ");
		new TaskDemo().generatePdf(list);
		long end = System.currentTimeMillis();
		String mes = "定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒";
		return  Result.fail("200",mes);
	}

	// /main/redirect/deleteCache?name=planList   删除缓存
    @ResponseBody
	@RequestMapping(value = "deleteCache")
	public Result deleteCache(HttpServletRequest request){
		String name=request.getParameter("name");
		Long result=cacheService.del(name);
		logger.info(">>>>>>>>>>>>>>>deleteCache:{}",result);
		return Result.ok();
	}

	// /main/redirect/supplementUpload
	@ResponseBody
	@RequestMapping(value = "supplementUpload")
	public Result supplementUpload(HttpServletRequest request){
		String type=request.getParameter("type");
		String entryId=request.getParameter("entryId");
		if(StringUtil.isBlank(type) || StringUtil.isBlank(entryId)){
			return Result.fail("参数缺失!");
		}
		logger.info(">>>>>>>>>>>>supplementUpload  type:{},entryId:{}",type,entryId);
		supplementUploadService.supplementUpload(Integer.parseInt(type),entryId);
		return Result.ok();
	}

	@ResponseBody
	@RequestMapping(value = "accessProjectApply")
	public void accessProjectApply(){
		String proCode = "22061910124078,22102916096782,22102010358726,22111114470349,22111212034251,22112717005190,22100116381649,22112011149057,22070717379624,22081816125679,22092916218053,22112710547281,22121217385647,22071510375142,22080910406730,22102111300983,22102414509720,22112311421967,22111411080587,22111411104781,22092012085417,22072517021536,22092717298172,22102911236217,22111416115638,22111416413694,22111910067156,22111314082931,22111110219830,22120614594379,22102610213621,22102610247184,22110411357695,22111016388902,22111017232075,22092915530976,22101314547941,22102011130824,22073110322469,22110915546748,22110916308069,22101909136574,22070616114780,22071910185761,22121813049106,22111314116287,22101414554081,22102015449586,22102709115487,22110108569762,22112911556842,22102900019528,22102311538532,22102702105738,22070814151820,22071517513620,22090110027365,22080509090259,22081410481560,22091212176302,22081416063956,22081416094150,22071909348490,22073010548530,22101916222480,22102016256803,22080210193462,22103015012638,22102514208095,22102711290138,22103016081283,22061808549321,22062410318145,22070108255894,22072511158052,22081816089638,22090214521084,22100717397321,22100816327829,22102715454870,22110211229352,22112817128176,22081114169265,22081218043098,22090208411542,22090417292154,22101014412583,22101309063647,22102410402063,22111215268961,22101708418461,22102515029817,22100309438027,22101316376238,22092121182638,22102709092059,22102411082537,22102411114265,22102715094326,22102111263945,22092608587590,22102416025289,22092216282763,22070108210968,22071617482379,22091811430198,22100211355730,22070714136548";
		logger.info("批量处理宽限期错误问题------------");
		String[] codes = proCode.split(",");
		for(String code :codes){
			logger.info("code------------{}",code);
			entryExtraService.SProjectApply(code,"1");

		}
	}

	@ResponseBody
	@RequestMapping(value = "accessProjectApplyTwo")
	public void accessProjectApplyTwo(){
		String proCode = "22061910124078,22102916096782,22102010358726,22111114470349,22111212034251,22112717005190,22100116381649,22112011149057,22070717379624,22081816125679,22092916218053,22112710547281,22121217385647,22071510375142,22080910406730,22102111300983,22102414509720,22112311421967,22111411080587,22111411104781,22092012085417,22072517021536,22092717298172,22102911236217,22111416115638,22111416413694,22111910067156,22111314082931,22111110219830,22120614594379,22102610213621,22102610247184,22110411357695,22111016388902,22111017232075,22092915530976,22101314547941,22102011130824,22073110322469,22110915546748,22110916308069,22101909136574,22070616114780,22071910185761,22121813049106,22111314116287,22101414554081,22102015449586,22102709115487,22110108569762,22112911556842,22102900019528,22102311538532,22102702105738,22070814151820,22071517513620,22090110027365,22080509090259,22081410481560,22091212176302,22081416063956,22081416094150,22071909348490,22073010548530,22101916222480,22102016256803,22080210193462,22103015012638,22102514208095,22102711290138,22103016081283,22061808549321,22062410318145,22070108255894,22072511158052,22081816089638,22090214521084,22100717397321,22100816327829,22102715454870,22110211229352,22112817128176,22081114169265,22081218043098,22090208411542,22090417292154,22101014412583,22101309063647,22102410402063,22111215268961,22101708418461,22102515029817,22100309438027,22101316376238,22092121182638,22102709092059,22102411082537,22102411114265,22102715094326,22102111263945,22092608587590,22102416025289,22092216282763,22070108210968,22071617482379,22091811430198,22100211355730,22070714136548";
		String[] codes = proCode.split(",");
		logger.info("批量处理宽限期错误问题,二次进件------------");
		for(String code :codes){

			entryExtraService.SProjectApply(code,"2");

		}
	}

	@ResponseBody
	@RequestMapping(value = "updateEntryStatua")
	public Result updateEntryStatua(String code,String status){
		Db.update("update crm_customer_entry set status=? where power_station_code=?",status,code);
		return Result.ok();
	}

	@ResponseBody
	@RequestMapping(value = "supplementUploadFile")
	public Result supplementUploadFile(HttpServletRequest request){

		String code=request.getParameter("code");
		if(StringUtil.isBlank(code)){
			return Result.fail("参数缺失!");
		}
		Record rd = Db.findFirst("select id from crm_customer_entry where power_station_code=?",code);
		String	entryId = rd.getStr("id");
		List<Integer> list = Lists.newArrayList();
		list.add(7);
		list.add(8);
		list.add(20);
		for(int type:list){
			supplementUploadService.supplementUpload(type,entryId);
		}

		return Result.ok();
	}
	/**
	 *
	*/
	private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "/tempdf/%s";
	@ResponseBody
	@RequestMapping(value = "idCodeJiama")
	public Object idCodeJiama() throws MalformedURLException {
		URL input = new URL("https://sky-energy.oss-cn-beijing.aliyuncs.com/energy_img/jpg/20230620/181ca6460e72419ab28e5edee9312c08/f7cde07654ab4624b1b68b14541e0003.jpg");

		String extName = "jpg";
		String filenewUrl = String.format(FILE_PATH_TEMPLATE, IdGen.uuid())+"/"+"iweioereiii."+extName;
		File out = new File(filenewUrl);
		URL watermarkImage = new URL("https://sky-energy.oss-cn-beijing.aliyuncs.com/prohibit_delete/masaike.png");
		MergeImageUtil.addWatermark(input,out,watermarkImage);

		String fileInfo = AliyunOSSClientUtil.uploadImage(PdfReport.File2byte(out), extName, "iweioereiii."+extName);
		logger.info("返回路径信息"+fileInfo+fileInfo);
		return  fileInfo;
	}


	/**
	 * 邀请农户签约授权
	 * /main/redirect/createAskAuthContract?idCard=3698745456666666&mobile=18217523224
	 */
	@ResponseBody
	@RequestMapping(value = "createAskAuthContract")
	public Result createAskAuthContract(HttpServletRequest request){
		String idCard=request.getParameter("idCard");
		String mobile=request.getParameter("mobile");
		String address=request.getParameter("address");
		String partnerId=request.getParameter("partnerId");
		redSunAskAuthContractService.createAskAuthContract(idCard,mobile,address,partnerId);
		return Result.ok();
	}

	// 获取签约地址  /main/redirect/toContractPage?entryId=
	@ResponseBody
	@RequestMapping(value = "toContractPage")
	public Object toContractPage(String entryId){
		logger.info("partnersContractNumber -------：{}", entryId);
		QueryDocumentRes res=yueXiuContractService.queryDocumentStatus(entryId);
		String mw=res.getPartnersContractEncr();  //密文
		//获取签约地址
		String contractUrl = String.format(JUMP_URL,mw,"00");
		return Result.success(contractUrl);
	}

	//查询农户单据状态   /main/redirect/queryDocumentStatus?entryId=
	@ResponseBody
	@RequestMapping(value = "queryDocumentStatus")
	public Result queryDocumentStatus(String partnersContractNumber,String idCode){
		logger.info(" queryDocumentStatus  partnersContractNumber -------：{}", partnersContractNumber);
		Map<String, Object> map = new HashMap<>();
		List<Object> bodyData=new ArrayList<>();
		Map<String,Object> map1=new HashMap<>();
		PrjDocumentStatusDto documentStatusDto=new PrjDocumentStatusDto();
		documentStatusDto.setPartnersContractNumber(partnersContractNumber);
		documentStatusDto.setIdCardNo(idCode);
		map1.put("prjDocumentStatusDto",documentStatusDto);
		bodyData.add(map1);
		map.put("body",bodyData);
		Map<String, Object> head = new HashMap<>();
		head.put("serialNumber",UUID.randomUUID().toString());
		head.put("systemId", YueXiuConstants.CLIENT_ID);
		head.put("transactionCode", YueXiuConstants.TRANSACTION_CODE_CONTRACT+YX);
		head.put("transactionTime", DateUtils.formatDate(new Date(),"yyyyMMdd HH:mm:ss"));
		head.put("version",1);
		map.put("head",head);
		logger.info("农户单据状态查询  queryDocumentStatus json:{}",new Gson().toJson(map));
		com.alibaba.fastjson.JSONObject jieMap = operatingLeaseService.clientPostZYMap(map,YueXiuConstants.QUERY_DOCUMENT_STATUS);
		logger.info("农户单据状态查询 queryDocumentStatus -------返回结果：{}", jieMap);

		JSONArray reqMap = jieMap.getJSONArray("body");
		com.alibaba.fastjson.JSONObject re = reqMap.getJSONObject(0);
		//type: S-请求成功 E-请求失败
		if ("S".equals(re.get("type"))) {
			QueryDocumentRes res=re.getObject("prjProjectOperatingLeaseStatus",QueryDocumentRes.class);
			return Result.success(res);
		} else {
			throw new BusinessException("查询农户单据状态失败!失败原因："+re.get("message"));
		}
	}

	@Autowired
	private ApplicationDetailService detailService;
	@Autowired
	private SupplyOrderAuditDao supplyOrderDao;

	//查询农户单据状态   /main/redirect/queryDocumentStatus?entryId=
	@ResponseBody
	@RequestMapping(value = "sysOrderToQQ")
	public Result sysOrderToQQ(String orderId,String way){
		try {
			CrmSupplyMaterialDeliverOrder order=supplyOrderDao.get(orderId);
			if (order == null) {
				return Result.fail("订单不存在");
			}
			boolean checkSysStatus = OpenapiTemplate.checkSysStatus(orderId);
			if (!checkSysStatus) {
				return Result.fail("订单已同步");
			}

			detailService.insertQQ(order.getId(),way);
		} catch (Exception r) {
			logger.error(r.getMessage(), r);
			return Result.fail("同步失败");
		}
		return Result.ok();
	}

	@ResponseBody
	@RequestMapping(value = "initBankImg")
	public Result initBankImg(){
		customerService.initBankImg();
		return Result.ok();
	}


	@ResponseBody
	@RequestMapping(value = "lookContractUrl")
	public Result lookContractUrl(String signFlowId) throws EsignDemoException {
		logger.info(" lookContractUrl  signFlowId -------：{}", signFlowId);
		String url= ESignSignService.fileDownloadUrl(signFlowId);
		return Result.success(url);
	}

	//查询附件上传状态  /main/redirect/queryFJStatus?quryId=
	@ResponseBody
	@RequestMapping(value = "queryFJStatus")
	public Result queryFJStatus(String quryId){
		logger.info(" queryFJStatus  quryId -------：{}", quryId);
		return operatingLeaseService.findUpdateFile2(quryId);
	}
	//同步友夸数据到本地
	@ResponseBody
	@RequestMapping(value = "getYKRecords")
	public Result getYKRecords(){
		GetYouKuaRecordsTask task = new GetYouKuaRecordsTask();
		task.getYKRecords();
		return Result.ok();
	}

	//同步友夸数据到监控运维平台
	@ResponseBody
	@RequestMapping(value = "syncYWData")
	public Result syncYWData(){
		ywTask.syncYWData();
		return Result.ok();
	}

	//同步能辉数据到监控运维平台
	@ResponseBody
	@RequestMapping(value = "syncNHData")
	public Result syncNHData(){
		nhTask.syncFirstNHData();
		return Result.ok();
	}

	//手动获取并网验收后 需要查询进件状态的电站,查询进件状态
	@ResponseBody
	@RequestMapping(value = "getNeedToAskBWStatus")
	public Result getNeedToAskBWStatus(){
		yueXiuProjectOperatingService.getNeedToAskBWStatus();
		return Result.ok();
	}

	@ResponseBody
	@RequestMapping(value = "pushEntryTime")
	public Result pushEntryTime(){
		nhTask.pushEntryTime();
		return Result.ok();
	}

	@Autowired
	private NhPowerStationService nhPowerStationService;

	/**
	 * 近三天发电量
	 * @param innerStationId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "stationLastDaysEnergy")
	public Result stationLastDaysEnergyUrl(String  innerStationId){
		ThreeDaysPowerVo threeDaysPower = nhPowerStationService.getThreeDaysPower(innerStationId);
		return Result.success(threeDaysPower);
	}

	/**
	 * 手动给华融推送一次进件
	 */
	@ResponseBody
	@RequestMapping(value = "pushHrOneJJ")
	public Result pushHrOneJJ(String entryId){
		return customerService.hrOneJJ(entryId);
	}


	@Autowired
	private CustomerEntrySupplementService supplementService;

	/**
	 * 并网进件驳回，手动补充信息授权书
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("pushAuthorizationYueXiu")
	public Result pushAuthorizationYueXiu(String id){
		CustomerEntry entry = customerService.getById(id);
		return supplementService.pushAuthorizationYueXiu(entry);
	}

	/**
	 * 获取电站实时数据
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getStationRealTimeInfo")
	public Result getStationRealTimeInfo(String id){
		PowerStationVo powerStationVo = nhPowerStationService.getStationRealTimeInfo(id);
		return Result.success(powerStationVo);
	}

	//todo 一次初始化 crm_customer_entry / crm_customer_entry_tenant 表
	/**
	 * 初始化 crm_customer_entry / crm_customer_entry_tenant 表  数据
	 * 			birthday_date 出生日期
	 *         ic_validity_begin  身份证生效日
	 *         ic_validity_end  身份证到期日
	 */
	@ResponseBody
	@RequestMapping("initData")
	public Result initData(){
		customerService.initCustomerData();
		return Result.ok();
	}

	/**
	 * 发电趋势图数据
	 * @param innerStationId
	 * @param type
	 * @param time
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getPowerGenerationTrends")
	public Result getPowerGenerationTrends(String innerStationId,String type ,String time){
		Map<String, Object> map = nhPowerStationService.getPowerGenerationTrends(innerStationId, type, time);
		return Result.success(map);
	}

	//获取农户收益   /main/redirect/cashFinanceGet?dueDateFrom=20240101&dueDateTo=20240201&partnersContractNumber=
	@ResponseBody
	@RequestMapping(value = "cashFinanceGet")
	public Result cashFinanceGet(String dueDateFrom,String dueDateTo,String partnersContractNumber){
		int i=yueXiuProjectOperatingService.financeGet(dueDateFrom,dueDateTo,partnersContractNumber);
		return Result.success(i);
	}

	@Autowired
	CrmCustomerEntryRentManagementService crmCustomerEntryRentManagementService;
	//农户收益查询   /main/redirect/dealRentList
	@ResponseBody
	@RequestMapping(value = "dealRentList")
	public Result dealRentList(String startDate, String endDate, String partnersContractNumber){
		try {
			crmCustomerEntryRentManagementService.dealRentList("FULL",startDate,endDate, partnersContractNumber);
		}catch (IllegalArgumentException e){
			return Result.fail(e.getMessage());
		}
		return Result.ok();
	}
	//获取友夸租金管理电站数据
	@ResponseBody
	@RequestMapping(value = "getYouKuaStationData")
	public Result getYouKuaStationData(){
		crmCustomerEntryRentManagementService.getYouKuaStationData();
		return Result.ok();
	}

	@ResponseBody
	@RequestMapping("stockEntryPush")
	public Result stockEntryPush(String id){
		nhPowerStationService.stockEntryPush(id);
		Map<String, Object> map = null;

		return Result.success(map);
	}
	@ResponseBody
	@RequestMapping("stockEntryStationInputPiece")
	public Result stockEntryStationInputPiece(String id){
		nhPowerStationService.stockEntryStationInputPiece(id);
		Map<String, Object> map = null;

		return Result.success(map);
	}


	@ResponseBody
	@RequestMapping("queryStockInputPieceState")
	public Result queryStockInputPieceState(String id){
		nhPowerStationService.queryStockInputPieceState(id);
		Map<String, Object> map = null;

		return Result.success(map);
	}

	@ResponseBody
	@RequestMapping("terminateProject")
	public Result terminateProject(){
		nhPowerStationService.terminateProject();
		Map<String, Object> map = null;

		return Result.success(map);
	}


	// 邀请农户合同    /main/redirect/askCreateContract?entryId=
	@ResponseBody
	@RequestMapping(value = "askCreateContract")
	public Result askCreateContract(String entryId,String partnersContractNumber){
		Operator operator=new Operator();
		operator.setUserId("1");
		operator.setUserName("系统");
		CustomerEntry customerEntry= customerService.getById(entryId);
		partnerContractESignSignService.InviteSign(partnersContractNumber,customerEntry,operator,"",null,null);
		return Result.success(null);
	}

	//查询印章跨企业授权状态
	@ResponseBody
	@RequestMapping(value = "getCompanyAuthorizedSealStatus")
	private Result getCompanyAuthorizedSealStatus(String orgId,String authorizerOrgId) throws EsignDemoException {
		EsignHttpResponse response= ESignAuthService.getCompanyAuthorizedSealStatus(orgId,authorizerOrgId);
		return Result.success(response);
	}

	//根据广发历史电站的图片地址把文件保存到我们服务器
	@ResponseBody
	@RequestMapping(value = "initImgs")
	public Object initImgs() throws IOException {
		SqlBuilder builder = new SqlBuilder();
		builder.line(" select e.id,e.id_card_front,e.id_card_back,e.residence_booklet ,s.house_ownership ,e.bank_card ")
				.line("  from crm_customer_entry e ")
				.line(" left join crm_customer_entry_survey_record s on s.entry_id=e.id ")
				.line("  where e.power_station_code like 'D%' ");
		List<Record> records = Db.find(builder.build());
		logger.info("初始化数量：{}",records.size());
		for (Record record : records) {
			String idCardFront = record.getStr("id_card_front");
			String idCardBack = record.getStr("id_card_back");
			String residenceBooklet = record.getStr("residence_booklet");//户口本
			String newHouseOwnership 	= "";//房产证
			if (StringUtil.isNotBlank(record.getStr("house_ownership"))){
				String[] houseOwnerships = record.getStr("house_ownership").split(",");
				for (String houseOwnership : houseOwnerships) {
					if (StringUtils.isNotBlank(houseOwnership)) {
						String extName4 = houseOwnership.substring(houseOwnership.lastIndexOf(".")).toLowerCase();
						if (StringUtil.isBlank(newHouseOwnership)){
							newHouseOwnership = AliyunOSSClientUtil.saveUrlWeb(houseOwnership,extName4);
						}else {
							newHouseOwnership = newHouseOwnership + "," + AliyunOSSClientUtil.saveUrlWeb(houseOwnership,extName4);
						}
					}
				}
			}
			String bankCard = record.getStr("bank_card");//银行卡

			String extName1 = idCardFront.substring(idCardFront.lastIndexOf(".")).toLowerCase();
			String extName2 = idCardBack.substring(idCardBack.lastIndexOf(".")).toLowerCase();
			String extName3 = residenceBooklet.substring(residenceBooklet.lastIndexOf(".")).toLowerCase();
			String extName5 = bankCard.substring(bankCard.lastIndexOf(".")).toLowerCase();

			String newIdCardFront= AliyunOSSClientUtil.saveUrlWeb(idCardFront,extName1);
			String newIdCardBack= AliyunOSSClientUtil.saveUrlWeb(idCardBack,extName2);
			String newResidenceBooklet= AliyunOSSClientUtil.saveUrlWeb(residenceBooklet,extName3);
			String newBankCard = AliyunOSSClientUtil.saveUrlWeb(bankCard,extName5);

			Db.update(" update  crm_customer_entry e, crm_customer_entry_survey_record r set e.id_card_front=?," +
					"e.id_card_back=?,e.residence_booklet=?,e.bank_card = ? ,r.house_ownership=? " +
					"where e.id=r.entry_id and e.id=? ",newIdCardFront,newIdCardBack,newResidenceBooklet,newBankCard,newHouseOwnership,record.getStr("id"));
		}
		return Result.ok();
	}

	//处理广发历史电站丢失客户记录问题
	@ResponseBody
	@RequestMapping(value = "initStockEntryTenantInfo")
	public Result initStockEntryTenantInfo(){
		customerService.selectEntryInfo();
		return Result.ok();
	}

	//删除固德威平台的电站设备
	@ResponseBody
	@RequestMapping(value = "removeStationGoodW")
	public Result removeStationGoodW(String entryId, String sid, String sn, String partnerId){
		try {
			customerService.removeInverterGoodW(entryId, sid, sn, partnerId);
			return Result.ok();
		}catch (Exception e){
			return Result.fail(e.getMessage());
		}
	}

	@Autowired
	OneDealService dealService;

	@ResponseBody
	@RequestMapping(value = "movOldMaterialRecords")
	public Result movOldMaterialRecords(String codes){
		String[] codeS = codes.split(",");
		String msg = "";
		for (String code : codeS) {
			try {
				String error = dealService.movOldMaterialRecords(code);
				if (StringUtil.isNotBlank(error)){
					msg = msg + "," + code +error;
				}
			}catch (Exception e) {
				logger.error(e.getMessage(), e);
				msg = msg + "," + code ;
			}
		}
		if (StringUtil.isNotBlank(msg)) {
			msg = msg + " 迁移失败";
		}
		return Result.ok(msg);
	}

	@Autowired
	private CrmEntryQualitySeekEntryDao qualitySeekEntryDao;

	//初始化数据（安装验收后的数据）   /main/redirect/initAzFinishEntry
	@ResponseBody
	@RequestMapping(value = "initAzFinishEntry")
	public Result initAzFinishEntry(){
		List<Record> list= Db.find(" SELECT e.id,e.power_station_code,IFNULL(e.install_accept_time,e.install_time) as install_accept_time,e.status,e.distributor_id  " +
				" FROM crm_customer_entry e LEFT JOIN crm_entry_quality_seek_entry s ON s.entry_id=e.id WHERE e.check_accept_flag IN ('4') AND s.id IS NULL and e.partner_id='01' ");
		logger.info("....initAzFinishEntry  count:{}",list.size());
		for(Record record:list){
			//生成一条安装验收通过待生成巡检单的记录
			logger.info("...initAzFinishEntry  id:{}",record.getStr("id"));
			qualitySeekEntryDao.saveSeekEntry(record.getStr("id"),record.getStr("distributor_id"), record.getDate("install_accept_time")==null?new Date():record.getDate("install_accept_time"));
		}
		return Result.ok();
	}


	//撤销E签宝的合同（不安全，撤销后不能恢复）   /main/redirect/revokeESignContract?signFlowIds=
	@ResponseBody
	@RequestMapping(value = "revokeESignContract")
	public Result revokeESignContract(String signFlowIds){
		StringBuilder errorMsg=new StringBuilder("错误的合同流程id：");
		int successCount=0;
		for(String signFlowId:signFlowIds.split(",")){
			try {
				ESignSignService.revoke(signFlowId);
				successCount++;
			} catch (EsignDemoException e) {
				e.printStackTrace();
				errorMsg.append(signFlowId+",");
				continue;
			}
		}
		Map<String,Object> resultMap=new HashMap<>();
		resultMap.put("errorMsg",errorMsg);
		resultMap.put("successCount",successCount);
		return Result.success(resultMap);
	}

	//华融混合屋顶生成结算明细
	@ResponseBody
	@RequestMapping(value = "getHuaRongMixRoofSettlement")
	public Result getHuaRongMixRoofSettlement(){
		huaRongGetStatusTask.getHuaRongMixRoofSettlement();
		return Result.ok();
	}

	@ResponseBody
	@RequestMapping(value = "sysPaidDateTask")
	public Result sysPaidDateTask() {
		logger.info(">>>>>>>>sysPaidDateTask  定时任务开始");
		crmCustomerEntryRentManagementService.sysPaidDate();
		logger.info(">>>>>>>>sysPaidDateTask  定时任务开始");
		return Result.ok();
	}
	/**
	 * 更新首日发电日期
	*/
	@ResponseBody
	@RequestMapping(value = "updateFirstGenerationTime")
	public void updateFirstGenerationTime(HttpServletRequest request,String powerStationCode,String time){

		CustomerEntry customerEntry= customerService.findCustomerEntryById(powerStationCode);
		if(customerEntry!= null){
			customerEntry.setFirstGenerationTime(DateUtils.parseDate(time));
			customerService.saveByUpdate(customerEntry);
		}

	}


}
