package com.willalp.web.controller.app;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.willalp.app.service.IHsAppHomeService;
import com.willalp.canteen.domain.*;
import com.willalp.canteen.domain.req.AppGetCuisinesReq;
import com.willalp.canteen.domain.req.AppOrderPaymentReq;
import com.willalp.canteen.domain.resp.CuisineListResp;
import com.willalp.canteen.service.*;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.domain.entity.SysUser;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.enums.ConsumeChangeEnum;
import com.willalp.common.enums.NumberRuleEnum;
import com.willalp.common.enums.PartternIdEnum;
import com.willalp.common.enums.PlaceEnum;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.SecurityUtils;
import com.willalp.common.utils.bean.BeanUtils;
import com.willalp.consume.domain.ConsumeMaintain;
import com.willalp.consume.service.IConsumeMaintainService;
import com.willalp.files.domain.HsOrgPersonnelFiles;
import com.willalp.files.service.IHsOrgPersonnelFilesService;
import com.willalp.framework.web.service.SysLoginService;
import com.willalp.integral.domain.Integral;
import com.willalp.integral.service.IIntegralService;
import com.willalp.number.domain.req.NumberRuleReq;
import com.willalp.number.service.IHsSysNumberRuleService;
import com.willalp.push.service.IHsAppPushService;
import com.willalp.system.domain.SysCardInfo;
import com.willalp.system.domain.SysUserOrganization;
import com.willalp.system.domain.req.AppLoginReq;
import com.willalp.system.domain.req.AppSysReq;
import com.willalp.system.domain.resp.AppUserResp;
import com.willalp.system.domain.resp.OrganizationListResp;
import com.willalp.system.service.*;
import com.willalp.wx.domain.WxMsgTemplateTakeFood;
import com.willalp.wx.enums.WxTemplateKeyEnum;
import com.willalp.wx.service.WxMsgService;
import com.willalp.wx.utils.WxUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Api("app接口")
@RestController
@RequestMapping("/app")
public class AppController extends BaseController {

    @Autowired
    IHsCanteenMenuService hsCanteenMenuService;

    @Autowired
    IHsCanteenMenuRegisterService hsCanteenMenuRegisterService;

    @Autowired
    IHsSysNumberRuleService hsSysNumberRuleService;

    @Autowired
    IHsCanteenOrderService hsCanteenOrderService;

    @Autowired
    IHsCanteenOrderDetailService hsCanteenOrderDetailService;

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    IIntegralService integralService;

    @Autowired
    IConsumeMaintainService consumeMaintainService;

    @Autowired
    ISysCardInfoService sysCardInfoService;

    @Autowired
    SysLoginService loginService;

    @Autowired
    ISysConfigService sysConfigService;

    @Autowired
    ISysUserOrganizationService sysUserOrganizationService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IHsCanteenDiningPlaceService hsCanteenDiningPlaceService;

    @Autowired
    private IHsGiftService hsGiftService;

    @Resource
    private ISysNoticeService noticeService;

    @Resource
    private IHsAppHomeService hsAppHomeService;

    @Resource
    private WxMsgService wxMsgService;

    @Resource
    private WxUtils wxUtils;


    /**
     * 获取首页配置数据
     *
     * @param orgCode
     * @return
     */
    @ApiOperation("获取首页配置数据")
    @GetMapping("/getHomeConfigData")
    public AjaxResult getHomeConfigData(@RequestParam(value = "orgCode", required = false)
                                        @ApiParam("机构编号") String orgCode) {
        return AjaxResult.success(hsAppHomeService.getHomeConfigData(orgCode).get("data"));
    }

