package com.fs.app.controller;


import cn.hutool.core.net.URLDecoder;
import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.Login;
import com.fs.app.param.TestMoneyParam;
import com.fs.app.utils.JwtUtils;
import com.fs.common.config.FSSysConfig;
import com.fs.common.core.domain.R;
import com.fs.common.exception.file.OssException;
import com.fs.company.domain.CompanyMoneyLogs;
import com.fs.company.service.ICompanyMoneyLogsService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.core.config.ServerConfig;
import com.fs.erp.domain.*;
import com.fs.erp.dto.*;
import com.fs.erp.service.IErpGoodsService;
import com.fs.erp.service.IErpOrderService;
import com.fs.erp.service.IErpShopService;
import com.fs.erp.service.IErpUserService;
import com.fs.pay.pay.domain.OrderResult;
import com.fs.pay.pay.dto.OrderQueryDTO;
import com.fs.pay.pay.service.PayService;
import com.fs.pay.pay.service.impl.PayApiServiceImpl;
import com.fs.store.config.StoreConfig;
import com.fs.store.domain.*;
import com.fs.store.dto.ExpressDataDTO;
import com.fs.store.dto.ExpressInfoDTO;
import com.fs.store.dto.ExpressNotifyDTO;
import com.fs.store.param.SignParam;
import com.fs.store.service.*;
import com.fs.pay.service.IPayService;
import com.fs.pay.service.dto.*;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.system.vo.DictVO;
import com.fs.system.service.ISysConfigService;
import com.fs.system.service.ISysDictDataService;
import com.hc.openapi.tool.util.Ids;
import com.tencentyun.TLSSigAPIv2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;


@Api("公共接口")
@RestController
@RequestMapping(value="/app/common")
public class CommonController extends AppBaseController {
	Logger logger = LoggerFactory.getLogger(CommonController.class);
	@Autowired
    JwtUtils jwtUtils;
	@Autowired
	private ServerConfig serverConfig;
	@Autowired
	private ISysDictDataService dictDataService;

	@Autowired
	private ISysConfigService configService;
	@Autowired
	IPrescribeService prescribeService;

	@Autowired
	IFsStoreOrderItemService orderItemService;
	@Autowired
	IFsStoreProductService productService;
	@Autowired
	FSSysConfig fsSysConfig;
	@Autowired
	IErpShopService erpShopService;
	@Autowired
	IErpUserService userService;
	@Autowired
	IPayService payService;
	@Autowired
	IErpOrderService erpOrderService;
	@Autowired
	IErpGoodsService goodsService;
	@Autowired
	PayService ybPayService;
	@Autowired
	private IFsWechatTemplateService wechatTemplateService;


	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private FSSysConfig sysConfig;

	@Autowired
	private IFsExpressService expressService;

	@Autowired
	private ICompanyService companyService;

