package com.fs.app.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.common.annotation.RepeatSubmit;

import com.fs.common.config.FSSysConfig;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.*;
import com.fs.huifuPay.domain.HuiFuCreateOrder;
import com.fs.huifuPay.domain.HuifuCreateOrderResult;
import com.fs.huifuPay.dto.*;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.tzBank.TzBankService;
import com.fs.pay.pay.domain.CreateWxOrderResult;
import com.fs.pay.pay.dto.OrderQueryDTO;
import com.fs.pay.pay.dto.WxJspayDTO;
import com.fs.pay.pay.service.PayService;
import com.fs.store.constants.StoreConstants;
import com.fs.store.domain.*;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.tzBank.utils.TzConfigUtils;
import com.fs.wx.miniapp.config.WxMaConfiguration;
import com.fs.wx.miniapp.config.WxMaProperties;
import com.fs.wx.pay.config.WxPayProperties;
import com.fs.erp.service.IErpOrderService;
import com.fs.store.config.StoreConfig;

import com.fs.store.dto.FsStoreOrderComputeDTO;
import com.fs.store.enums.OrderInfoEnum;
import com.fs.store.mapper.FsStorePaymentMapper;
import com.fs.store.param.*;
import com.fs.store.service.*;
import com.fs.store.vo.FsMyStoreOrderListQueryVO;
import com.fs.store.vo.FsStoreOrderItemVO;
import com.fs.pay.service.IPayService;
import com.fs.system.service.ISysConfigService;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Api("商城接口")
@RestController
@RequestMapping(value="/app/storeOrder")
public class StoreOrderController extends  AppBaseController {

    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private WxMaProperties properties;

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;
    @Autowired
    private HuiFuService huiFuService;
    @Autowired
    private IFsStoreOrderItemService itemService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    private IFsPrescribeService prescribeService;
    @Autowired
    private IPayService payService;
    @Autowired
    private FSSysConfig sysConfig;
    @Autowired
    private IErpOrderService erpOrderService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IFsStoreAfterSalesService afterSalesService;
    @Autowired
    private IFsStoreProductPackageService productPackageService;
    @Autowired
    PayService ybPayService;
    @Autowired
    TzBankService tzBankService;



    @Login
    @ApiOperation("获取我的订单列表")
    @GetMapping("/getMyStoreOrderList")
        public R getMyStoreOrderList(FsMyStoreOrderQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsMyStoreOrderListQueryVO> list=orderService.selectFsMyStoreOrderListVO(param);
        PageInfo<FsMyStoreOrderListQueryVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取销售公司订单列表")
    @GetMapping("/getCompanyStoreOrderList")
    public R getCompanyStoreOrderList(FsMyStoreOrderQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<FsMyStoreOrderListQueryVO> list=orderService.selectFsCompanyStoreOrderListVO(param);
        PageInfo<FsMyStoreOrderListQueryVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }

    @Login
    @ApiOperation("获取我的订单详情")
    @GetMapping("/getMyStoreOrderById")
    public R getMyStoreOrderById(@RequestParam("orderId") Long orderId, HttpServletRequest request){
        FsStoreOrder order=orderService.selectFsStoreOrderById(orderId);
//        if(order.getUserId()-Long.parseLong(getUserId())!=0){
//            return R.error("非法操作");
//        }
        order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
        order.setUserAddress(ParseUtils.parseIdCard(order.getUserAddress()));
        List<FsStoreOrderItemVO> list=itemService.selectFsStoreOrderItemListByOrderId(orderId);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(order.getCreateTime());
        String json=configService.selectConfigByKey("store.config");
        StoreConfig config=JSONUtil.toBean(json,StoreConfig.class);
        calendar.add(Calendar.MINUTE,config.getUnPayTime());
        SimpleDateFormat format = new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String payLimitTime = format.format(calendar.getTime() );
        FsPrescribe prescribe=null;
        if(order.getPrescribeId()!=null){
            prescribe=prescribeService.selectFsPrescribeById(order.getPrescribeId());
        }
        //处理是否可以申请售后
        Integer isAfterSales=0;
        if(order.getStatus().equals(OrderInfoEnum.STATUS_3.getValue())) {
            //已完成订单 如果是私域用户就不允许售后
            if(ObjectUtil.isNotNull(order.getCompanyId())){
                isAfterSales=0;
            } else {
                isAfterSales=1;
                if (order.getFinishTime() != null) {
                    if (config.getStoreAfterSalesDay() != null && config.getStoreAfterSalesDay() > 0) {
                        //判断完成时间是否超过指定时间
                        Calendar calendarAfterSales = new GregorianCalendar();
                        calendarAfterSales.setTime(order.getFinishTime());
                        calendarAfterSales.add(calendarAfterSales.DATE, config.getStoreAfterSalesDay()); //把日期往后增加一天,整数  往后推,负数往前移动
                        if (calendarAfterSales.getTime().getTime() < new Date().getTime()) {
                            isAfterSales = 0;
                        }
                    }
                }
            }
        }
        else if(order.getStatus()==1||order.getStatus()==2){
            isAfterSales=1;
        }
        return R.ok().put("isAfterSales",isAfterSales).put("order",order).put("items",list).put("payLimitTime",payLimitTime).put("prescribe",prescribe);
    }

    @Login
    @ApiOperation("获取订单")
    @GetMapping("/getStoreOrderById")
    public R getStoreOrderById(@RequestParam("orderId") Long orderId, HttpServletRequest request){
        FsStoreOrder order=orderService.selectFsStoreOrderById(orderId);
          if(order.getUserId()-Long.parseLong(getUserId())!=0){
              return R.error("非法操作");
          }
        order.setUserPhone(ParseUtils.parsePhone(order.getUserPhone()));
        order.setUserAddress(ParseUtils.parseIdCard(order.getUserAddress()));

        String json=configService.selectConfigByKey("store.config");
        StoreConfig config=JSONUtil.toBean(json,StoreConfig.class);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(order.getCreateTime());
        calendar.add(Calendar.MINUTE,config.getUnPayTime());
        SimpleDateFormat format = new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String payLimitTime = format.format(calendar.getTime() );
        FsStoreProductPackage productPackage=null;
        if(order.getIsPackage()!=null&&order.getIsPackage()==1){
            productPackage= productPackageService.selectFsStoreProductPackageById(order.getPackageId());
        }
        return R.ok().put("order",order).put("productPackage",productPackage).put("payLimitTime",payLimitTime);
    }

    @Login
    @ApiOperation("获取订单-轮询获取信息")
    @GetMapping("/getStoreOrderByOrderIdTz")
    public R getStoreOrderByIdRemote(@RequestParam(value = "orderId",required = false) Long orderId,
                                     @RequestParam(value = "payCode",required = false) String payCode, HttpServletRequest request){
        // 根据订单查询payment
        if(ObjectUtil.isNull(orderId)&&ObjectUtil.isNull(payCode)){
            return R.error("参数错误");
        }

        List<FsStorePayment> fsStorePayments;
        if(ObjectUtil.isNotNull(orderId)){
            fsStorePayments = fsStorePaymentMapper.selectFsStorePaymentByOrder(orderId);
        } else{
            fsStorePayments = fsStorePaymentMapper.selectFsStorePaymentByPayCode(payCode);
        }
        // 如果已经有支付成功的记录
        if(CollectionUtils.isNotEmpty(fsStorePayments)){
            for (FsStorePayment fsStorePayment : fsStorePayments) {
                // 如果状态为已支付或者已经退款
                if(ObjectUtil.equal(fsStorePayment.getStatus(),1) || ObjectUtil.equal(fsStorePayment.getStatus(), -1)){
                    return R.ok().put("orderId", orderId)
                            .put("payCode", payCode)
                            .put("status", fsStorePayment.getStatus());
                }
            }
        }
        // 如果没找到，查看付款信息是否有未支付的 且 类型为tzbank 且 trade_no 不为空的数据
        // 调用台州银行接口查询订单信息
        List<FsStorePayment> fsStorePayments1;
        if(ObjectUtil.isNotNull(orderId)){
            fsStorePayments1 = fsStorePaymentMapper.selectFsStorePaymentTzUnpayByOrder(orderId);
        } else {
            fsStorePayments1 = fsStorePaymentMapper.selectFsStorePaymentTzUnpayByPayCode(payCode);
        }

        if(CollectionUtils.isNotEmpty(fsStorePayments1)){
            FsStorePayment fsStorePayment = fsStorePayments1.get(0);

            RequestDTO<QueryOrderRestDTO> requestDTO = new RequestDTO<>();

            QueryOrderRestDTO queryOrderRestDTO = new QueryOrderRestDTO();

            queryOrderRestDTO.setOrderFlowNo(fsStorePayment.getTradeNo());
            TzConfigInfoDTO tzConfigInfoDTO = TzConfigUtils.getConfig();

            queryOrderRestDTO.setPlatMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());

            requestDTO.setReqBody(queryOrderRestDTO);
            requestDTO.setReqHeader(TzReqHeaderDTO.getInstance(fsStorePayment.getPayCode()));

            TzReqResultDTO<QueryOrderInfoDTO> resultDTO = null;
            try {
                resultDTO = tzBankService.payQueryOrder(requestDTO);
                String retCode = resultDTO.getRetCode();
                // 如果查询支付成功
                if(retCode.equals("00000000")){
                    QueryOrderInfoDTO body = resultDTO.getBody();
                    String status = body.getStatus();
                    if("90".equals(status)){
                        // 如果查询支付成功 更新订单状态
                        orderService.payConfirm(1,orderId,fsStorePayment.getPayCode(),
                                fsStorePayment.getTradeNo(),body.getChlTrxId(),fsStorePayment.getTradeNo());
                        return R.ok().put("orderId", orderId)
                                .put("payCode", payCode)
                                .put("status", 1);
                    } else if("70".equals(status)) {
                        return R.ok().put("orderId", orderId)
                                .put("payCode", payCode)
                                .put("status", -1);
                    }

                }
            } catch (Exception e) {
                logger.error("台州银行支付回调查询失败:",e);
            }

        }
        FsStoreOrder order=orderService.selectFsStoreOrderById(orderId);

        if(ObjectUtil.isNotNull(order)){
            return R.ok().put("orderId",orderId)
                    .put("payCode", payCode)
                    .put("status", order.getStatus());
        } else {
            // 如果没有订单信息可能是从微信收款而来
            return R.ok().put("orderId", orderId)
                    .put("payCode", payCode)
                    .put("status", 0);
        }

    }


