package com.fs.app.controller.store;


import cn.hutool.core.net.URLDecoder;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.app.controller.AppBaseController;
import com.fs.app.param.SignParam;
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.common.utils.security.OssUploadSecurityUtils;
import com.fs.company.service.ICompanyMoneyLogsService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsCoursePlaySourceConfig;
import com.fs.course.service.IFsCoursePlaySourceConfigService;
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.his.service.IFsCityService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.config.StoreConfig;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.dto.ExpressDataDTO;
import com.fs.hisStore.dto.ExpressInfoDTO;
import com.fs.hisStore.dto.ExpressNotifyDTO;
import com.fs.hisStore.enums.SysConfigEnum;
import com.fs.hisStore.service.*;
import com.fs.pay.pay.dto.OrderQueryDTO;
import com.fs.pay.service.IPayService;
import com.fs.pay.service.dto.OpenBusinessDTO;
import com.fs.pay.service.dto.OpenQueryDTO;
import com.fs.pay.service.dto.QueryFullBalanceDTO;
import com.fs.pay.service.dto.UploadDTO;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.fs.system.service.ISysConfigService;
import com.fs.system.service.ISysDictDataService;
import com.fs.system.vo.DictVO;
import com.fs.ybPay.domain.OrderResult;
import com.tencentyun.TLSSigAPIv2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.IOException;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.List;


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

    @Autowired
    private ISysConfigService configService;

    @Autowired
    IFsStoreOrderItemScrmService orderItemService;
    @Autowired
    FSSysConfig fsSysConfig;
    @Autowired
    ConfigUtil configUtil;
    @Autowired
    IErpShopService erpShopService;
    @Autowired
    IErpUserService userService;
    @Autowired
    IPayService payService;
    @Autowired
    IPayService ybPayService;
    @Autowired
    private IFsWechatTemplateScrmService wechatTemplateService;
    @Autowired
    @Qualifier("erpOrderServiceImpl")
    private IErpOrderService gyOrderService;

    @Autowired
    @Qualifier("wdtErpOrderServiceImpl")
    private IErpOrderService wdtOrderService;

	@Autowired
	@Qualifier("k9OrderScrmServiceImpl")
	private IErpOrderService k9OrderService;

    @Qualifier("erpGoodsServiceImpl")
    private IErpGoodsService gyGoodsService;

    @Autowired
    @Qualifier("wdtErpGoodsServiceImpl")
    private IErpGoodsService wdtErpGoodsService;

    @Autowired
    @Qualifier("hzOMSErpOrderServiceImpl")
    private IErpOrderService hzOMSOrderService;

    @Autowired
    @Qualifier("dfOrderServiceImpl")
    private IErpOrderService dfOrderService;
    @Autowired
    @Qualifier("k9StockScrmServiceImpl")
    private IErpGoodsService k9StockService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private IFsExpressScrmService expressService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    ICompanyUserService companyUserService;
    @Autowired
    ICompanyMoneyLogsService logsService;
    @Autowired
    private IFsStoreOrderItemScrmService storeOrderItemService;
    @Autowired
    private IFsCityService cityService;
    @Autowired
    IFsStoreOrderScrmService orderService;
    @Autowired
    IFsStorePaymentScrmService paymentService;

    @Autowired
    private IFsCoursePlaySourceConfigService fsCoursePlaySourceConfigService;

    @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("testErpDeliverys")
//    @PostMapping("testErpDeliverys")
//    public R testErpDeliverys(@RequestBody ErpDeliverysRequest request) throws Exception {
//        IErpOrderService erpOrderService = getErpOrderService();
//        request.setDetail_flag(true);
//        return R.ok().put("data", erpOrderService.getDeliver(request));
//    }