	@Autowired
	ICompanyUserService companyUserService;
	@Autowired
	ICompanyMoneyLogsService logsService;
	@Autowired
	private IFsStoreOrderItemService storeOrderItemService;
	@Autowired
	private IFsCityService cityService;
	@Autowired
	IFsStoreOrderService orderService;
	@Autowired
	IFsStorePaymentService paymentService;
//	@ApiOperation("批量推送订单")
//	@GetMapping("pushOms")
//	public R pushOms(String startTime) throws Exception
//	{
//		List<Long> ids=orderService.selectFsStoreOrderToPushByIds(startTime);
//		for(Long id:ids){
//			orderService.createOmsOrder(id);
//		}
//		return R.ok();
//
//	}
	@ApiOperation("支付手动通知")
	@GetMapping("payNotify")
	public R payNotify(String payCode) throws Exception
	{
		OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
		orderQueryDTO.setLowOrderId("store-"+payCode);
		OrderResult orderResult = ybPayService.getOrder(orderQueryDTO);
		return R.ok().put("data",orderResult);
	}



//	@ApiOperation("testGetOrder")
//	@GetMapping("testGetOrder")
//	public R testGetOrder(String orderId) throws Exception
//	{
//		PayApiServiceImpl payService = new PayApiServiceImpl();
//		OrderQueryDTO o = new OrderQueryDTO();
////        o.setLowOrderId("orderWx123456121");
//		o.setUpOrderId(orderId);
//		OrderResult order = payService.getOrder(o);
//
//		return R.ok().put("data",order);
//	}


//	@ApiOperation("同步企业金额")
//	@PostMapping("testUpdateCompanyMoney")
//	public R testUpdateCompanyMoney(@RequestBody TestMoneyParam param) throws Exception
//	{
//		List<CompanyMoneyLogs> logs=logsService.selectCompanyMoneyLogsByCompanyId(param.getCompanyId(),param.getLogsId().toString());
//		if(logs!=null){
//			BigDecimal companyMoney=param.getMoney();
//			for(CompanyMoneyLogs log:logs){
//				companyMoney=companyMoney.add(log.getMoney());
//				CompanyMoneyLogs logMap=new CompanyMoneyLogs();
//				logMap.setLogsId(log.getLogsId());
//				logMap.setBalance(companyMoney);
//				logsService.updateCompanyMoneyLogs(logMap);
//			}
//		}
//		return R.ok();
//	}



	@ApiOperation("testErpDeliverys")
	@PostMapping("testErpDeliverys")
	public R testErpDeliverys(@RequestBody  ErpDeliverysRequest request) throws Exception
	{
		request.setDetail_flag(true);
		return R.ok().put("data", erpOrderService.getDeliver(request));
	}
	@ApiOperation("testErpGetOrder")
	@PostMapping("testErpGetOrder")
	public R testErpGetOrder(@RequestBody ErpOrderQueryRequert request) throws Exception
	{
		return R.ok().put("data", erpOrderService.getOrder(request));
	}

	@ApiOperation("testErpGetGoods")
	@PostMapping("testErpGetGoods")
	public R testErpGetGoods(@RequestBody ErpGoodsQueryRequert request) throws Exception
	{
		return R.ok().put("data", goodsService.getGoods(request));
	}

	@ApiOperation("testErpGetGoodsStock")
	@PostMapping("testErpGetGoodsStock")
	public R testErpGetGoodsStock(@RequestBody ErpGoodsStockQueryRequert request) throws Exception
	{
		return R.ok().put("data", goodsService.getGoodsStock(request));
	}




	@ApiOperation("testRefundErp")
	@PostMapping("testRefundErp")
	public R testRefundErp() throws Exception
	{
		ErpRefundOrder order=new ErpRefundOrder();
		order.setShop_code(fsSysConfig.getErpShopCode());
		order.setVip_code("10000");
		order.setType_code("001");
		order.setTrade_platform_code("202211111110");
		List<ErpOrderItem> details=new ArrayList<>();
		ErpOrderItem item=new ErpOrderItem();
		item.setItem_code("105015");
		// item.setSku_code("1122");
		item.setOrigin_price("1.00");
		item.setPrice("12.00");
		item.setQty(1);
		item.setRefund(0);
		details.add(item);
		order.setDetails(details);


		return R.ok().put("data", erpOrderService.refundOrder(order));
	}





//	@ApiOperation("testTask")
//	@PostMapping("testTask")
//	public void testErpGetOrder() throws Exception
//	{
//		Set<String> orders=redisTemplate.keys(DELIVERY+":*");
//		for(String extndOrderId:orders){
//			String orderCode=(String)redisTemplate.opsForValue().get(extndOrderId);
//			ErpOrderQueryRequert request=new ErpOrderQueryRequert();
//			String[] extendOrder=extndOrderId.split(":");
//			request.setCode(extendOrder[1]);
//			ErpOrderQueryResponse response=erpOrderService.getOrder(request);
//			if(response.getOrders()!=null&&response.getOrders().size()>0){
//				for(ErpOrderQuery orderQuery : response.getOrders()){
//					if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
//						//更新商订单状态 删除REDIS
//						orderService.deliveryOrder(orderCode,orderQuery.getDeliverys().get(0).getMail_no());
//						redisCache.deleteObject(DELIVERY+":"+extndOrderId);
//					}
//				}
//			}
//		}
//
//	}