    @Login
    @ApiOperation("确认订单")
    @PostMapping("/confirm")
    public R confirm(@Validated @RequestBody FsStoreConfirmOrderParam param, HttpServletRequest request){
        return orderService.confirmOrder(Long.parseLong(getUserId()),param);
    }
    @Login
    @ApiOperation("计算订单金额")
    @PostMapping("/computed")
    public R computed(@Validated @RequestBody FsStoreOrderComputedParam param, HttpServletRequest request){
        FsStoreOrderComputeDTO dto=orderService.computedOrder(Long.parseLong(getUserId()),param);
        return R.ok().put("data",dto);
    }

    @Login
    @ApiOperation("创建订单")
    @PostMapping("/create")
    public R create(@Validated @RequestBody FsStoreOrderCreateParam param, HttpServletRequest request){
        return orderService.createOrder(Long.parseLong(getUserId()),param);
    }

    @Login
    @ApiOperation("支付")
    @PostMapping("/pay")
    @Transactional
    @RepeatSubmit
    //@Synchronized
    public R pay(HttpServletRequest request, @Validated @RequestBody FsStoreOrderPayParam param)
    {
        logger.info("Rt pay:"+param.getOrderId()+"的订单支付类型为"+param.getPayType());
        FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= OrderInfoEnum.STATUS_0.getValue()){
            return R.error("订单状态不正确");
        }
        //String userAddress = order.getUserAddress();
//        String noAdd="南通市,镇江市,淮安市,江阴市,金华市,驻马店市,民权县";
//        String[] split = noAdd.split(",");
//        for (String s : split) {
//            if (userAddress.contains(s)){
//                return R.error("此地区暂不支持配送");
//            }
//        }
        String orderId=redisCache.getCacheObject("isPaying:"+order.getId());
        if(StringUtils.isNotEmpty(orderId)&&orderId.equals(order.getId().toString())){
            return R.error("正在支付中...");
        }