    /**
     * 查询菜品
     *
     * @param appGetCuisinesReq
     * @return
     */
    @ApiOperation("获取菜品")
    @RequestMapping("/cuisines")
    @ResponseBody
    public AjaxResult getMenuCuisines(@RequestBody AppGetCuisinesReq appGetCuisinesReq) {
        Map<String, Object> result = new HashMap<>();
        HsCanteenMenu hsCanteenMenu = new HsCanteenMenu();
        BeanUtils.copyBeanProp(hsCanteenMenu, appGetCuisinesReq);
        hsCanteenMenu.setConsumerType(null);
        List<HsCanteenMenu> menus = hsCanteenMenuService.selectHsCanteenMenuList(hsCanteenMenu);
        menus = menus.stream().filter(o ->
                Arrays.asList(o.getConsumerType().split(",")).contains(String.valueOf(appGetCuisinesReq.getConsumerType())))
                .collect(Collectors.toList());
        if (menus.size() > 0) {
            result.put("patternId", menus.get(0).getPatternId());
            result.put("menuNumber", menus.get(0).getMenuNumber());
            result.put("periodId", menus.get(0).getPeriodId());
            result.put("maxCount", menus.get(0).getMaxCount());
            List<CuisineListResp> registers = new ArrayList<>();
            Integer limit = Integer.valueOf(sysConfigService.selectConfigByKey("app.canteen.limit"));
            if (limit == 1) {
                //判断限制
                ConsumeMaintain consumeMaintain = new ConsumeMaintain();
                consumeMaintain.setMenuNumber(menus.get(0).getMenuNumber());
                List<ConsumeMaintain> cons = new ArrayList<>();
                cons = consumeMaintainService.selectConsumeMaintainList(consumeMaintain);
                if (cons.size() > 0) {//有限制
                    consumeMaintain = cons.get(0);
                    String begin = DateUtils.parseDateToStr("yyyy-MM-dd", consumeMaintain.getSendTime()) + " " + consumeMaintain.getBeginDate() + ":00";
                    String end = DateUtils.parseDateToStr("yyyy-MM-dd", consumeMaintain.getSendTime()) + " " + consumeMaintain.getEndDate() + ":00";
                    if (DateUtil.isIn(new Date(), DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", begin), DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", end))) {
                        HsCanteenMenuRegister register = new HsCanteenMenuRegister();
                        register.setMenuNumber(menus.get(0).getMenuNumber());
                        registers = hsCanteenMenuRegisterService.selectCuisineList(register, 0, 0);
                    } else {
                        return AjaxResult.error("菜单不在可选时间内");
                    }
                } else {
                    return AjaxResult.error("菜单未维护限制时间");
                }
            } else {
                HsCanteenMenuRegister register = new HsCanteenMenuRegister();
                register.setMenuNumber(menus.get(0).getMenuNumber());
                registers = hsCanteenMenuRegisterService.selectCuisineList(register, 0, 0);
            }
//            Integer maximum = Integer.valueOf(sysConfigService.selectConfigByKey("app.canteen.maximum"));
//            registers = registers.stream().map(item -> {
////                if (item.getCuisinePicture() != null) {
////                    item.setCuisinePicture("http://" + getIp() + item.getCuisinePicture());
////                }
//                //设置菜品最大数量
//                item.setMaximum(maximum);
//                return item;
//            }).collect(Collectors.toList());
            result.put("registers", registers);
            return AjaxResult.success(result);
        }