	@ApiOperation("testErpGoods")
	@PostMapping("testErpGoods")
	public R testErpGoods() throws Exception
	{
		ErpGoods goods=new ErpGoods();
		goods.setCode("11");
		goods.setName("测试商品");
		goods.setSimple_name("test");
		goods.setItem_add_attribute(0);
		List<ErpGoodsSku> skus =new ArrayList<>();
		ErpGoodsSku sku=new ErpGoodsSku();
		sku.setSku_code("1122");
		sku.setSku_name("12寸");
		sku.setSku_agent_price("12");
		sku.setSku_cost_price("1");
		skus.add(sku);
		goods.setSkus(skus);

		return R.ok().put("data", goodsService.addGoods(goods));
	}



	@ApiOperation("testErp")
	@PostMapping("testErp")
	public R testErp() throws Exception
	{
		ErpOrder order=new ErpOrder();
		order.setShop_code(fsSysConfig.getErpShopCode());
		order.setVip_code("10000");
		order.setPlatform_code("202211111110");
		order.setWarehouse_code("CQDS001");
		order.setExpress_code("YZJD");
		order.setPost_fee(1.00);
		order.setSeller_memo("备注");
		// order.setCurrency_code("JCZD");
		// order.setCod_fee(2.00);//到 付服务费
		order.setBuyer_memo("备注");
		order.setOrder_type_code("order");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		order.setDeal_datetime(sdf.format(new Date()));
		List<ErpOrderItem> details=new ArrayList<>();
		ErpOrderItem item=new ErpOrderItem();
		item.setItem_code("105015");
		// item.setSku_code("1122");
		item.setOrigin_price("1.00");
		item.setPrice("12.00");
		item.setQty(1);
		item.setRefund(0);
		details.add(item);
		order.setDetails(details);
		order.setReceiver_name("张三");
		order.setReceiver_mobile("15193139333");
		order.setReceiver_province("重庆市");
		order.setReceiver_city("重庆市");
		order.setReceiver_district("江北区");
		order.setReceiver_address("观音桥街道中翰名苑");
		return R.ok().put("data", erpOrderService.addOrder(order));
	}


	@ApiOperation("testRefundErp1")
	@PostMapping("testRefundErp1")
	public R testRefundErp1() throws Exception
	{
		ErpRefundUpdateRequest request=new ErpRefundUpdateRequest();
		request.setTid("1546383973272256512");
		request.setOid("1546383973272256512");
		request.setRefund_state(1);
		return R.ok().put("data", erpOrderService.refundUpdate(request));
	}
	@ApiOperation("testErpAddUser")
	@PostMapping("testErpAddUser")
	public R testErpAddUser() throws Exception
	{
		ErpUser user=new ErpUser();
		user.setCode("test001");
		user.setName("测试001");
		user.setShop_code(fsSysConfig.getErpShopCode());
		List<ErpUserAddress> receive_infos=new ArrayList<>();
		ErpUserAddress address=new ErpUserAddress();
		// address.setAddress("详细地址");
		// address.setArea("北京-北京市-朝阳区");
		// address.setMobile("15193190697");
		// address.setReceiver("张三");
		// address.setName(user.getName());
		// receive_infos.add(address);
		user.setReceive_infos(receive_infos);
		BaseResponse response=userService.addUser(user);
		return R.ok();
	}

	@ApiOperation("testCreateOrder")
	@GetMapping("testCreateOrder")
	public R testCreateOrder(@RequestParam("orderId") String orderId) throws Exception
	{
		// return payService.createOrder(orderId);
		return R.ok();
	}