        FsUser user=userService.selectFsUserById(order.getUserId());
        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){
            //已改价处理
            if(order.getIsEditMoney()!=null&&order.getIsEditMoney()==1){
                //改过价不做处理
            }
            else{
                String config=configService.selectConfigByKey("store.config");
                StoreConfig storeConfig= JSONUtil.toBean(config,StoreConfig.class);
                if(param.getPayType().equals(1)){
                    order.setPayType("1");
                    order.setPayMoney(order.getPayPrice());
                    order.setPayDelivery(BigDecimal.ZERO);
                }
                else if(param.getPayType().equals(2)){
                    order.setPayType("2");
                    BigDecimal payMoney=order.getPayPrice().multiply(new BigDecimal(storeConfig.getPayRate())).divide(new BigDecimal(100));
                    payMoney=new BigDecimal(payMoney.setScale(0, BigDecimal.ROUND_HALF_UP).longValue());
                    order.setPayDelivery(order.getPayPrice().subtract(payMoney));
                    order.setPayMoney(payMoney);
                }
                else if(param.getPayType().equals(3)){
                    //货到付款
                    order.setPayType("3");
                    order.setPayDelivery(order.getPayPrice() );
                    order.setPayMoney(BigDecimal.ZERO);
                }
                orderService.updateFsStoreOrder(order);
            }
            String payCode = IdUtil.getSnowflake(0, 0).nextIdStr();
//            order.setOrderCode(orderCode);

            // 台州银行支付
            if(order.getPayType().equals("1")||order.getPayType().equals("2")){
                String json = configService.selectConfigByKey("store.pay");
                FsPayConfig fsPayConfig = JSON.parseObject(json, FsPayConfig.class);
                FsStorePayment storePayment=new FsStorePayment();
                storePayment.setCompanyId(order.getCompanyId());
                storePayment.setCompanyUserId(order.getCompanyUserId());
                storePayment.setPayMode(fsPayConfig.getType());
                storePayment.setStatus(0);
                storePayment.setPayCode(payCode);
                storePayment.setPayMoney(order.getPayMoney());
                storePayment.setCreateTime(new Date());
                storePayment.setPayTypeCode("weixin");
                storePayment.setBusinessType(2);
                storePayment.setRemark("商城订单支付");
                storePayment.setOpenId(user.getRealName());
                storePayment.setUserId(user.getUserId());
                storePayment.setBusinessOrderId(order.getId().toString());
                storePayment.setOrderId(order.getId());
                fsStorePaymentMapper.insertFsStorePayment(storePayment);
                if (fsPayConfig.getType().equals("hf")){
                    HuiFuCreateOrder o = new HuiFuCreateOrder();
                    o.setTradeType("T_MINIAPP");
                    o.setOpenid(user.getMaOpenId());
                    o.setReqSeqId("store-"+storePayment.getPayCode());
                    o.setTransAmt(storePayment.getPayMoney().toString());
                    o.setGoodsDesc("商城订单支付");
                    HuifuCreateOrderResult result = huiFuService.createOrder(o);
                    //创建订单
                    if(result.getResp_code()!=null&&(result.getResp_code().equals("00000000")||result.getResp_code().equals("00000100"))){
                        FsStorePayment mt=new FsStorePayment();
                        mt.setPaymentId(storePayment.getPaymentId());
                        mt.setTradeNo(result.getHf_seq_id());
                        fsStorePaymentMapper.updateFsStorePayment(mt);
                        redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                        return R.ok().put("payType",param.getPayType()).put("result",result.getPay_info());
                    }
                    else{
                        return R.error(result.getResp_desc());
                    }
                } else if(fsPayConfig.getType().equals("tzbk")){
                    TzConfigInfoDTO tzConfigInfoDTO = JSON.parseObject(json, TzConfigInfoDTO.class);

                    TzPayCreateOrderReqBodyDTO reqBodyDTO = new TzPayCreateOrderReqBodyDTO();
                    RequestDTO<TzPayCreateOrderReqBodyDTO> requestDTO = new RequestDTO<>();
                    reqBodyDTO.setOrderNo(payCode);
                    reqBodyDTO.setOrderSource("02");
                    reqBodyDTO.setTrxAmt(storePayment.getPayMoney());
                    reqBodyDTO.setCurrency("CNY");
                    reqBodyDTO.setTransType("2001");
                    reqBodyDTO.setTradeMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());
                    reqBodyDTO.setPlatMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());
                    reqBodyDTO.setBusinessCstNo(user.getUserId().toString());
                    reqBodyDTO.setPayNotifyUrl(tzConfigInfoDTO.getPayNotifyUrl());
                    reqBodyDTO.setPayerName(user.getUsername());
                    reqBodyDTO.setPayerMobileNo(user.getPhone());
                    reqBodyDTO.setGoodsInfo("商城订单支付");
                    // 不需要分账
                    reqBodyDTO.setNeedLedger("00");
                    reqBodyDTO.setClientIp(IPUtils.getIpAddr(ServletUtils.getRequest()));
                    // 获取订单到期时间
                    String redisKey = String.valueOf(StrUtil.format("{}{}",
                            StoreConstants.REDIS_ORDER_OUTTIME_UNPAY, order.getId()));
                    Long expire = redisCache.getExpire(redisKey);
                    Long currentTimeMillis = System.currentTimeMillis();

                    reqBodyDTO.setExpiredTime(String.valueOf(currentTimeMillis+expire));



                    requestDTO.setReqHeader(TzReqHeaderDTO.getInstance(payCode));
                    requestDTO.setReqBody(reqBodyDTO);
                    try {
                        // 创建订单
                        TzReqResultDTO<TzPayCreateOrderRspDTO> payCreateOrder = tzBankService.payCreateOrder(requestDTO);
                        // 获得小程序请求码
                        if("00000000".equals(payCreateOrder.getRetCode())){
                            TzPayCreateOrderRspDTO body = payCreateOrder.getBody();

                            RequestDTO<TzMiniProgramCodeReqDTO> reqDTORequestDTO = new RequestDTO<>();
                            TzMiniProgramCodeReqDTO tzMiniProgramCodeReqDTO = new TzMiniProgramCodeReqDTO();
                            tzMiniProgramCodeReqDTO.setOrderNo(body.getOrderFlowNo());
                            tzMiniProgramCodeReqDTO.setPlatMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());
                            tzMiniProgramCodeReqDTO.setBusinessCstNo(user.getUserId().toString());
                            reqDTORequestDTO.setReqHeader(TzReqHeaderDTO.getInstance(payCode));
                            reqDTORequestDTO.setReqBody(tzMiniProgramCodeReqDTO);
                            TzReqResultDTO<TzMiniProgramCodeRespDTO> miniProgramCode = tzBankService.miniProgramCode(reqDTORequestDTO);
                            if("00000000".equals(miniProgramCode.getRetCode())){
                                FsStorePayment mt=new FsStorePayment();
                                mt.setPaymentId(storePayment.getPaymentId());
                                mt.setTradeNo(miniProgramCode.getBody().getOrderNo());
                                fsStorePaymentMapper.updateFsStorePayment(mt);
                                redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                                TzMiniProgramCodeRespDTO result = miniProgramCode.getBody();
                                result.setPayCode(payCode);
                                return R.ok().put("payType",param.getPayType()).put("result",result);
                            } else {
                                return R.error(miniProgramCode.getRetMsg());
                            }
                        }
                    } catch (Exception e) {
                        logger.error("系统异常",e);
                        return R.error("系统异常，请联系管理员!");
                    }
                } else if (fsPayConfig.getType().equals("yb")){
                    WxJspayDTO p = new WxJspayDTO();
                    p.setPayMoney(order.getPayMoney().toString());
                    p.setLowOrderId("store-"+payCode);
                    p.setBody("商城订单支付");
                    p.setIsMinipg("1");
                    p.setReturnUrl(fsPayConfig.getYbNotifyUrl());
                    p.setOpenId(user.getMaOpenId());
                    p.setAttach("");
                    p.setStoreid("0");
                    CreateWxOrderResult wxOrder = ybPayService.createWxOrder(p);
                if(wxOrder.getStatus().equals("100")){
                    FsStorePayment ment=new FsStorePayment();
                    ment.setPaymentId(storePayment.getPaymentId());
                    ment.setTradeNo(wxOrder.getUpOrderId());
                    fsStorePaymentMapper.updateFsStorePayment(ment);
                    redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                    return R.ok().put("payType",param.getPayType()).put("result",wxOrder.getPay_info());
                }
                else{
                    return R.error(wxOrder.getMessage());
                }
                }
            }
            //易宝支付
//            if(order.getPayType().equals("1")||order.getPayType().equals("2")){
//                FsStorePayment storePayment=new FsStorePayment();
//                storePayment.setCompanyId(order.getCompanyId());
//                storePayment.setCompanyUserId(order.getCompanyUserId());
//                storePayment.setStatus(0);
//                storePayment.setPayCode(payCode);
//                storePayment.setPayMoney(order.getPayMoney());
//                storePayment.setCreateTime(new Date());
//                storePayment.setPayTypeCode("weixin");
//                storePayment.setBusinessType(2);
//                storePayment.setRemark("商城订单支付");
//                storePayment.setOpenId(user.getRealName());
//                storePayment.setUserId(user.getUserId());
//                storePayment.setBusinessOrderId(order.getId().toString());
//                storePayment.setOrderId(order.getId());
//                fsStorePaymentMapper.insertFsStorePayment(storePayment);
//
//                //创建订单
//
//            }
            else if(order.getPayType().equals("3")){
                //货到付款
                orderService.payConfirm(2,order.getId(),null,null,null,null);
                return R.ok().put("payType",param.getPayType());
            }

            //小雨点支付