        return AjaxResult.error("菜单不存在");
    }

    /**
     * 查询菜品
     *
     * @param appGetCuisinesReq
     * @return
     */
    @ApiOperation("获取菜品2")
    @RequestMapping("/getCuisines")
    @ResponseBody
    public AjaxResult getMenuCuisinesLimit(@RequestBody AppGetCuisinesReq appGetCuisinesReq) {
        List<Map<String, Object>> resp = new ArrayList<>();
        //根据当前日期查找符合要求菜单
        ConsumeMaintain consumeMaintain = new ConsumeMaintain();
        consumeMaintain.setOrganizationCode(appGetCuisinesReq.getJgid());
        List<ConsumeMaintain> cons = new ArrayList<>();
        cons = consumeMaintainService.selectConsumeMaintainList(consumeMaintain);
        cons = cons.stream().filter(o ->
                DateUtil.isIn(new Date(),
                        DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", DateUtils.parseDateToStr("yyyy-MM-dd", o.getSendTime()) + " " + o.getBeginDate() + ":00"),
                        DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", DateUtils.parseDateToStr("yyyy-MM-dd", o.getSendTime()) + " " + o.getEndDate() + ":00")
                )
        ).collect(Collectors.toList());
        List<String> nums = cons.stream().map(ConsumeMaintain::getMenuNumber).collect(Collectors.toList());
        if (nums.size() == 0) {
            return AjaxResult.error("当前时间无内容");
        }
        List<HsCanteenMenu> menus = hsCanteenMenuService.selectAppMenuList(nums, appGetCuisinesReq.getJgid());
        menus = menus.stream().filter(o ->
                Arrays.asList(o.getConsumerType().split(",")).contains(String.valueOf(appGetCuisinesReq.getConsumerType())))
                .collect(Collectors.toList());
        if (menus.size() == 0) {
            return AjaxResult.error("不存在符合条件菜单");
        }
        menus.stream().forEach(o -> {
            Map<String, Object> result = new HashMap<>();
            result.put("patternId", o.getPatternId());
            result.put("menuNumber", o.getMenuNumber());
            result.put("periodId", o.getPeriodId());
            result.put("menuName", o.getMenuName());
            result.put("useDate", o.getUseDate());
            result.put("jgid", o.getJgid());
            result.put("maxCount", o.getMaxCount());
            HsCanteenMenuRegister register = new HsCanteenMenuRegister();
            register.setMenuNumber(o.getMenuNumber());
            register.setJgid(o.getJgid());
            List<CuisineListResp> registers = hsCanteenMenuRegisterService.selectCuisineList(register, 0, 0);
//            if (registers.size() > 0) {
//                Integer maximum = Integer.valueOf(sysConfigService.selectConfigByKey("app.canteen.maximum"));
//                registers = registers.stream().map(item -> {
//                    item.setMaximum(maximum);
//                    return item;
//                }).collect(Collectors.toList());
            result.put("registers", registers);
            resp.add(result);

//            }
        });

        return AjaxResult.success(resp);
    }

    /**
     * 下单
     *
     * @return
     */
    @RequestMapping("/order")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult orderPayment(@RequestBody AppOrderPaymentReq appOrderPaymentReq) {
        HsCanteenOrder hsCanteenOrder = new HsCanteenOrder();//订单
        Integral integral = new Integral();//消费记录
        //验证订单唯一性
        List<HsCanteenOrder> existOrders = new ArrayList<>();
        HsCanteenOrder existOrder = new HsCanteenOrder();
        existOrder.setUserNumber(appOrderPaymentReq.getUserNumber());
        existOrder.setMenuNumber(appOrderPaymentReq.getMenuNumber());
        existOrder.setJgid(appOrderPaymentReq.getJgid());
        existOrders = hsCanteenOrderService.selectHsCanteenOrderList(existOrder);
        existOrders = existOrders.stream().filter(o -> o.getZfbz() != 1).collect(Collectors.toList());
        if (existOrders.size() > 0) {
            return AjaxResult.error("用户已有此餐订单");
        }
        //验证用户
        SysUserOrganization user = new SysUserOrganization();
        user.setLoginName(appOrderPaymentReq.getUserNumber());
        user.setOrganizationCode(appOrderPaymentReq.getJgid());
        List<SysUserOrganization> userList = sysUserOrganizationService.selectSysUserOrganizationList(user);
        if (userList.size() == 0) {
            return AjaxResult.error("用户信息不存在");
        }
        user = userList.get(0);
        //生成消费记录
        integral.setId(IdWorker.getIdStr());
        //设备编号
        integral.setRechargeEquipmentCode(appOrderPaymentReq.getDeviceNumber());
        //设备名称
        integral.setRechargeEquipmentName(appOrderPaymentReq.getDeviceName());
        //账号编号
        integral.setLoginName(appOrderPaymentReq.getUserNumber());
        //支付时间
        integral.setRechargeTime(appOrderPaymentReq.getPaytime());
        //积分(负数)
        integral.setRechargeIntegral(appOrderPaymentReq.getOrderTotal().negate());
        //有效标志
        integral.setIsDelete(0);
        integral.setNickName(user.getNickName());
        //机构代码
        integral.setOrganizationCode(appOrderPaymentReq.getJgid());
        //预定消费模式扣减积分
        if (appOrderPaymentReq.getPatternId().equals(PartternIdEnum.RESERVE.getValue())) {
            if (user.getIntegral().compareTo(appOrderPaymentReq.getOrderTotal()) < 0) {
                return AjaxResult.error("账户积分不足");
            }
            //扣减积分
            user.setIntegral(user.getIntegral().subtract(appOrderPaymentReq.getOrderTotal()));
            //消费标志
            hsCanteenOrder.setConsumeSign(0);
            integral.setMoneyType(Integer.valueOf(ConsumeChangeEnum.ONLINECONSUME.getValue()));//消费
        } else {
            if (user.getQuota().compareTo(appOrderPaymentReq.getOrderTotal()) < 0) {
                return AjaxResult.error("记账额度不足");
            }
            //扣减积分
            user.setQuota(user.getQuota().subtract(appOrderPaymentReq.getOrderTotal()));
            //记账标志
            hsCanteenOrder.setConsumeSign(1);
            integral.setMoneyType(Integer.valueOf(ConsumeChangeEnum.ONLINEBOOKING.getValue()));//消费
        }
        //订单
        BeanUtils.copyBeanProp(hsCanteenOrder, appOrderPaymentReq);
        //获取id
        hsCanteenOrder.setOrderId(IdWorker.getIdStr());
        //获取订单编码
        NumberRuleReq numberRuleReq = new NumberRuleReq();
        numberRuleReq.setRuleId(NumberRuleEnum.ORDER.getValue());
        numberRuleReq.setInput(String.valueOf(DateUtil.year(appOrderPaymentReq.getPaytime())).substring(2, 4));
        String number = hsSysNumberRuleService.getNumber(numberRuleReq);
        hsCanteenOrder.setOrderNumber(number);
        //默认字符 0
        hsCanteenOrder.setDeviceName("0");
        hsCanteenOrder.setDeviceNumber("0");
        //订单详情
        if (appOrderPaymentReq.getDetails() == null) {
            return AjaxResult.error("订单明细不能为空");
        }
        appOrderPaymentReq.getDetails().stream().forEach(o -> {
            o.setDetailId(IdWorker.getIdStr());
            o.setOrderNumber(hsCanteenOrder.getOrderNumber());
        });

        try {
            WxMsgTemplateTakeFood wxMsgTemplateTakeFood = new WxMsgTemplateTakeFood();
            wxMsgTemplateTakeFood.setThing4(wxUtils.getFormat(appOrderPaymentReq.getPlaceName()));
            wxMsgTemplateTakeFood.setPhrase14(wxUtils.getFormat("待取餐"));
            wxMsgTemplateTakeFood.setTime8(wxUtils.getFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", appOrderPaymentReq.getPaytime())));
            StringBuilder de = new StringBuilder();
            for (HsCanteenOrderDetail detail : appOrderPaymentReq.getDetails()) {
                de.append("【").append(detail.getCuisineName()).append("】");
            }
            wxMsgTemplateTakeFood.setThing16(wxUtils.getFormat(de.toString()));
            wxMsgTemplateTakeFood.setAmount11(wxUtils.getFormat(String.valueOf(appOrderPaymentReq.getOrderTotal())));
            wxMsgService.sendQRCodeMsg(appOrderPaymentReq.getUserNumber(), wxMsgTemplateTakeFood, WxTemplateKeyEnum.TAKE_FOOD, true);
            sysUserOrganizationService.updateById(user);//更新账户信息
            hsCanteenOrderService.save(hsCanteenOrder);//订单主表
            hsCanteenOrderDetailService.saveBatch(appOrderPaymentReq.getDetails());//订单明细
            integral.setOrderNumber(hsCanteenOrder.getOrderNumber());
            integralService.save(integral);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("保存失败");
        }

        return AjaxResult.success("保存成功");
    }


    /**
     * 获取用户
     *
     * @param sys
     * @return
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public AjaxResult getUser(@RequestBody AppSysReq sys) {
        SysUser user = new SysUser();
        user.setUserName(sys.getUserName());
        if (StrUtil.isBlank(sys.getOrganizationCode())) {
            return AjaxResult.error("机构代码不能为空");
        }
        user.setOrganizationCode(sys.getOrganizationCode());
        AppUserResp userResp = sysUserService.selectAppUserList(user);
        if (userResp == null) {
            return AjaxResult.error("暂未绑定机构或绑定已到期");
        }
//        if (StrUtil.isNotBlank(user.getAvatar())) {
//            user.setAvatar("http://" + getIp() + user.getAvatar());
//        }
        return AjaxResult.success(userResp);
    }

    @Resource
    private IHsGiftOrderService giftOrderService;

    /**
     * 获取待取订单
     *
     * @return
     */
    @RequestMapping("/getOrder2")
    @ResponseBody
    public TableDataInfo getOrder(HttpServletRequest request) {
        startPage();
        HsGiftOrder order = new HsGiftOrder();
        order.setUserNumber(request.getHeader("UserName"));
        List<HsGiftOrder> orders = giftOrderService.selectHsCanteenOrderList(order);
        orders.sort(Comparator.comparing(HsGiftOrder::getPaytime).reversed());
        return getDataTable(orders);
    }

    /**
     * 获取订单信息
     *
     * @param sys
     * @return
     */
    @RequestMapping("/getOrder")
    @ResponseBody
    public TableDataInfo getOrder(@RequestBody AppSysReq sys) {
        startPage();
        List<HsCanteenOrder> orders = new ArrayList<>();
        HsCanteenOrder order = new HsCanteenOrder();
        order.setUserNumber(sys.getUserName());
        order.setJgid(sys.getOrganizationCode());
        orders = hsCanteenOrderService.selectHsCanteenOrderList(order);
        orders.sort(Comparator.comparing(HsCanteenOrder::getPaytime).reversed());
        return getDataTable(getPage().setRecords(orders));
    }

    /**
     * 获取订单信息详情
     *
     * @param sys
     * @return
     */
    @RequestMapping("/getOrderDetail")
    @ResponseBody
    public TableDataInfo getOrderDetail(@RequestBody AppSysReq sys) {
        startPage();
        HsCanteenOrderDetail hcod = new HsCanteenOrderDetail();
        hcod.setOrderNumber(sys.getOrderNumber());
        return getDataTable(hsCanteenOrderDetailService.selectHsCanteenOrderDetailList(hcod));
    }

    /**
     * 获取充值历史记录
     *
     * @param req
     * @return
     */
    @RequestMapping("/getRecharge")
    @ResponseBody
    public TableDataInfo getRecharge(@RequestBody AppSysReq req) {
        startPage();
        List<Integral> integrals = new ArrayList<>();
        Integral integral = new Integral();
        integral.setLoginName(req.getUserName());
        integral.setOrganizationCode(req.getOrganizationCode());
        integrals = integralService.selectIntegralList(integral);
        int[] typeArr = {1, 2, 3, 4, 5, 6, 7, 8};
        integrals = integrals.stream().filter(o -> ArrayUtil.contains(typeArr, o.getMoneyType())).collect(Collectors.toList());
        return getDataTable(integrals);
    }

    /**
     * 获取用户卡片
     *
     * @param req
     * @return
     */
    @RequestMapping("/getCardInfo")
    @ResponseBody
    public AjaxResult getCardInfo(@RequestBody AppSysReq req) {
        List<SysCardInfo> cardInfos = new ArrayList<>();
        SysCardInfo cardInfo = new SysCardInfo();
        cardInfo.setOrganizationCode(req.getOrganizationCode());
        cardInfo.setUserId(req.getUserName());
        cardInfos = sysCardInfoService.selectSysCardInfoList(cardInfo);
        if (cardInfos.size() > 0) {
            cardInfo = cardInfos.get(0);
        }

        return AjaxResult.success(cardInfo);
    }


    @Resource
    private IHsAppPushService pushService;

    @Resource
    private IHsOrgPersonnelFilesService personnelFilesService;

    /**
     * 登录接口(token永久有效)
     *
     * @param loginBody
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestBody AppLoginReq loginBody) {
        AjaxResult ajax = AjaxResult.success();
        if ("1".equals(loginBody.getLoginType())) {
            SysUser info = userService.getUserByPhone(loginBody.getUsername());
            if (info == null) {
                return AjaxResult.error("用户信息不存在");
            }
            loginBody.setUsername(info.getUserName());
        }
        AjaxResult ajaxResult = loginService.appLogin(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), ajax);//员工表单信息
        HsOrgPersonnelFiles files = orgPersonnelFilesService.getBaseMapper().selectOne(new QueryWrapper<HsOrgPersonnelFiles>()
                .eq("user_code", loginBody.getUsername()));
        if (files != null) {
            ajaxResult.put("files", files);
        }
        return ajax;
    }

    /**
     * app退单接口
     *
     * @param orderNumber
     * @return
     */
    @RequestMapping("/back")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult back(String orderNumber) {
        HsCanteenOrder order = new HsCanteenOrder();
        order.setOrderNumber(orderNumber);
        List<HsCanteenOrder> orders;
        orders = hsCanteenOrderService.selectHsCanteenOrderList(order);
        if (orders.size() > 0) {
            order = orders.get(0);
            //判断时间是否在时间内
            ConsumeMaintain consumeMaintain = new ConsumeMaintain();
            consumeMaintain.setMenuNumber(order.getMenuNumber());
            List<ConsumeMaintain> cons = new ArrayList<>();
            cons = consumeMaintainService.selectConsumeMaintainList(consumeMaintain);
            //有限制
            if (cons.size() > 0) {
                consumeMaintain = cons.get(0);
                String begin = DateUtils.parseDateToStr("yyyy-MM-dd", consumeMaintain.getSendTime()) + " " + consumeMaintain.getBeginDate() + ":00";
                String end = DateUtils.parseDateToStr("yyyy-MM-dd", consumeMaintain.getSendTime()) + " " + consumeMaintain.getEndDate() + ":00";
                if (!DateUtil.isIn(new Date(), DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", begin), DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", end))) {
                    return AjaxResult.error("订单已过可退时间,请联系管理员");
                }
            }
//            else {
//                throw new BaseException("未找到对应菜单信息");
//            }
            //处理订单信息
            if (order.getZfbz() == 1) {
                return AjaxResult.error("该订单已作废，不可重复作废");
            }
            try {
                SysUserOrganization user = new SysUserOrganization();
                user.setLoginName(order.getUserNumber());
                user.setOrganizationCode(order.getJgid());
                List<SysUserOrganization> userList = sysUserOrganizationService.selectSysUserOrganizationList(user);
                if (userList.size() == 0) {
                    return AjaxResult.error("用户信息不存在");
                }
                user = userList.get(0);
                //生成作废消费记录
                Integral integral = new Integral();
                integral.setId(IdWorker.getIdStr());//积分主键
                integral.setMoneyType(Integer.valueOf(ConsumeChangeEnum.REFUND.getValue()));//退还
                integral.setRechargeEquipmentCode(order.getDeviceNumber());//设备编号
                integral.setRechargeEquipmentName(order.getDeviceName());//设备名称
                integral.setLoginName(order.getUserNumber());//账号编号
                integral.setRechargeTime(new Date());//作废时间
                integral.setRechargeIntegral(order.getOrderTotal());//积分
                integral.setIsDelete(0);//有效标志
                integral.setNickName(user.getNickName());
                integral.setOrganizationCode(order.getJgid());//机构代码
                integral.setOrderNumber(order.getOrderNumber());
                //更新余额
                if (order.getConsumeSign() == 0) {
                    //扣减积分
                    user.setIntegral(user.getIntegral().add(order.getOrderTotal()));
                } else {
                    user.setQuota(user.getQuota().add(order.getOrderTotal()));
                }
                //订单状态
                order.setZfbz(1);
                order.setZfsj(new Date());
                //update
                hsCanteenOrderService.updateById(order);
                integralService.save(integral);
                sysUserOrganizationService.updateById(user);
            } catch (Exception e) {
                throw new BaseException("作废失败");
            }
            return AjaxResult.success("作废成功");
        }

        return AjaxResult.error("订单信息不存在");
    }


    /**
     * app获取用户机构
     *
     * @return
     */
    @RequestMapping("/getOrganization")
    @ResponseBody
    public AjaxResult getOrganizationByUserName(@RequestBody AppSysReq req) {
        List<OrganizationListResp> resp = sysUserOrganizationService.getOrganizationByUserName(req.getUserName());
        return AjaxResult.success(resp);
    }

    @RequestMapping("/add")
    @ResponseBody
    public AjaxResult add(@RequestBody SysUser user) {
//        if (StringUtils.isNotEmpty(user.getPhonenumber())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
//        } else if (StringUtils.isNotEmpty(user.getEmail())
//                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        user.setCreateBy("app");
        user.setUserType("1");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        HsOrgPersonnelFiles opf = new HsOrgPersonnelFiles();
        opf.setUserCode(user.getUserName());
        opf.setPhone(user.getPhonenumber());
        opf.setOrgCode("G00000007");
        orgPersonnelFilesService.save(opf);
        return AjaxResult.success(userService.insertUser(user));
    }

    @RequestMapping("/getPlace")
    @ResponseBody
    public AjaxResult getPlace(@RequestBody AppSysReq req) {
        HsCanteenDiningPlace place = new HsCanteenDiningPlace();
        List<HsCanteenDiningPlace> list;
        place.setJgid(req.getOrganizationCode());
        place.setPlaceType(PlaceEnum.CANTEEN.getValue());
        place.setParentId(Long.valueOf("1550048349556744193"));
        list = hsCanteenDiningPlaceService.selectHsCanteenDiningPlaceList(place);
        //List<Long> ids = list.stream().map(HsCanteenDiningPlace::getParentId).collect(Collectors.toList());
        //list = list.stream().filter(o -> !ids.contains(o.getId())).collect(Collectors.toList());
        return AjaxResult.success(list);
    }


    /**
     * 获取通知公告
     *
     * @param orgNo 机构编号
     * @return
     */
    @GetMapping("/notice")
    public AjaxResult appNoticeList(@RequestParam String orgNo) {
        return AjaxResult.success(noticeService.selectNoticeList(null));
    }

    @Resource
    private IHsOrgPersonnelFilesService orgPersonnelFilesService;

}