	@ApiOperation("testRefund")
	@PostMapping("testPay")
	public R testPay(RefundDTO dto) {
		dto.setMerchOrderNo(Ids.oid());
		return payService.refundOrder(dto);


	}
	@ApiOperation("上传证件")
	@PostMapping("upload")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception
	{
		String fileName = file.getOriginalFilename();
		byte[] fileByte = null;
		try {
			fileByte = file.getBytes();
		} catch (IOException e) {
			return R.error(e.getMessage());
		}
		String voiceBase64= Base64.getEncoder().encodeToString(fileByte);
		UploadDTO dto=new UploadDTO();
		dto.setFileName(fileName);
		dto.setData(voiceBase64);
		return payService.upload(dto);
	}

	@ApiOperation("开户")
	@PostMapping("openBusiness")
	public R openBusiness(@RequestBody  OpenBusinessDTO dto) throws Exception
	{
		return payService.openBusiness(dto);
	}
	@ApiOperation("开户查询")
	@PostMapping("openQuery")
	public R openQuery(@RequestBody OpenQueryDTO dto) throws Exception
	{
		return payService.openQuery(dto);
	}

	@ApiOperation("查询余额")
	@PostMapping("queryBalance")
	public R queryBalance(@RequestBody QueryFullBalanceDTO dto) throws Exception
	{
		return payService.queryFullBalance(dto);
	}


	/**
	 * 通用上传请求
	 */
	@PostMapping("uploadOSS")
	public R uploadOSS(@RequestParam("file") MultipartFile file) throws Exception
	{

		if (file.isEmpty())
		{
			throw new OssException("上传文件不能为空");
		}
		// 上传文件
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		CloudStorageService storage = OSSFactory.build();
		String url = storage.uploadSuffix(file.getBytes(), suffix);
		return R.ok().put("url",url);
	}

	@ApiOperation("获取数据字典")
	@GetMapping("/getDicts")
//	@Cacheable(value= "dicts")
	public R getDicts(){
		List<DictVO> doctorPosition=dictDataService.selectDictDataListByType("doctor_position");
		List<DictVO> doctorOrderStatus=dictDataService.selectDictDataListByType("doctor_order_status");
		List<DictVO> storeOrderStatus=dictDataService.selectDictDataListByType("store_order_status");
		List<DictVO> storeAfterSalesReasons=dictDataService.selectDictDataListByType("store_after_sales_reasons");
		List<DictVO> storeProductType=dictDataService.selectDictDataListByType("store_product_type");
		List<DictVO> storeAfterSalesSalesStatus=dictDataService.selectDictDataListByType("store_after_sales_sales_status");
		List<DictVO> storeAfterSalesStatus=dictDataService.selectDictDataListByType("store_after_sales_status");
		List<DictVO> storeProductPackageCate=dictDataService.selectDictDataListByType("store_product_package_cate");
		List<DictVO> storeProductTuiCate=dictDataService.selectDictDataListByType("store_product_tui_cate");
		return R.ok()
				.put("storeProductPackageCate",storeProductPackageCate)
				.put("storeAfterSalesStatus",storeAfterSalesStatus)
				.put("storeAfterSalesSalesStatus",storeAfterSalesSalesStatus)
				.put("storeProductType", storeProductType)
				.put("doctorPosition",doctorPosition)
				.put("doctorOrderStatus",doctorOrderStatus)
				.put("storeOrderStatus", storeOrderStatus)
				.put("storeAfterSalesReasons", storeAfterSalesReasons)
				.put("storeProductTuiCate",storeProductTuiCate);
	}

	@GetMapping(value = "/getStoreConfig")
	@ApiOperation("获取系统配置")
	public R getStoreConfig()
	{
		String config=configService.selectConfigByKey("store.config");
		StoreConfig storeConfig= JSONUtil.toBean(config,StoreConfig.class);
		return  R.ok().put("data",storeConfig);

	}

	@GetMapping(value = "/getConfigByKey")
	@ApiOperation("获取配置")
	public R getConfigByKey(@RequestParam(value = "key", required = false) String key)
	{
		String config=configService.selectConfigByKey(key);
		return  R.ok().put("data",config);

	}