//            if(sysConfig.getPayOpen()==1){
//                if(order.getPayType().equals("1")||order.getPayType().equals("2")){
//
//                    FsStorePayment storePayment=new FsStorePayment();
//                    storePayment.setCompanyId(order.getCompanyId());
//                    storePayment.setCompanyUserId(order.getCompanyUserId());
//                    storePayment.setStatus(0);
//                    storePayment.setPayCode(payCode);
//                    storePayment.setPayMoney(order.getPayMoney());
//                    storePayment.setCreateTime(new Date());
//                    storePayment.setPayTypeCode("weixin");
//                    storePayment.setBusinessType(2);
//                    storePayment.setRemark("商城订单支付");
//                    storePayment.setOpenId(user.getRealName());
//                    storePayment.setUserId(user.getUserId());
//                    storePayment.setBusinessOrderId(order.getId().toString());
//                    storePayment.setOrderId(order.getId());
//                    fsStorePaymentMapper.insertFsStorePayment(storePayment);
//
//                    //创建订单
//                    CreatePayDTO createPayDTO=new CreatePayDTO();
//                    createPayDTO.setMerchOrderNo(payCode);
//                    List<TradeOrder> orders=new ArrayList<>();
//                    TradeOrder tradeOrder=new TradeOrder();
//                    tradeOrder.setAmount(order.getPayMoney().toString());
//                    tradeOrder.setSubMerchOrderNo("store-"+payCode);
//                    tradeOrder.setTradeName("商品订单支付");
//                    tradeOrder.setPayeeOutUserId(sysConfig.getPayPartnerId());
//                    orders.add(tradeOrder);
//                    createPayDTO.setOrders(orders);
//                    payService.createOrder(createPayDTO);
//                    //支付订单
//                    PayDTO payDTO=new PayDTO();
//                    payDTO.setOrigMerchOrderNo(payCode);
//                    payDTO.setOpenID(user.getMaOpenId());
//                    payDTO.setAppID(wxPayProperties.getAppId());
//                    payDTO.setPayerOutUserId(user.getUserId().toString());
//                    payDTO.setPayerOutUserName(user.getNickname());
//                    payDTO.setUserIp(IPUtils.getIpAddr(request));
//                    return R.ok().put("payType",param.getPayType()).put("result",payService.payOrder(payDTO));
//                }
//                else if(order.getPayType().equals("3")){
//                    //货到付款
//                    orderService.payConfirm(2,order.getId(),null,null,null,null);
//                    return R.ok().put("payType",param.getPayType());
//                }
//            }
//            else{
//
//                //创建微信订单
//                WxPayConfig payConfig = new WxPayConfig();
//                payConfig.setAppId(wxPayProperties.getAppId());
//                payConfig.setMchId(wxPayProperties.getMchId());
//                payConfig.setMchKey(wxPayProperties.getMchKey());
//                payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
//                payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
//                payConfig.setKeyPath(null);
//                payConfig.setNotifyUrl(wxPayProperties.getNotifyUrl());
//                wxPayService.setConfig(payConfig);
//                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
//                orderRequest.setOpenid(user.getMaOpenId());//公众号支付提供用户openid
//                orderRequest.setBody("商城订单支付");
//                orderRequest.setOutTradeNo("store-"+order.getOrderCode());
//                orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(order.getPayMoney().toString()));//测试
//                //orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(money));//测试
//                orderRequest.setTradeType("JSAPI");
//                orderRequest.setSpbillCreateIp(IPUtils.getIpAddr(request));
//                //调用统一下单接口，获取"预支付交易会话标识"
//                try {
//                    WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);
//                    return R.ok().put("result",orderResult);
//                } catch (WxPayException e) {
//                    e.printStackTrace();
//                    return R.error("下单失败"+e.getMessage());
//                }
//            }
            return R.error();
        }
        else{
            return R.error("用户OPENID不存在");
        }

    }





    @Login
    @ApiOperation("修改支付类型")
    @PostMapping("/editPayType")
    @Transactional
    public R editPayType(HttpServletRequest request, @Validated @RequestBody FsStoreOrderPayParam param) {
        FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= OrderInfoEnum.STATUS_0.getValue()){
            return R.error("订单状态不正确");
        }
