package com.stylefeng.guns.modular.system.controller.specialTrain; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.mysql.cj.log.Log; import com.stylefeng.guns.core.base.controller.BaseController; import com.stylefeng.guns.core.common.constant.factory.PageFactory; import com.stylefeng.guns.core.shiro.ShiroKit; import com.stylefeng.guns.core.shiro.ShiroUser; import com.stylefeng.guns.core.util.DateUtil; import com.stylefeng.guns.core.util.RequestSeqUtil; import com.stylefeng.guns.core.util.SinataUtil; import com.stylefeng.guns.core.util.ToolUtil; import com.stylefeng.guns.modular.cloudPayment.example.AllocationExample; import com.stylefeng.guns.modular.cloudPayment.req.AllocationReq; import com.stylefeng.guns.modular.huifu.biz.DouGongRefundBiz; import com.stylefeng.guns.modular.huifu.biz.FenZhangUtil; import com.stylefeng.guns.modular.system.controller.util.Base64Util; import com.stylefeng.guns.modular.system.dao.OrderCancelMapper; import com.stylefeng.guns.modular.system.model.*; import com.stylefeng.guns.modular.system.service.*; import com.stylefeng.guns.modular.system.util.*; import com.unionpay.upyzt.exception.UpyztException; import com.unionpay.upyzt.resp.AllocationResp; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.ui.Model; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; /** * 小件物流订单控制器 * * @author fengshuonan * @Date 2020-09-24 14:20:41 */ @Slf4j @Controller @RequestMapping("/tOrderLogistics") public class TOrderLogisticsController extends BaseController { private String PREFIX = "/system/tOrderLogistics/"; @Autowired private ITOrderLogisticsService tOrderLogisticsService; @Resource private OrderCancelMapper orderCancelMapper; @Autowired private ITUserService userService; @Autowired private ITransactionDetailsService transactionDetailsService; @Autowired private IPaymentRecordService paymentRecordService; @Autowired private IIncomeService incomeService; @Autowired private ITDriverService tDriverService; @Autowired private ITTimeoutAppealService timeoutAppealService; @Autowired private PayMoneyUtil payMoneyUtil; @Autowired private IUserCouponRecordService userCouponRecordService; @Autowired private DouGongRefundBiz douGongRefundBiz; /** * 跳转到小件物流订单首页 */ @RequestMapping("") public String index() { return PREFIX + "tOrderLogistics.html"; } /** * 跳转到添加小件物流订单 */ @RequestMapping("/tOrderLogistics_add") public String tOrderLogisticsAdd() { return PREFIX + "tOrderLogistics_add.html"; } /** * 跳转到查看小件物流订单 */ @RequestMapping("/tOrderLogistics_detail/{tOrderLogisticsId}") public String tOrderLogistics_detail(@PathVariable Integer tOrderLogisticsId, Model model) { Map tOrderLogistics = tOrderLogisticsService.getLogisticsOrderDetailById(tOrderLogisticsId); TTimeoutAppeal tTimeoutAppeal = timeoutAppealService.selectOne(new EntityWrapper().eq("orderId",tOrderLogistics.get("id"))); if (ToolUtil.isNotEmpty(tTimeoutAppeal) && ToolUtil.isNotEmpty(tTimeoutAppeal.getReturnMoney())){ tOrderLogistics.put("returnMoney",tTimeoutAppeal.getReturnMoney()); }else { tOrderLogistics.put("returnMoney","0.00"); } model.addAttribute("item",tOrderLogistics); return PREFIX + "tOrderLogistics_detail.html"; } /** * 获取小件物流订单列表 */ @RequestMapping(value = "/list") @ResponseBody public Object list(String insertTime, String orderNum, Integer type, Integer orderSource, String userName, String userPhone, String recipient, String recipientPhone, String driver, Integer state) { String beginTime = null; String endTime = null; if (SinataUtil.isNotEmpty(insertTime)){ String[] timeArray = insertTime.split(" - "); beginTime = timeArray[0]; endTime = timeArray[1]; } Page> page = new PageFactory>().defaultPage(); page.setRecords(tOrderLogisticsService.getLogisticsOrderList(page,beginTime,endTime,ShiroKit.getUser().getRoleType(),ShiroKit.getUser().getObjectId(), orderNum,orderSource,type,userName,userPhone,recipient,recipientPhone,driver,state)); return super.packForBT(page); } @Autowired private ITDriverService itDriverService; /** * 取消小件物流订单 */ @RequestMapping(value = "/cancel") @ResponseBody public Object cancel(@RequestParam Integer tOrderLogisticsId) { try{ ShiroUser user = ShiroKit.getUser(); TOrderLogistics tOrderLogistics = tOrderLogisticsService.selectById(tOrderLogisticsId); Integer orgState = tOrderLogistics.getState(); tOrderLogistics.setState(10); //已支付的情况下进行退款操作 if(null != tOrderLogistics.getPayType() && null != tOrderLogistics.getPayMoney()) { if (tOrderLogistics.getPayType() ==3) {//余额支付 TUser tUser = userService.selectById(tOrderLogistics.getUserId()); tUser.setBalance(tUser.getBalance().add(tOrderLogistics.getPayMoney())); userService.updateById(tUser); if(tOrderLogistics.getPayMoney().doubleValue()>0) { createAllocationReqUser(1, tUser.getId(), 1, tOrderLogistics.getPayMoney().doubleValue()); } } else { System.out.println("其他支付"); if(tOrderLogistics.getOrderSource()==4){ System.out.println("退司机"); TDriver driver = itDriverService.selectById(tOrderLogistics.getDriverId()); driver.setBalance(driver.getBalance().add(tOrderLogistics.getPayMoney())); itDriverService.updateById(driver); if(tOrderLogistics.getPayMoney().doubleValue()>0) { createAllocationReq(1, driver.getId(), 1, tOrderLogistics.getPayMoney().doubleValue()); } }else { System.out.println("退用户"); // TUser tUser = userService.selectById(tOrderLogistics.getUserId()); // tUser.setBalance(tUser.getBalance().add(tOrderLogistics.getPayMoney())); // userService.updateById(tUser); // if(tOrderLogistics.getPayMoney().doubleValue()>0) { // createAllocationReqUser(1, tUser.getId(), 1, tOrderLogistics.getPayMoney().doubleValue()); // } List querys = paymentRecordService.query_(1, tOrderLogistics.getUserId(), 1, tOrderLogistics.getId(), tOrderLogistics.getType(), tOrderLogistics.getPayType(), 2); System.out.println(querys); boolean b = false; List orderIds = querys.stream().map(PaymentRecord::getOrderId).collect(Collectors.toList()); Map orderLogisticsMap = Collections.emptyMap(); if (CollectionUtils.isNotEmpty(orderIds)) { orderLogisticsMap = tOrderLogisticsService.selectList(new EntityWrapper() .in("id", orderIds).isNotNull("outTradeNo")) .stream().collect(Collectors.toMap(TOrderLogistics::getId, Function.identity())); } for (PaymentRecord query : querys) { System.out.println("支付方式:"+query.getPayType()); if(query.getPayType() == 1 || query.getPayType() == 2){//微信 //Map map = payMoneyUtil.wxRefund(query.getCode(), tOrderLogistics.getId() + "_" + tOrderLogistics.getType() + "_" + UUIDUtil.getRandomCode(5), query.getAmount().toString(), query.getAmount().toString(), "/base/cancleOrderWXPay"); //System.out.println("map:"+map); //if(!"SUCCESS".equals(map.get("return_code"))){ // return ResultUtil.error(map.get("return_msg")); //} TOrderLogistics orderLogistics = orderLogisticsMap.get(query.getOrderId()); if (Objects.isNull(orderLogistics)) { log.error("小件物流取消订单退款失败,未找到对应的斗拱支付订单,orderId={}", query.getOrderId()); continue; } String refundReqSeqId = RequestSeqUtil.generate("TK"); Map refund = douGongRefundBiz.refund(refundReqSeqId, BigDecimal.valueOf(query.getAmount()), DateUtil.format(query.getInsertTime(), "yyyyMMdd"), orderLogistics.getOutTradeNo(), 1); orderLogistics.setRefundReqSeqId(refundReqSeqId); orderLogistics.setState(orgState); tOrderLogistics.setState(orgState); if ("00000000".equals(refund.get("resp_code")) && "S".equals(refund.get("trans_stat"))) { orderLogistics.setState(10); tOrderLogistics.setState(10); }else if (!"00000000".equals(refund.get("resp_code"))) { return ResultUtil.error("订单取消失败:" + refund.get("resp_desc").toString()); } tOrderLogisticsService.updateById(orderLogistics); } } } List paymentRecords = paymentRecordService.query(1, null, null, tOrderLogisticsId, tOrderLogistics.getType(), null, 2); if (paymentRecords.size() == 0) { return ResultUtil.error("订单还未进行支付"); } boolean b = false; for(PaymentRecord query : paymentRecords){ // Map merrefund = icbcPayUtil.merrefund(query.getCode(), "", query.getAmount(), tOrderLogistics.getId() + "_" + tOrderLogistics.getType(), tOrderLogistics.getOrderNum()); // if (Integer.valueOf(merrefund.get("code").toString()) == 0) { // Map refundqry = icbcPayUtil.refundqry("", query.getCode(), tOrderLogistics.getOrderNum()); // if (Integer.valueOf(refundqry.get("code").toString()) == 0 && Integer.valueOf(refundqry.get("pay_status").toString()) == 0) {//成功 // b = true; // } // if (Integer.valueOf(refundqry.get("code").toString()) == 0 && Integer.valueOf(refundqry.get("pay_status").toString()) == 1) {//失败 // return ResultUtil.error("订单取消失败(退款不成功)"); // } // if (Integer.valueOf(refundqry.get("code").toString()) == 0 && Integer.valueOf(refundqry.get("pay_status").toString()) == 2) {//未知 // return ResultUtil.error("退款返回未知异常"); // } // } } if(b){ //添加交易明细 } } transactionDetailsService.saveData(tOrderLogistics.getUserId(), "小件订单取消退款", tOrderLogistics.getPayMoney().doubleValue(), 1, 1, 1, 4, tOrderLogistics.getId()); //添加负的收入明细 List incomes = incomeService.selectList(new EntityWrapper().eq("type", 2).eq("incomeId", tOrderLogistics.getId()).eq("orderType", tOrderLogistics.getType())); for(Income income : incomes){ if(income.getUserType() == 2){//处理司机的收入 TDriver driver = tDriverService.selectById(income.getObjectId()); driver.setBalance(driver.getBalance().subtract(new BigDecimal(income.getMoney()))); driver.setLaveBusinessMoney(new BigDecimal(driver.getLaveBusinessMoney()).subtract(new BigDecimal(income.getMoney())).doubleValue()); driver.setBusinessMoney(new BigDecimal(driver.getBusinessMoney()).subtract(new BigDecimal(income.getMoney())).doubleValue()); tDriverService.updateById(driver); } Income income1 = new Income(); BeanUtils.copyProperties(income, income1); income1.setMoney(income.getMoney() * -1); income1.setId(null); income1.setInsertTime(new Date()); incomeService.insert(income1); } } tOrderLogisticsService.updateById(tOrderLogistics); //添加取消记录 OrderCancel orderCancel = new OrderCancel(); orderCancel.setOrderId(tOrderLogistics.getId()); orderCancel.setOrderType(tOrderLogistics.getType()); orderCancel.setReason("调度端取消订单"); orderCancel.setRemark("调度“" + user.getName() + "-" + user.getId() + "”执行取消操作"); orderCancel.setState(2); orderCancel.setInsertTime(new Date()); orderCancel.setUserType(3); orderCancel.setUserId(user.getId()); orderCancelMapper.insert(orderCancel); //增加推送 Map map = new HashMap<>(); map.put("id", tOrderLogistics.getId().toString()); map.put("orderType", tOrderLogistics.getType().toString()); String result = HttpRequestUtil.postRequest(PushURL.cancel_order_url, map); System.out.println("小件物流取消:【orderId="+tOrderLogistics.getId().toString()+"】,调用接口:"+result); }catch (Exception e){ e.printStackTrace(); } return SUCCESS_TIP; } @Autowired private ITEnterpriseWithdrawalService tEnterpriseWithdrawalService; @Autowired private IUserWithdrawalService userWithdrawalService; public String createAllocationReq(Integer companyId,Integer userId,int type,double money){ List tEnterpriseWithdrawals = tEnterpriseWithdrawalService.selectList(new EntityWrapper().eq("companyId", companyId)); TDriver tUser = tDriverService.selectById(userId); List userWithdrawals = userWithdrawalService.selectList(new EntityWrapper().eq("phone", tUser.getPhone())); if(userWithdrawals.size()==0){ return "error"; } AllocationReq allocationReq= new AllocationReq(); allocationReq.setOutOrderNo(ToolUtil.getRandomString(32)); try { Map result; if(type==1){ //allocationReq.setPayBalanceAcctId(tEnterpriseWithdrawals.get(0).getBalanceAcctId()); //allocationReq.setRecvBalanceAcctId(userWithdrawals.get(0).getBalanceAcctId()); // //allocationReq.setPassword(Base64Util.decode(tEnterpriseWithdrawals.get(0).getTransactionAuthorizationCode())); result = FenZhangUtil.fenzhang(RequestSeqUtil.generate("TK"), DateUtil.formatDate(new Date(), "yyyyMMdd"), String.valueOf(money), userWithdrawals.get(0).getHuifuId()); }else { //allocationReq.setRecvBalanceAcctId(tEnterpriseWithdrawals.get(0).getBalanceAcctId()); //allocationReq.setPayBalanceAcctId(userWithdrawals.get(0).getBalanceAcctId()); //allocationReq.setPassword(Base64Util.decode(userWithdrawals.get(0).getTransactionAuthorizationCode())); result = FenZhangUtil.payFromUser(RequestSeqUtil.generate("TK"), DateUtil.formatDate(new Date(), "yyyyMMdd"), String.valueOf(money), userWithdrawals.get(0).getHuifuId()); } if ("00000000".equals(result.get("respCode").toString())) { return "ok"; } else { return result.get("respDesc").toString(); } } catch (Exception e) { log.error("分账异常", e); throw new RuntimeException(e); } //money=money*100; //allocationReq.setAmount((int)money); //allocationReq.setProductName("分账"); //allocationReq.setProductCount(1); //allocationReq.setOrderNo(ToolUtil.getRandomString(32)); //allocationReq.setOrderAmount(1l); //try { // AllocationResp allocationResp = AllocationExample.create(allocationReq); // System.out.println(allocationResp); // return "ok"; //} catch (UpyztException e) { // e.printStackTrace(); // return e.getMessage(); //} } public String createAllocationReqUser(Integer companyId,Integer userId,int type,double money) { List tEnterpriseWithdrawals = tEnterpriseWithdrawalService.selectList(new EntityWrapper().eq("companyId", companyId)); TUser tUser = userService.selectById(userId); List userWithdrawals = userWithdrawalService.selectList(new EntityWrapper().eq("phone", tUser.getPhone())); if(userWithdrawals.size()==0){ return "error"; } //AllocationReq allocationReq= new AllocationReq(); //allocationReq.setOutOrderNo(ToolUtil.getRandomString(32)); try { Map result; if(type==1){ //allocationReq.setPayBalanceAcctId(tEnterpriseWithdrawals.get(0).getBalanceAcctId()); //allocationReq.setRecvBalanceAcctId(userWithdrawals.get(0).getBalanceAcctId()); // //allocationReq.setPassword(Base64Util.decode(tEnterpriseWithdrawals.get(0).getTransactionAuthorizationCode())); result = FenZhangUtil.fenzhang(RequestSeqUtil.generate("TK"), DateUtil.formatDate(new Date(), "yyyyMMdd"), String.valueOf(money), userWithdrawals.get(0).getHuifuId()); }else { //allocationReq.setRecvBalanceAcctId(tEnterpriseWithdrawals.get(0).getBalanceAcctId()); //allocationReq.setPayBalanceAcctId(userWithdrawals.get(0).getBalanceAcctId()); //allocationReq.setPassword(Base64Util.decode(userWithdrawals.get(0).getTransactionAuthorizationCode())); result = FenZhangUtil.payFromUser(RequestSeqUtil.generate("TK"), DateUtil.formatDate(new Date(), "yyyyMMdd"), String.valueOf(money), userWithdrawals.get(0).getHuifuId()); } if ("00000000".equals(result.get("respCode").toString())) { return "ok"; } else { return result.get("respDesc").toString(); } } catch (Exception e) { log.error("分账异常", e); throw new RuntimeException(e); } //money=money*100; //allocationReq.setAmount((int)money); //allocationReq.setProductName("分账"); //allocationReq.setProductCount(1); //allocationReq.setOrderNo(ToolUtil.getRandomString(32)); //allocationReq.setOrderAmount(1l); //try { // AllocationResp allocationResp = AllocationExample.create(allocationReq); // System.out.println(allocationResp); // return "ok"; //} catch (UpyztException e) { // e.printStackTrace(); // return e.getMessage(); //} } /** * 删除小件物流订单 */ @RequestMapping(value = "/delete") @ResponseBody public Object delete(@RequestParam Integer tOrderLogisticsId) { TOrderLogistics tOrderLogistics = tOrderLogisticsService.selectById(tOrderLogisticsId); tOrderLogistics.setIsDelete(2); tOrderLogisticsService.updateById(tOrderLogistics); return SUCCESS_TIP; } /** * 修改收件人 * @param id * @param name * @param phone * @return */ @RequestMapping(value = "/updateRecipient") @ResponseBody public ResultUtil updateRecipient(Integer id, String name, String phone){ try { TOrderLogistics tOrderLogistics = tOrderLogisticsService.selectById(id); if(ToolUtil.isNotEmpty(name)){ tOrderLogistics.setRecipient(name); } if(ToolUtil.isNotEmpty(phone)){ tOrderLogistics.setRecipientPhone(phone); } tOrderLogisticsService.updateById(tOrderLogistics); if(tOrderLogistics.getState() == 4 || tOrderLogistics.getState() == 6){ Map map = new HashMap<>(); map.put("orderId", id.toString()); String result = HttpRequestUtil.postRequest(PushURL.zull_user_url + "/driver/base/order/sendVerificationCode1", map); } return ResultUtil.success(); }catch (Exception e){ e.printStackTrace(); return ResultUtil.runErr(); } } /** * 取消订单微信退款成功回调 * @param request * @param response */ // @ResponseBody // @PostMapping("/base/cancleOrderWXPay") // public void cancleOrderWXPay(HttpServletRequest request, HttpServletResponse response){ // try { // System.out.println("小件物流取消"); // Map map = payMoneyUtil.wxRefundCallback(request); // if(null != map){ // String order_id = map.get("refund_id"); // String out_refund_no = map.get("out_refund_no"); // String result = map.get("result"); // if(ToolUtil.isNotEmpty(out_refund_no) && ToolUtil.isNotEmpty(order_id)){ // PrintWriter out = response.getWriter(); // out.write(result); // out.flush(); // out.close(); // // String[] split = out_refund_no.split("_"); // Integer id = Integer.valueOf(split[0]); // Integer type = Integer.valueOf(split[1]); // System.out.println("取消回调:"+type); // switch (type){ // case 1: // break; // case 2: // break; // case 3: // TOrderLogistics orderCrossCity = tOrderLogisticsService.selectById(id); // PaymentRecord query = paymentRecordService.query_(1, orderCrossCity.getUserId(), 1, id, 3, orderCrossCity.getPayType(), 2); // //添加交易明细 // transactionDetailsService.saveData(orderCrossCity.getUserId(), "跨城出行取消退款", query.getAmount(), 1, 1, 1, 3, id); // break; // case 4: // TOrderLogistics orderLogistics1 = tOrderLogisticsService.selectById(id); // PaymentRecord query1 = paymentRecordService.query_(1, orderLogistics1.getUserId(), 1, id, 4, orderLogistics1.getPayType(), 2); // //添加交易明细 // transactionDetailsService.saveData(orderLogistics1.getUserId(), "同城小件物流取消退款", query1.getAmount(), 1, 1, 1, 4, id); // UserCouponRecord userCouponRecord1 = userCouponRecordService.selectById(orderLogistics1.getCouponId()); // userCouponRecord1.setState(1); // userCouponRecordService.updateById(userCouponRecord1); // orderLogistics1.setCouponMoney(BigDecimal.ZERO); // tOrderLogisticsService.updateById(orderLogistics1); // break; // case 5: // TOrderLogistics orderLogistics2 = tOrderLogisticsService.selectById(id); // PaymentRecord query2 = paymentRecordService.query_(1, orderLogistics2.getUserId(), 1, id, 5, orderLogistics2.getPayType(), 2); // //添加交易明细 // transactionDetailsService.saveData(orderLogistics2.getUserId(), "跨城小件物流取消退款", query2.getAmount(), 1, 1, 1, 5, id); // UserCouponRecord userCouponRecord2 = userCouponRecordService.selectById(orderLogistics2.getCouponId()); // userCouponRecord2.setState(1); // userCouponRecordService.updateById(userCouponRecord2); // orderLogistics2.setCouponMoney(BigDecimal.ZERO); // tOrderLogisticsService.updateById(orderLogistics2); // break; // } // } //// cloudPay(map.get("total_fee"),map.get("transaction_id"),1); // } // }catch (Exception e){ // e.printStackTrace(); // } // } }