	@ApiOperation("获取数据字典")
	@GetMapping("/getDictByKey")
	public R getDictByKey(@ApiParam(required = false, name = "key", value = "key") @RequestParam(value = "key", required = false) String key){
		List<DictVO> dictVOS=dictDataService.selectDictDataListByType(key);
		return R.ok().put("data",dictVOS);
	}


	@Login
	@GetMapping(value = "/getTlsSig")
	@ApiOperation("获取腾讯云签名")
	public R getTlsSig(@Validated SignParam signParam)
	{
		TLSSigAPIv2 api = new TLSSigAPIv2(fsSysConfig.getSdkAppId(), fsSysConfig.getSdkAppKey());
		String sign=api.genUserSig(signParam.getUserId(),180*86400);
		return R.ok().put("data",sign);
	}


	//
	// @ApiOperation("测试开处方")
	// @PostMapping("/doPrescribe")
	// public R doPrescribe() throws Exception
	// {
	// 	PrescribeParam prescribeParam=new PrescribeParam();
	// 	List<Prescribe> data=new ArrayList<>();
	// 	Prescribe prescribe=new Prescribe();
	// 	prescribe.setRp_id(OrderUtils.getOrderNo());
	// 	prescribe.setPharmacy_code("00001");
	// 	prescribe.setPharmacy_name("测试门店");
	// 	prescribe.setPatient_name("张三");
	// 	prescribe.setPatient_age(12);
	// 	prescribe.setPatient_tel("15193190697");
	// 	prescribe.setPatient_gender("1");
	// 	prescribe.setIs_history_allergic("否");
	// 	prescribe.setLiver_unusual("否");
	// 	prescribe.setRenal_unusual("否");
	// 	prescribe.setLactation_flag("否");
	// 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	// 	Date now = new Date();
	// 	prescribe.setRp_create_time(sdf.format(now));
	// 	prescribe.setRp_url_type("png");
	// 	prescribe.setLactation_flag("否");
	// 	prescribe.setCallback_url(fsSysConfig.getCallbackUrl());
	// 	data.add(prescribe);
	//
	// 	List<Drug> drug_list=new ArrayList<>();
	// 	Drug drug=new Drug();
	// 	drug.setDrug_common_name("维力青 恩替卡韦分散片 0.5mg*7片");
	// 	drug.setDrug_specification("0.5mg*7片");
	// 	drug.setSale_amount("1");
	// 	drug.setSale_unit("盒");
	// 	drug.setApproval_number("000001");
	// 	drug_list.add(drug);
	// 	prescribe.setDrug_list(drug_list);
	// 	prescribeParam.setData(data);
	//
	// 	prescribeService.doPrescribe(prescribeParam);
	// 	return R.ok();
	// }


	@ApiOperation("创建ERP订单")
	@GetMapping("createErpOrder")
	public R createErpOrder(@RequestParam("orderCode") String orderCode) throws Exception
	{
		FsStoreOrder order=orderService.selectFsStoreOrderByOrderCode(orderCode);
		orderService.createOmsOrder(order.getId());
		return R.ok();
	}