//        String userAddress = order.getUserAddress();
//        String noAdd="南通市,镇江市,淮安市,江阴市,金华市,驻马店市,民权县";
//        String[] split = noAdd.split(",");
//        for (String s : split) {
//            if (userAddress.contains(s)){
//                return R.error("此地区暂不支持配送");
//            }
//        }

        String orderId=redisCache.getCacheObject("isPaying:"+order.getId());
        if(StringUtils.isNotEmpty(orderId)&&orderId.equals(order.getId().toString())){
            return R.error("正在支付中...");
        }
        List<FsStorePayment>  payments=fsStorePaymentMapper.selectFsStorePaymentByOrder(order.getId());
        if(payments.size()>0){
            for(FsStorePayment payment : payments){
                if(StringUtils.isEmpty(payment.getTradeNo())){
                    continue;
                }
                OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
                orderQueryDTO.setLowOrderId("store-"+payment.getPayCode());
                RequestDTO<QueryOrderRestDTO> requestDTO = new RequestDTO<>();

                QueryOrderRestDTO queryOrderRestDTO = new QueryOrderRestDTO();

                queryOrderRestDTO.setOrderFlowNo(payment.getTradeNo());
                TzConfigInfoDTO tzConfigInfoDTO = TzConfigUtils.getConfig();

                queryOrderRestDTO.setPlatMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());

                requestDTO.setReqBody(queryOrderRestDTO);
                requestDTO.setReqHeader(TzReqHeaderDTO.getInstance(payment.getPayCode()));
                try {
                    TzReqResultDTO<QueryOrderInfoDTO> resultDTO = tzBankService.payQueryOrder(requestDTO);
                    if(ObjectUtil.isNotNull(resultDTO)){
                        QueryOrderInfoDTO body = resultDTO.getBody();
                        if(ObjectUtil.isNotNull(body)){
                            if("80".equals(body.getStatus()) || "90".equals(body.getStatus())){
                                // 更新订单状态和支付状态
                                payment.setStatus(1);
                                fsStorePaymentMapper.updateFsStorePayment(payment);
                                orderService.payConfirm(1, order.getId(), payment.getPayCode(),
                                        payment.getTradeNo(),
                                        body.getChlTrxId(),
                                        payment.getTradeNo());
                                return R.error("订单已支付");
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        FsUser user=userService.selectFsUserById(order.getUserId());
        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){
            //已改价处理
            if(order.getIsEditMoney()!=null&&order.getIsEditMoney()==1){
                //改过价不做处理
            }
            else{
                String config=configService.selectConfigByKey("store.config");
                StoreConfig storeConfig= JSONUtil.toBean(config,StoreConfig.class);
                if(param.getPayType().equals(1)){
                    order.setPayType("1");
                    order.setPayMoney(order.getPayPrice());
                    order.setPayDelivery(BigDecimal.ZERO);
                }
                else if(param.getPayType().equals(2)){

                    order.setPayType("2");
                    BigDecimal payMoney=order.getPayPrice().multiply(new BigDecimal(storeConfig.getPayRate())).divide(new BigDecimal(100));
                    payMoney=new BigDecimal(payMoney.setScale(0, BigDecimal.ROUND_HALF_UP).longValue());
                    order.setPayDelivery(order.getPayPrice().subtract(payMoney));
                    order.setPayMoney(payMoney);
                }
                else if(param.getPayType().equals(3)){
                    //货到付款
                    order.setPayType("3");
                    order.setPayDelivery(order.getPayPrice() );
                    order.setPayMoney(BigDecimal.ZERO);
                }
                orderService.updateFsStoreOrder(order);
            }
            return R.ok().put("order",order);
        }
        else{
            return R.error("用户OPENID不存在");
        }

    }


    @Login
    @ApiOperation("支付尾款")
    @PostMapping("/payRemain")
    @Transactional
    public R payRemain(HttpServletRequest request, @Validated @RequestBody FsStoreOrderPayParam param) {
        FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= OrderInfoEnum.STATUS_2.getValue()){
            return R.error("待收货订单可申请支付尾款");
        }
        if(order.getPayType().equals(1)){
            return R.error("此订单已支付");
        }
        //只有顺风才可以付尾
        if(!order.getDeliverySn().trim().equals("SF")){
            return R.error("只有顺丰物流支持尾款支付");
        }

        if(!order.getIsPayRemain().equals(0)){
            return R.error("此订单已支付");
        }
        FsUser user=userService.selectFsUserById(order.getUserId());
        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){
            String payCode = IdUtil.getSnowflake(0, 0).nextIdStr();
            String json = configService.selectConfigByKey("store.pay");
            FsPayConfig fsPayConfig = JSON.parseObject(json, FsPayConfig.class);

            FsStorePayment storePayment=new FsStorePayment();
            storePayment.setCompanyId(order.getCompanyId());
            storePayment.setCompanyUserId(order.getCompanyUserId());
            storePayment.setStatus(0);
            storePayment.setPayMode(fsPayConfig.getType());
            storePayment.setPayCode(payCode);
            storePayment.setPayMoney(order.getPayDelivery());
            storePayment.setCreateTime(new Date());
            storePayment.setPayTypeCode("weixin");
            storePayment.setBusinessType(2);
            storePayment.setRemark("商城订单尾款支付");
            storePayment.setOpenId(user.getRealName());
            storePayment.setUserId(user.getUserId());
            storePayment.setBusinessOrderId(order.getId().toString());
            storePayment.setOrderId(order.getId());
            storePayment.setIsPayRemain(1);
            fsStorePaymentMapper.insertFsStorePayment(storePayment);
            if (fsPayConfig.getType().equals("hf")){
                HuiFuCreateOrder o = new HuiFuCreateOrder();
                o.setTradeType("T_MINIAPP");
                o.setOpenid(user.getMaOpenId());
                o.setReqSeqId("store_remain-"+storePayment.getPayCode());
                o.setTransAmt(storePayment.getPayMoney().toString());
                o.setGoodsDesc("商城订单尾款支付");
                HuifuCreateOrderResult result = huiFuService.createOrder(o);
                //创建订单
                if(result.getResp_code()!=null&&(result.getResp_code().equals("00000000")||result.getResp_code().equals("00000100"))){
                    FsStorePayment mt=new FsStorePayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getHf_seq_id());
                    fsStorePaymentMapper.updateFsStorePayment(mt);
                    redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                    return R.ok().put("result",result.getPay_info());
                }
                else{
                    return R.error(result.getResp_desc());
                }
            }else if(fsPayConfig.getType().equals("yb")){
                WxJspayDTO p = new WxJspayDTO();
            // 使用setter方法为对象赋值
                p.setPayMoney(order.getPayDelivery().toString());
                p.setLowOrderId("store_remain-"+payCode);
                p.setBody("商城订单尾款支付");
                p.setIsMinipg("1");
                p.setReturnUrl(fsPayConfig.getYbNotifyUrl());
                p.setOpenId(user.getMaOpenId());
                p.setAttach("");
                p.setStoreid("0");
                CreateWxOrderResult wxOrder = ybPayService.createWxOrder(p);
                if(wxOrder.getStatus().equals("100")){
                    FsStorePayment ment=new FsStorePayment();
                    ment.setPaymentId(storePayment.getPaymentId());
                    ment.setTradeNo(wxOrder.getUpOrderId());
                    fsStorePaymentMapper.updateFsStorePayment(ment);
                    return R.ok().put("result",wxOrder.getPay_info());
                }
            else{
                return R.error(wxOrder.getMessage());
            }
            }

//
//            //创建订单
//
            //小雨点支付
//            if(sysConfig.getPayOpen()==1){
//                FsStorePayment storePayment=new FsStorePayment();
//                storePayment.setCompanyId(order.getCompanyId());
//                storePayment.setCompanyUserId(order.getCompanyUserId());
//                storePayment.setStatus(0);
//                storePayment.setPayCode(payCode);
//                storePayment.setPayMoney(order.getPayDelivery());
//                storePayment.setCreateTime(new Date());
//                storePayment.setPayTypeCode("weixin");
//                storePayment.setBusinessType(2);
//                storePayment.setRemark("商城订单尾款支付");
//                storePayment.setOpenId(user.getRealName());
//                storePayment.setUserId(user.getUserId());
//                storePayment.setBusinessOrderId(order.getId().toString());
//                storePayment.setOrderId(order.getId());
//                storePayment.setIsPayRemain(1);
//                fsStorePaymentMapper.insertFsStorePayment(storePayment);
//                //创建订单
//                CreatePayDTO createPayDTO=new CreatePayDTO();
//                createPayDTO.setMerchOrderNo(payCode);
//                List<TradeOrder> orders=new ArrayList<>();
//                TradeOrder tradeOrder=new TradeOrder();
//                tradeOrder.setAmount(order.getPayDelivery().toString());
//                tradeOrder.setSubMerchOrderNo("store_remain-"+payCode);
//                tradeOrder.setTradeName("支付订单尾款");
//                tradeOrder.setPayeeOutUserId(sysConfig.getPayPartnerId());
//                orders.add(tradeOrder);
//                createPayDTO.setOrders(orders);
//                payService.createOrder(createPayDTO);
//                //支付订单
//                PayDTO payDTO=new PayDTO();
//                payDTO.setOrigMerchOrderNo(payCode);
//                payDTO.setOpenID(user.getMaOpenId());
//                payDTO.setAppID(wxPayProperties.getAppId());
//                payDTO.setPayerOutUserId(user.getUserId().toString());
//                payDTO.setPayerOutUserName(user.getNickname());
//                payDTO.setUserIp(IPUtils.getIpAddr(request));
//                return R.ok().put("result",payService.payOrder(payDTO));
//            }
//            else{
////                //创建微信订单
////                WxPayConfig payConfig = new WxPayConfig();
////                payConfig.setAppId(wxPayProperties.getAppId());
////                payConfig.setMchId(wxPayProperties.getMchId());
////                payConfig.setMchKey(wxPayProperties.getMchKey());
////                payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
////                payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
////                payConfig.setKeyPath(null);
////                payConfig.setNotifyUrl(wxPayProperties.getNotifyUrl());
////                wxPayService.setConfig(payConfig);
////                WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
////                orderRequest.setOpenid(user.getMaOpenId());//公众号支付提供用户openid
////                orderRequest.setBody("商城订单支付");
////                orderRequest.setOutTradeNo("store-"+order.getOrderCode());
////                orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(order.getPayMoney().toString()));//测试
////                //orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(money));//测试
////                orderRequest.setTradeType("JSAPI");
////                orderRequest.setSpbillCreateIp(IPUtils.getIpAddr(request));
////                //调用统一下单接口，获取"预支付交易会话标识"
////                try {
////                    WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);
////                    return R.ok().put("result",orderResult);
////                } catch (WxPayException e) {
////                    e.printStackTrace();
////                    return R.error("下单失败"+e.getMessage());
////                }
//            }
//            return R.error();
        }
        else{
            return R.error("用户OPENID不存在");
        }
        return R.error("无支付类型");
    }


    @Login
    @ApiOperation("亲友支付")
    @PostMapping("/otherPayment")
    @Transactional
    public R otherPayment(@Validated @RequestBody FsStoreOrderOtherPayParam param, HttpServletRequest request){
        final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
        try {
            String ip = IpUtil.getRequestIp();
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(param.getCode());
            FsUser user=userService.selectFsUserByMaOpenId(session.getOpenid());
            if(user==null){
                //创建
                user=new FsUser();
                user.setUsername("");
                user.setNickname("微信用户");
                user.setStatus(1);
                user.setMaOpenId(session.getOpenid());
                user.setUnionId(session.getUnionid());
                user.setIsWeixinAuth(0);
                user.setLastIp(ip);
                user.setCreateTime(new Date());
                userService.insertFsUser(user);
            }
            FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
            if(order==null){
                return R.error("订单不存在");
            }
            if(order.getStatus()!= OrderInfoEnum.STATUS_0.getValue()){
                return R.error("此订单不能支付");
            }
            if(order.getPayMoney().compareTo(new BigDecimal(0))<1){
                return R.error("此订单没有可支付的金额");
            }

            String orderId=redisCache.getCacheObject("isPaying:"+order.getId());
            if(StringUtils.isNotEmpty(orderId)&&orderId.equals(order.getId().toString())){
                return R.error("正在支付中...");
            }


            String payCode = IdUtil.getSnowflake(0, 0).nextIdStr();
            String json = configService.selectConfigByKey("store.pay");
            FsPayConfig fsPayConfig = JSON.parseObject(json, FsPayConfig.class);
            FsStorePayment storePayment=new FsStorePayment();
            storePayment.setCompanyId(order.getCompanyId());
            storePayment.setCompanyUserId(order.getCompanyUserId());
            storePayment.setStatus(0);
            storePayment.setPayMode(fsPayConfig.getType());
            storePayment.setPayCode(payCode);
            storePayment.setPayMoney(order.getPayMoney());
            storePayment.setCreateTime(new Date());
            storePayment.setPayTypeCode("weixin");
            storePayment.setBusinessType(2);
            storePayment.setRemark("商城订单支付");
            storePayment.setOpenId(session.getOpenid());
            storePayment.setUserId(user.getUserId());
            storePayment.setBusinessOrderId(order.getId().toString());
            storePayment.setOrderId(order.getId());
            fsStorePaymentMapper.insertFsStorePayment(storePayment);
            if (fsPayConfig.getType().equals("hf")){
                HuiFuCreateOrder o = new HuiFuCreateOrder();
                o.setTradeType("T_MINIAPP");
                o.setOpenid(user.getMaOpenId());
                o.setReqSeqId("store-"+storePayment.getPayCode());
                o.setTransAmt(storePayment.getPayMoney().toString());
                o.setGoodsDesc("商城订单支付");
                HuifuCreateOrderResult result = huiFuService.createOrder(o);
                if(result.getResp_code()!=null&&(result.getResp_code().equals("00000000")||result.getResp_code().equals("00000100"))){
                    FsStorePayment mt=new FsStorePayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getHf_seq_id());
                    fsStorePaymentMapper.updateFsStorePayment(mt);
                    redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                    return R.ok().put("result",result.getPay_info());
                }
                else{
                    return R.error(result.getResp_desc());
                }
            }else  if (fsPayConfig.getType().equals("yb")){
                WxJspayDTO p = new WxJspayDTO();
                // 使用setter方法为对象赋值
                p.setPayMoney(order.getPayMoney().toString());
                p.setLowOrderId("store-"+payCode);
                p.setBody("商城订单支付");
                p.setIsMinipg("1");
                p.setReturnUrl(fsPayConfig.getYbNotifyUrl());
                p.setOpenId(user.getMaOpenId());
                p.setAttach("");
                p.setStoreid("0");
                CreateWxOrderResult wxOrder = ybPayService.createWxOrder(p);
                if(wxOrder.getStatus().equals("100")){
                    FsStorePayment ment=new FsStorePayment();
                    ment.setPaymentId(storePayment.getPaymentId());
                    ment.setTradeNo(wxOrder.getUpOrderId());
                    fsStorePaymentMapper.updateFsStorePayment(ment);
                    redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                    return R.ok().put("result",wxOrder.getPay_info());
                }
                else{
                    return R.error(wxOrder.getMessage());
                }
            } else if(fsPayConfig.getType().equals("tzbk")){
                TzConfigInfoDTO tzConfigInfoDTO = JSON.parseObject(json, TzConfigInfoDTO.class);

                TzPayCreateOrderReqBodyDTO reqBodyDTO = new TzPayCreateOrderReqBodyDTO();
                RequestDTO<TzPayCreateOrderReqBodyDTO> requestDTO = new RequestDTO<>();
                reqBodyDTO.setOrderNo(storePayment.getPayCode());
                reqBodyDTO.setOrderSource("02");
                reqBodyDTO.setTrxAmt(storePayment.getPayMoney());
                reqBodyDTO.setCurrency("CNY");
                reqBodyDTO.setTransType("2001");
                reqBodyDTO.setTradeMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());
                reqBodyDTO.setPlatMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());
                reqBodyDTO.setBusinessCstNo(user.getUserId().toString());
                reqBodyDTO.setPayNotifyUrl(tzConfigInfoDTO.getPayNotifyUrl());
                reqBodyDTO.setPayerName(user.getUsername());
                reqBodyDTO.setPayerMobileNo(user.getPhone());
                reqBodyDTO.setGoodsInfo("商城订单支付");
                // 不需要分账
                reqBodyDTO.setNeedLedger("00");
                reqBodyDTO.setClientIp(IPUtils.getIpAddr(ServletUtils.getRequest()));
                // 获取订单到期时间
                String redisKey = String.valueOf(StrUtil.format("{}{}",
                        StoreConstants.REDIS_ORDER_OUTTIME_UNPAY, order.getId()));
                Long expire = redisCache.getExpire(redisKey);
                Long currentTimeMillis = System.currentTimeMillis();

                reqBodyDTO.setExpiredTime(String.valueOf(currentTimeMillis+expire));



                requestDTO.setReqHeader(TzReqHeaderDTO.getInstance(payCode));
                requestDTO.setReqBody(reqBodyDTO);
                try {
                    // 创建订单
                    TzReqResultDTO<TzPayCreateOrderRspDTO> payCreateOrder = tzBankService.payCreateOrder(requestDTO);
                    // 获得小程序请求码
                    if("00000000".equals(payCreateOrder.getRetCode())){
                        TzPayCreateOrderRspDTO body = payCreateOrder.getBody();

                        RequestDTO<TzMiniProgramCodeReqDTO> reqDTORequestDTO = new RequestDTO<>();
                        TzMiniProgramCodeReqDTO tzMiniProgramCodeReqDTO = new TzMiniProgramCodeReqDTO();
                        tzMiniProgramCodeReqDTO.setOrderNo(body.getOrderFlowNo());
                        tzMiniProgramCodeReqDTO.setPlatMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());
                        tzMiniProgramCodeReqDTO.setBusinessCstNo(user.getUserId().toString());
                        reqDTORequestDTO.setReqHeader(TzReqHeaderDTO.getInstance(payCode));
                        reqDTORequestDTO.setReqBody(tzMiniProgramCodeReqDTO);
                        TzReqResultDTO<TzMiniProgramCodeRespDTO> miniProgramCode = tzBankService.miniProgramCode(reqDTORequestDTO);
                        if("00000000".equals(miniProgramCode.getRetCode())){
                            FsStorePayment mt=new FsStorePayment();
                            mt.setPaymentId(storePayment.getPaymentId());
                            mt.setTradeNo(miniProgramCode.getBody().getOrderNo());
                            fsStorePaymentMapper.updateFsStorePayment(mt);
                            redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                            return R.ok().put("result",miniProgramCode.getBody());
                        } else {
                            return R.error(miniProgramCode.getRetMsg());
                        }
                    }
                } catch (Exception e) {
                    logger.error("系统异常",e);
                    return R.error("系统异常，请联系管理员!");
                }
            }


            //小雨点支付