//    @ApiOperation("testErpGetOrder")
//    @PostMapping("testErpGetOrder")
//    public R testErpGetOrder(@RequestBody ErpOrderQueryRequert request) throws Exception {
//        IErpOrderService erpOrderService = getErpOrderService();
//        return R.ok().put("data", erpOrderService.getOrder(request));
//    }
//
//    @ApiOperation("testErpGetGoods")
//    @PostMapping("testErpGetGoods")
//    public R testErpGetGoods(@RequestBody ErpGoodsQueryRequert request) throws Exception {
//        IErpGoodsService goodsService = getErpGoodService();
//        return R.ok().put("data", goodsService.getGoods(request));
//    }

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

//    @ApiOperation("testRefundErp")
//    @PostMapping("testRefundErp")
//    public R testRefundErp() throws Exception {
//        IErpOrderService erpOrderService = getErpOrderService();
//        FsErpConfig erpConfig = configUtil.getErpConfig();
//        ErpRefundOrder order = new ErpRefundOrder();
//        order.setShop_code(erpConfig.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("testErpGoods")
//    @PostMapping("testErpGoods")
//    public R testErpGoods() throws Exception {
//        IErpGoodsService goodsService = getErpGoodService();
//        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 {
//        IErpOrderService erpOrderService = getErpOrderService();
//        FsErpConfig erpConfig = configUtil.getErpConfig();
//        ErpOrder order = new ErpOrder();
//        order.setShop_code(erpConfig.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 {
//        IErpOrderService erpOrderService = getErpOrderService();
//        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 {
//        FsErpConfig erpConfig = configUtil.getErpConfig();
//        ErpUser user = new ErpUser();
//        user.setCode("test001");
//        user.setName("测试001");
//        user.setShop_code(erpConfig.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 safeFileName = OssUploadSecurityUtils.validateAndGetSafeFilename(file);
        byte[] fileByte = null;
        try {
            fileByte = file.getBytes();
        } catch (IOException e) {
            return R.error(e.getMessage());
        }
        String fileName = safeFileName;
        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 suffix = OssUploadSecurityUtils.validateAndGetDotSuffix(file);
        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");
        List<DictVO> storeOrderType=dictDataService.selectDictDataListByType("store_order_type");
        List<DictVO> storeOrderMedium=dictDataService.selectDictDataListByType("store_order_medium");
        List<DictVO> orderTypeOptions=dictDataService.selectDictDataListByType("sys_inquiry_order_type");
        List<DictVO> inquiryTypeOptions=dictDataService.selectDictDataListByType("sys_inquiry_type");
        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)
                .put("storeOrderType",storeOrderType)
                .put("storeOrderMedium",storeOrderMedium)
                .put("orderTypeOptions",orderTypeOptions)
                .put("inquiryTypeOptions",inquiryTypeOptions);
    }

    @GetMapping(value = "/getStoreConfig")
    @ApiOperation("获取系统配置")
    public R getStoreConfig() {
        String config = configService.selectConfigByKey("store.config");
        StoreConfig storeConfig = JSONUtil.toBean(config, StoreConfig.class);
        //资质证书
        String certs = configUtil.generateConfigByKey(SysConfigEnum.HIS_CERTS.getKey()).getString("certs");
        storeConfig.setCerts(certs);
        //退款商家
        configUtil.generateConfigByKey(SysConfigEnum.HIS_CONFIG.getKey());
        return R.ok().put("data", storeConfig);

    }

    @GetMapping(value = "/getConfigByKey")
    @ApiOperation("获取配置")
    public R getConfigByKey(
            @RequestParam(value = "key", required = false) String key,
            @ApiParam(value = "小程序appId，用于获取自定义授权配置") @RequestParam(value = "appId", required = false) String appId) {

        String config = configService.selectConfigByKey(key);

        if ("course.config".equals(key) && appId != null && !appId.trim().isEmpty()) {
            FsCoursePlaySourceConfig playSourceConfig = fsCoursePlaySourceConfigService.selectCoursePlaySourceConfigByAppId(appId);

            if (playSourceConfig != null && playSourceConfig.getCustomAuthEnabled() != null && playSourceConfig.getCustomAuthEnabled() == 1) {
                JSONObject result;
                if (config != null && !config.trim().isEmpty()) {
                    try {
                        result = JSONObject.parseObject(config);
                    } catch (Exception e) {
                        result = new JSONObject();
                    }
                } else {
                    result = new JSONObject();
                }
                result.put("miniAppAuthType", playSourceConfig.getMiniAppAuthType());
                result.put("userCourseAuthDomain", playSourceConfig.getUserCourseAuthDomain());
                return R.ok().put("data", result.toJSONString());
            }
        }

        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("创建ERP订单")
    @GetMapping("createErpOrder")
    public R createErpOrder(@RequestParam("orderCode") String orderCode) throws Exception {
        FsStoreOrderScrm order = orderService.selectFsStoreOrderByOrderCode(orderCode);
        orderService.createOmsOrder(order.getId());
        return R.ok();
    }


    @ApiOperation("查询运单信息")
    @PostMapping("testGetExpress")
    public R testGetExpress(@RequestParam("orderId") Long orderId) throws Exception {
        FsStoreOrderScrm 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<FsStoreOrderScrm> orders = orderService.selectFsStoreOrderListByDeliveryId(dto.getLogisticCode());
                if (orders != null) {
                    for (FsStoreOrderScrm order : orders) {
                        logger.info("订单信息:" + JSONUtil.toJsonStr(order));
                        logger.info("运单号:" + dto.getLogisticCode());
                        if (order != null && order.getDeliveryStatus() != 3) {
                            FsStoreOrderScrm map = new FsStoreOrderScrm();
                            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);

    }

    //	private IErpOrderService getErpOrderService(){
//		//判断是否开启erp
//		IErpOrderService erpOrderService = null;
//		FsErpConfig erpConfig = configUtil.getErpConfig();
//		Integer erpOpen = erpConfig.getErpOpen();
//		if (erpOpen != null && erpOpen == 1) {
//			//判断erp类型
//			Integer erpType = erpConfig.getErpType();
//			if (erpType != null) {
//				if (erpType == 1) {
//					//管易
//					erpOrderService = gyOrderService;
//				} else if (erpType == 2) {
//					//旺店通
//					erpOrderService = wdtOrderService;
//				} else if (erpType == 3) {
//					//旺店通
//					erpOrderService = k9OrderService;
//				}
//			}
//		}
//		return erpOrderService;
//	}
//    private IErpOrderService getErpService() {
//        FsSysConfig sysConfig = configUtil.getSysConfig();
//        Integer erpOpen = sysConfig.getErpOpen();
//        if (erpOpen != null && erpOpen == 1) {
//            //判断erp类型
//            Integer erpType = sysConfig.getErpType();
//            if (erpType != null) {
//                IErpOrderService erpOrderService = null;
//                if (erpType == 1) {
//                    //管易
//                    erpOrderService = gyOrderService;
//                } else if (erpType == 2) {
//                    //旺店通
//                    erpOrderService = wdtOrderService;
//                } else if (erpType == 3) {
//                    //
//                    erpOrderService = hzOMSOrderService;
//                } else if (erpType == 4) {
//                    //代服
//                    erpOrderService = dfOrderService;
//                }
//                return erpOrderService;
//
//
//            }
//        }
//        return null;
//    }
//
//    private IErpGoodsService getErpGoodService() {
//        //判断是否开启erp
//        IErpGoodsService goodsService = null;
//        FsErpConfig erpConfig = configUtil.getErpConfig();
//        Integer erpOpen = erpConfig.getErpOpen();
//        if (erpOpen != null && erpOpen == 1) {
//            //判断erp类型
//            Integer erpType = erpConfig.getErpType();
//            if (erpType != null) {
//                if (erpType == 1) {
//                    //管易
//                    goodsService = gyGoodsService;
//                } else if (erpType == 2) {
//                    //旺店通
//                    goodsService = wdtErpGoodsService;
//                } else if (erpType == 3) {
//                    //旺店通
//                    goodsService = k9StockService;
//                }
//            }
//        }
//        return goodsService;
//    }


}