	@ApiOperation("查询运单信息")
	@PostMapping("testGetExpress")
	public R testGetExpress(@RequestParam("orderId")Long orderId) throws Exception
	{
		FsStoreOrder order=orderService.selectFsStoreOrderById(orderId);
		return orderService.getExpress(order);

	}
	@ApiOperation("查询运单信息")
	@PostMapping(path = "expressNotify" )
	public void expressNotify(ExpressNotifyDTO notifyDTO) throws Exception
	{

		//RequestData={"PushTime":"2022-09-06 09:59:26","EBusinessID":"1762981","Data":[{"StateEx":"0","LogisticCode":"SF1650775430012","ShipperCode":"SF","State":"0","OrderCode":"XCRTZH22090500435","EBusinessID":"1762981","Success":false}],"Count":"1"}&DataSign=YTEwMzAxMTAzNGI4ZjQ0OTU5MWE1Y2U0NzMzYTczNWM=&RequestType=102
		//RequestData={"PushTime":"2022-09-06 10:28:41","EBusinessID":"1762981","Data":[{"StateEx":"301","LogisticCode":"SF1372196615474","ShipperCode":"SF","Traces":[{"Action":"1","AcceptStation":"顺丰速运 已收取快件","AcceptTime":"2022-09-04 15:27:25","Remark":"","Location":"重庆"},{"Action":"1","AcceptStation":"顺丰速运 已收取快件","AcceptTime":"2022-09-04 15:34:27","Remark":"","Location":"重庆市"},{"Action":"2","AcceptStation":"快件在【重庆南岸区时代都汇营业点】完成分拣,准备发往 【重庆渝北中转场】","AcceptTime":"2022-09-04 17:17:16","Remark":"","Location":"重庆市"},{"Action":"2","AcceptStation":"快件已发车","AcceptTime":"2022-09-04 17:44:37","Remark":"","Location":"重庆市"},{"Action":"2","AcceptStation":"快件到达 【重庆渝北中转场】","AcceptTime":"2022-09-04 22:13:11","Remark":"","Location":"重庆市"},{"Action":"2","AcceptStation":"快件在【重庆渝北中转场】完成分拣,准备发往 【郑州港区中转场】","AcceptTime":"2022-09-05 00:04:51","Remark":"","Location":"重庆市"},{"Action":"2","AcceptStation":"快件已发车","AcceptTime":"2022-09-05 04:45:47","Remark":"","Location":"重庆市"},{"Action":"2","AcceptStation":"车辆当前所在位置道路管控，等待通行中，请您耐心等待\n","AcceptTime":"2022-09-05 19:35:55","Remark":"","Location":"重庆市"},{"Action":"2","AcceptStation":"快件到达 【郑州港区中转场】","AcceptTime":"2022-09-05 22:43:06","Remark":"","Location":"郑州市"},{"Action":"2","AcceptStation":"快件在【郑州港区中转场】完成分拣,准备发往 【焦作丰收集散点】","AcceptTime":"2022-09-05 23:16:24","Remark":"","Location":"郑州市"},{"Action":"2","AcceptStation":"快件已发车","AcceptTime":"2022-09-06 00:43:25","Remark":"","Location":"郑州市"},{"Action":"2","AcceptStation":"车辆当前所在位置道路管控，等待通行中，请您耐心等待\n","AcceptTime":"2022-09-06 01:03:39","Remark":"","Location":"郑州市"},{"Action":"2","AcceptStation":"快件到达 【焦作丰收集散点】","AcceptTime":"2022-09-06 03:03:35","Remark":"","Location":"焦作市"},{"Action":"2","AcceptStation":"快件在【焦作丰收集散点】完成分拣,准备发往 【济源市济源市汤帝路营业点】","AcceptTime":"2022-09-06 06:41:58","Remark":"","Location":"焦作市"},{"Action":"2","AcceptStation":"快件已发车","AcceptTime":"2022-09-06 06:42:17","Remark":"","Location":"焦作市"},{"Action":"2","AcceptStation":"车辆当前所在位置道路管控，等待通行中，请您耐心等待\n","AcceptTime":"2022-09-06 07:58:17","Remark":"","Location":"济源市"},{"Action":"2","AcceptStation":"快件到达 【济源市济源市汤帝路营业点】","AcceptTime":"2022-09-06 08:27:59","Remark":"","Location":"济源市"},{"Action":"202","AcceptStation":"正在派送途中,请您准备签收(派件人：刘亚飞，电话：18439188789)","AcceptTime":"2022-09-06 08:28:00","Remark":"","Location":"济源市"},{"Action":"202","AcceptStation":"快件交给刘亚飞，正在派送途中（联系电话：18439188789，顺丰已开启“安全呼叫”保护您的电话隐私,请放心接听！）（主单总件数：1件）","AcceptTime":"2022-09-06 08:38:03","Remark":"","Location":"济源市"},{"Action":"301","AcceptStation":"您的快件已签收，如有疑问请电联快递员【刘亚飞，电话：18439188789】。疫情期间顺丰每日对网点消毒、快递员每日测温、配戴口罩，感谢您使用顺丰，期待再次为您服务。（主单总件数：1件）","AcceptTime":"2022-09-06 08:54:05","Remark":"","Location":"济源市"}],"State":"3","OrderCode":"SKP012000681762","EBusinessID":"1762981","Success":true,"Location":"济源市"}],"Count":"1"}&DataSign=MTNlYTA5OTJmMjgxYjhiY2FjMTZjNTYyOGYxYjVhODA=&RequestType=102
		//https://api.hospital.ifeiyu100.com/app/common/expressNotify
		String data=URLDecoder.decode(notifyDTO.getRequestData(), Charset.forName("UTF-8"));
		//ExpressInfoDTO
		logger.info("快递根踪回调:"+data);
		ExpressDataDTO expressDataDTO=JSONUtil.toBean(data,ExpressDataDTO.class);
		if(expressDataDTO!=null&&expressDataDTO.getData()!=null){
			for(ExpressInfoDTO dto:expressDataDTO.getData()){
				List<FsStoreOrder> orders=orderService.selectFsStoreOrderListByDeliveryId(dto.getLogisticCode());
				if(orders!=null){
					for(FsStoreOrder order:orders){
						logger.info("订单信息:"+JSONUtil.toJsonStr(order));
						logger.info("运单号:"+dto.getLogisticCode());
						if(order!=null && order.getDeliveryStatus()!=3){
							FsStoreOrder map=new FsStoreOrder();
							map.setDeliveryStatus(Integer.parseInt(dto.getState()));
							map.setId(order.getId());
							map.setDeliveryType(dto.getStateEx());
							orderService.updateFsStoreOrder(map);
							//如果是正常签收，更新订单状态
							if(dto.getState().equals("3")&&(dto.getStateEx().equals("301")||dto.getStateEx().equals("302")||dto.getStateEx().equals("304")||dto.getStateEx().equals("311"))){
								orderService.finishOrder(order.getId());
							}

						}
					}
				}

			}
		}

	}