//            if(sysConfig.getPayOpen()==1){
//                FsStorePayment storePayment=new FsStorePayment();
//                storePayment.setCompanyId(order.getCompanyId());
//                storePayment.setCompanyUserId(order.getCompanyUserId());
//                storePayment.setStatus(0);
//                storePayment.setPayCode(payCode);
//                storePayment.setPayMoney(order.getPayMoney());
//                storePayment.setCreateTime(new Date());
//                storePayment.setPayTypeCode("weixin");
//                storePayment.setBusinessType(2);
//                storePayment.setRemark("商城订单支付");
//                storePayment.setOpenId(session.getOpenid());
//                storePayment.setUserId(user.getUserId());
//                storePayment.setBusinessOrderId(order.getId().toString());
//                storePayment.setOrderId(order.getId());
//                fsStorePaymentMapper.insertFsStorePayment(storePayment);
//
//                //创建订单
//                CreatePayDTO createPayDTO=new CreatePayDTO();
//                createPayDTO.setMerchOrderNo(payCode);
//                List<TradeOrder> orders=new ArrayList<>();
//                TradeOrder tradeOrder=new TradeOrder();
//                tradeOrder.setAmount(order.getPayMoney().toString());
//                tradeOrder.setSubMerchOrderNo("store-"+payCode);
//                tradeOrder.setTradeName("商品订单支付");
//                tradeOrder.setPayeeOutUserId(sysConfig.getPayPartnerId());
//                orders.add(tradeOrder);
//                createPayDTO.setOrders(orders);
//                payService.createOrder(createPayDTO);
//                //支付订单
//                PayDTO payDTO=new PayDTO();
//                payDTO.setOrigMerchOrderNo(payCode);
//                payDTO.setOpenID(user.getMaOpenId());
//                payDTO.setAppID(wxPayProperties.getAppId());
//                payDTO.setPayerOutUserId(user.getUserId().toString());
//                payDTO.setPayerOutUserName(user.getNickname());
//                payDTO.setUserIp(IPUtils.getIpAddr(request));
//                return R.ok().put("result",payService.payOrder(payDTO));
//            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
        return R.error("无支付类型");
    }

    @Login
    @ApiOperation("亲友支付")
    @PostMapping("/otherPaymentRemain")
    @Transactional
    public R otherPaymentRemain(@Validated @RequestBody FsStoreOrderOtherPayParam param, HttpServletRequest request){
        final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
        try {
            String ip = IpUtil.getRequestIp();
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(param.getCode());
            FsUser user=userService.selectFsUserByMaOpenId(session.getOpenid());
            if(user==null){
                //创建
                user=new FsUser();
                user.setUsername("");
                user.setNickname("微信用户");
                user.setStatus(1);
                user.setMaOpenId(session.getOpenid());
                user.setUnionId(session.getUnionid());
                user.setIsWeixinAuth(0);
                user.setLastIp(ip);
                user.setCreateTime(new Date());
                userService.insertFsUser(user);
            }
            FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
            if(order==null){
                return R.error("订单不存在");
            }
            if(order.getStatus()!= OrderInfoEnum.STATUS_2.getValue()){
                return R.error("待收货订单可申请支付尾款");
            }
            if(order.getPayType().equals(1)){
                return R.error("此订单已支付");
            }
            //只有顺风才可以付尾
            if(!order.getDeliverySn().trim().equals("SF")){
                return R.error("只有顺丰物流支持尾款支付");
            }

            if(!order.getIsPayRemain().equals(0)){
                return R.error("此订单已支付");
            }
            String payCode = IdUtil.getSnowflake(0, 0).nextIdStr();
            //易宝支付
            String json = configService.selectConfigByKey("store.pay");
            FsPayConfig fsPayConfig = JSON.parseObject(json, FsPayConfig.class);
            FsStorePayment storePayment=new FsStorePayment();
            storePayment.setCompanyId(order.getCompanyId());
            storePayment.setCompanyUserId(order.getCompanyUserId());
            storePayment.setStatus(0);
            storePayment.setPayCode(payCode);
            storePayment.setPayMoney(order.getPayDelivery());
            storePayment.setCreateTime(new Date());
            storePayment.setPayTypeCode("weixin");
            storePayment.setBusinessType(2);
            storePayment.setRemark("商城订单尾款支付");
            storePayment.setOpenId(user.getRealName());
            storePayment.setUserId(user.getUserId());
            storePayment.setBusinessOrderId(order.getId().toString());
            storePayment.setOrderId(order.getId());
            storePayment.setIsPayRemain(1);
            storePayment.setPayMode(fsPayConfig.getType());
            fsStorePaymentMapper.insertFsStorePayment(storePayment);
            if (fsPayConfig.getType().equals("hf")){
                HuiFuCreateOrder o = new HuiFuCreateOrder();
                o.setTradeType("T_MINIAPP");
                o.setOpenid(user.getMaOpenId());
                o.setReqSeqId("store_remain-"+storePayment.getPayCode());
                o.setTransAmt(storePayment.getPayMoney().toString());
                o.setGoodsDesc("支付订单尾款");
                HuifuCreateOrderResult result = huiFuService.createOrder(o);
                if(result.getResp_code()!=null&&(result.getResp_code().equals("00000000")||result.getResp_code().equals("00000100"))){
                    FsStorePayment mt=new FsStorePayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getHf_seq_id());
                    fsStorePaymentMapper.updateFsStorePayment(mt);
                    redisCache.setCacheObject("isPaying:"+order.getId(),order.getId().toString(),1, TimeUnit.MINUTES);
                    return R.ok().put("result",result.getPay_info());
                }else{
                    return R.error(result.getResp_desc());
                }
            }else if (fsPayConfig.getType().equals("yb")){
                WxJspayDTO p = new WxJspayDTO();
                // 使用setter方法为对象赋值
                p.setPayMoney(order.getPayDelivery().toString());
                p.setLowOrderId("store_remain-"+payCode);
                p.setBody("支付订单尾款");
                p.setIsMinipg("1");
                p.setReturnUrl(fsPayConfig.getYbNotifyUrl());
                p.setOpenId(user.getMaOpenId());
                p.setAttach("");
                p.setStoreid("0");
                CreateWxOrderResult wxOrder = ybPayService.createWxOrder(p);
                if(wxOrder.getStatus().equals("100")){
                    FsStorePayment ment=new FsStorePayment();
                    ment.setPaymentId(storePayment.getPaymentId());
                    ment.setTradeNo(wxOrder.getUpOrderId());
                    fsStorePaymentMapper.updateFsStorePayment(ment);
                    return R.ok().put("result",wxOrder.getPay_info());
                }
                else{
                    return R.error(wxOrder.getMessage());
                }
            }

            //小雨点支付
//            if(sysConfig.getPayOpen()==1){
//                FsStorePayment storePayment=new FsStorePayment();
//                storePayment.setCompanyId(order.getCompanyId());
//                storePayment.setCompanyUserId(order.getCompanyUserId());
//                storePayment.setStatus(0);
//                storePayment.setPayCode(payCode);
//                storePayment.setPayMoney(order.getPayDelivery());
//                storePayment.setCreateTime(new Date());
//                storePayment.setPayTypeCode("weixin");
//                storePayment.setBusinessType(2);
//                storePayment.setRemark("商城订单尾款支付");
//                storePayment.setOpenId(user.getRealName());
//                storePayment.setUserId(user.getUserId());
//                storePayment.setBusinessOrderId(order.getId().toString());
//                storePayment.setOrderId(order.getId());
//                storePayment.setIsPayRemain(1);
//                fsStorePaymentMapper.insertFsStorePayment(storePayment);
//                //创建订单
//                CreatePayDTO createPayDTO=new CreatePayDTO();
//                createPayDTO.setMerchOrderNo(payCode);
//                List<TradeOrder> orders=new ArrayList<>();
//                TradeOrder tradeOrder=new TradeOrder();
//                tradeOrder.setAmount(order.getPayDelivery().toString());
//                tradeOrder.setSubMerchOrderNo("store_remain-"+payCode);
//                tradeOrder.setTradeName("支付订单尾款");
//                tradeOrder.setPayeeOutUserId(sysConfig.getPayPartnerId());
//                orders.add(tradeOrder);
//                createPayDTO.setOrders(orders);
//                payService.createOrder(createPayDTO);
//                //支付订单
//                PayDTO payDTO=new PayDTO();
//                payDTO.setOrigMerchOrderNo(payCode);
//                payDTO.setOpenID(user.getMaOpenId());
//                payDTO.setAppID(wxPayProperties.getAppId());
//                payDTO.setPayerOutUserId(user.getUserId().toString());
//                payDTO.setPayerOutUserName(user.getNickname());
//                payDTO.setUserIp(IPUtils.getIpAddr(request));
//                return R.ok().put("result",payService.payOrder(payDTO));
//            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }

        return R.error("无支付类型");
    }


    @Login
    @ApiOperation("取消订单")
    @PostMapping("/cancelOrder")