	@ApiOperation("获取微信模板")
	@GetMapping("/getWeixinTemps")
	@Cacheable(value= "temps")
	public R getWeixinTemps(
	){
		List<String> temp=wechatTemplateService.selectFsWechatTemplateIds();
		return R.ok().put("temp",temp);

	}

	@ApiOperation("获取微信模板")
	@GetMapping("/getWeixinOrderTemps")
	@Cacheable(value= "orderTemps")
	public R getWeixinOrderTemps(
	){
		List<String> temp=wechatTemplateService.selectFsWechatTemplateIdsByKeys("delivery_success,finish_success,cancel_success");
		return R.ok().put("temp",temp);

	}
	@ApiOperation("获取微信模板")
	@GetMapping("/getWeixinPrescribeTemps")
	@Cacheable(value= "prescribetemps")
	public R getWeixinPrescribeTemps(
	){
		List<String> temp=wechatTemplateService.selectFsWechatTemplateIdsByKeys("prescribe");
		return R.ok().put("temp",temp);

	}


	@ApiOperation("导入CVS")
	@PostMapping("importCVS")
	public R importCVS(@RequestParam("file") MultipartFile file) throws Exception
	{
		File csv = new File("c:\\1.cvs");
		FileUtils.copyInputStreamToFile(file.getInputStream(), csv);
		BufferedReader br = null;
		try
		{
			br = new BufferedReader(new FileReader(csv));
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		String line = "";
		try {
			Integer index=0;
			while ((line = br.readLine()) != null)
			{
				if(index>0){
					String[] data=line.split(",");
					FsCity city=new FsCity();
					city.setCityId(Long.parseLong(data[0]));
					city.setParentId(Long.parseLong(data[1]));
					city.setLevel(Long.parseLong(data[2]));
					city.setName(data[7]);
					city.setAreaCode(data[6]);
					city.setIsShow(1);
					cityService.insertFsCity(city);
				}

				System.out.println(line);
				index++;

			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		return R.ok();
	}




}