//    @Log(title = "取消订单", businessType = BusinessType.UPDATE)
    public R cancelOrder( @Validated @RequestBody FsStoreOrderCancelParam param, HttpServletRequest request){
        FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
        if (order.getStatus() !=0) {
            throw new CustomException("非法操作");
        }
        orderService.cancelOrder(param.getOrderId());
//        if(sysConfig.getPayOpen()==1){
//            if (order.getPaid() == 1) {
//                RefundDTO refundDTO=new RefundDTO();
//                refundDTO.setMerchOrderNo(Ids.oid());
//                refundDTO.setAmount(order.getPayMoney().toString());
//                refundDTO.setOrigMerchOrderNo("store-"+order.getOrderCode());
//                refundDTO.setOrderId(order.getId());
//                payService.refundOrder(refundDTO);
//            }
//            else{
//                orderService.cancelOrder(param.getOrderId());
//            }
//        }
//        else{
//            if (order.getPaid() == 1) {
//                //todo 微信原生退款
//                // BigDecimal bigDecimal = new BigDecimal("100");
//                // int payPrice = bigDecimal.multiply(orderInfo.getPayPrice()).intValue();
//                // weixinPayService.refundOrder(param.getId(),payPrice);
//
//            }
//            else{
//                orderService.cancelOrder(param.getOrderId());
//            }
//
//        }
        return R.ok("操作成功");
    }
    @Login
    @ApiOperation("物流查询")
    @PostMapping("/getExpress")
    public R getExpress( @Validated @RequestBody FsStoreOrderExpressParam param, HttpServletRequest request){
        FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
        if (order.getStatus() <2) {
            throw new CustomException("未发货订单不能查询");
        }

        return orderService.getExpress(order);
    }


    @Login
    @ApiOperation("物流查询多运单号")
    @PostMapping("/getExpressMulti")
    public R getExpressMulti( @Validated @RequestBody FsStoreOrderExpressParam param, HttpServletRequest request){
        FsStoreOrder order=orderService.selectFsStoreOrderById(param.getOrderId());
        if (ObjectUtil.isNull(order)) {
            throw new CustomException("订单不存在");
        }
        if (order.getStatus() <2) {
            throw new CustomException("未发货订单不能查询");
        }
        return orderService.getExpressMulti(order);
    }


    @Login
    @ApiOperation("确认套餐订单")
    @PostMapping("/confirmPackageOrder")
    public R confirmPackageOrder(@Validated @RequestBody FsStoreConfirmPackageIdOrderParam param, HttpServletRequest request){
        return orderService.confirmPackageOrder(Long.parseLong(getUserId()),param);
    }

    @Login
    @ApiOperation("计算套餐订单")
    @PostMapping("/computedPackageOrder")
    public R computedPackageOrder(@Validated @RequestBody FsStoreComputedPackageIdOrderParam param, HttpServletRequest request){
        return orderService.computedPackageOrder(Long.parseLong(getUserId()),param);
    }

    @Login
    @ApiOperation("创建订单")
    @PostMapping("/createPackageOrder")
    public R createPackageOrder(@Validated @RequestBody FsStorePackageOrderCreateParam param, HttpServletRequest request){
        return orderService.createPackageOrder(Long.parseLong(getUserId()),param);
    }

    @Login
    @ApiOperation("完成订单")
    @PostMapping("/finishOrder")
    public R finishOrder( @Validated @RequestBody FsStoreOrderFinishParam param, HttpServletRequest request){
        return orderService.finishOrder(param.getOrderId());
    }


    @Login
    @ApiOperation("获取订单总数")
    @GetMapping("/getOrderCount")
    public R getOrderCount( HttpServletRequest request){
        Integer count0=orderService.selectFsStoreOrderCount(Long.parseLong(getUserId()),0);
        Integer count1=orderService.selectFsStoreOrderCount(Long.parseLong(getUserId()),1);
        Integer count2=orderService.selectFsStoreOrderCount(Long.parseLong(getUserId()),2);
        Integer afterSalesCount=afterSalesService.selectFsStoreAfterSalesCount(Long.parseLong(getUserId()),0);
        return R.ok().put("count0",count0).put("count1",count1).put("count2",count2).put("afterSalesCount",afterSalesCount);
    }


}
