package com.willalp.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.willalp.canteen.domain.HsGift;
import com.willalp.canteen.domain.HsGiftOrder;
import com.willalp.canteen.domain.HsGiftOrderDetail;
import com.willalp.canteen.domain.HsOrderProcess;
import com.willalp.canteen.domain.req.GiftCustomPayReq;
import com.willalp.canteen.domain.vo.UserShopCarJsonDoMainVo;
import com.willalp.canteen.service.*;
import com.willalp.clockingin.domain.BizLeave;
import com.willalp.clockingin.service.IBizLeaveService;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.enums.SysOrgCodeEnum;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.StringUtils;
import com.willalp.common.utils.bean.BeanUtils;
import com.willalp.common.utils.http.HttpUtils;
import com.willalp.event.domain.HsEvent;
import com.willalp.event.service.IHsEventService;
import com.willalp.flow.service.HsFlowEngineService;
import com.willalp.flow.service.IHsFlowTaskService;
import com.willalp.msg.domain.HsAppUserMsg;
import com.willalp.msg.service.IHsAppUserMsgService;
import com.willalp.system.domain.SysUserOrganization;
import com.willalp.system.domain.req.AppSysReq;
import com.willalp.system.service.IHsPostConfigService;
import com.willalp.system.service.ISysConfigService;
import com.willalp.system.service.ISysUserOrganizationService;
import com.willalp.wx.domain.WxMsgTemplateInExcSuccess;
import com.willalp.wx.enums.WxTemplateKeyEnum;
import com.willalp.wx.service.WxMsgService;
import com.willalp.wx.utils.WxUtils;
import io.swagger.annotations.Api;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

    @Resource
    private IHsPostConfigService hsPostConfigService;

    @Resource
    private IHsAppUserMsgService hsAppUserMsgService;

    @Resource
    private IHsFlowTaskService taskService;

    @Resource
    private HsFlowEngineService flowEngineService;

    @Resource
    private IBizLeaveService bizLeaveService;

    /**
     * 当前流程审批人员
     * @param groupId
     * @param baseId
     */
    @GetMapping("/currentPL")
    public AjaxResult currentPL(String groupId, String baseId) {
        return AjaxResult.success(flowEngineService.getApprovalTreePost(groupId, baseId));
    }

    /**
     * 当前流程下一级审批人员
     * @param groupId
     * @param baseId
     */
    @GetMapping("/pL")
    public AjaxResult list(String groupId, String baseId) {
        return AjaxResult.success(flowEngineService.getNextApprovalTreePost(groupId, baseId));
    }

    /**
     * 查询岗位配置列表
     * @param taskId
     * @param candidate
     */
    @GetMapping("/task/submit/candidate")
    public AjaxResult submitCandidate(String taskId, String candidate, String applyUserName) {
        return AjaxResult.success(flowEngineService.submitCandidate(taskId, candidate, applyUserName));
    }


    /**
     * 获取消息列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/gum")
    public TableDataInfo getUserMsg(HttpServletRequest request) {
        startPage();
        return getDataTable(
                hsAppUserMsgService.getBaseMapper().selectList(new QueryWrapper<HsAppUserMsg>()
                        .eq("user_code", request.getHeader("UserName"))
                        .last("order by create_time desc")));
    }

    /**
     * 更新消息已读
     *
     * @param uc
     * @param request
     * @return
     */
    @RequestMapping("/rm")
    public AjaxResult readMsg(String id, String uc, HttpServletRequest request) {
        hsAppUserMsgService.readMsgById(id);
        hsAppUserMsgService.allReadMsgByUserCode(uc);
        return AjaxResult.success();
    }

    /**
     * 更新审批任务已读
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/rt")
    public AjaxResult readTask(String taskId, HttpServletRequest request) {
        taskService.readTask(taskId);
        String userName = request.getHeader("UserName");
        hsAppUserMsgService.readMsgByTaskId(taskId, userName);
        hsAppUserMsgService.readReceiptVerify(userName);
        return AjaxResult.success(taskId);
    }

    /**
     * 更新我的发起已读
     *
     * @param id
     * @return
     */
    @RequestMapping("/rl")
    public AjaxResult readTask(String id) {
        if (StringUtils.isNotBlank(id)) {
            BizLeave byId = bizLeaveService.getById(id);
            if (byId != null) {
                byId.setRemark("");
                bizLeaveService.updateById(byId);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询消息总信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/msgs")
    public AjaxResult msgSum(HttpServletRequest request) {
//        return AjaxResult.success(hsAppUserMsgService.pushMsgSum(request.getHeader("UserName")));
        return AjaxResult.success();
    }

    @Resource
    private ISysUserOrganizationService sysUserOrganizationService;

    @Autowired
    private IHsGiftService hsGiftService;

    @Resource
    private IHsGiftOrderService giftOrderService;

    @Resource
    private IHsGiftOrderDetailService giftOrderDetailServic;

    @Resource
    private WxUtils wxUtils;

    /**
     * 获取积分记录
     *
     * @param uc
     * @return
     */
    @RequestMapping("/ac")
    @ResponseBody
    public AjaxResult getAc(@RequestParam String uc) {
        if (StringUtils.isBlank(uc)) {
            return AjaxResult.error("用户系统编码不能为空");
        }
        return AjaxResult.success(sysUserOrganizationService.getBaseMapper().selectOne(new QueryWrapper<SysUserOrganization>()
                .eq("organization_code", SysOrgCodeEnum.HuiJiFen.getCode())
                .eq("login_name", uc)).getIntegral());
    }

    /**
     * 积分商城礼品列表
     *
     * @param req
     * @return
     */
    @RequestMapping("/getGift")
    @ResponseBody
    public TableDataInfo getGift(@RequestBody AppSysReq req) {
        startPage();
        List<HsGift> hsGifts = hsGiftService.appSelectedHsGiftList(req.getGiftType(), req.getGiftTypeCode());
        return getDataTable(hsGifts);
    }

    @Resource
    private IHsGiftOrderDetailService giftOrderDetailService;

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

    /**
     * 退单
     *
     * @param on
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("backOd")
    @ResponseBody
    public AjaxResult backOrder(String on, HttpServletRequest request) {
        try {
            if (StringUtils.isBlank(on)) {
                return AjaxResult.error("单号不可为空");
            }
            String userName = request.getHeader("UserName");
            if (StringUtils.isBlank(userName)) {
                return AjaxResult.error("非法接口请求 - 用户无法获取");
            }
            //获取订单信息
            HsGiftOrder one = giftOrderService.getOne(new QueryWrapper<HsGiftOrder>()
                    .eq("order_number", on)
                    .eq("user_number", userName));
            if (null != one) {
                if (!"已回收".equals(one.getStatusText()) && !"已下单".equals(one.getStatusText())) {
                    return AjaxResult.error("非法退单操作");
                }
                BigDecimal orderTotal = one.getOrderTotal();
                if (null != orderTotal) {
                    //积分退回
                    SysUserOrganization oneSysUo = sysUserOrganizationService.getOne(new QueryWrapper<SysUserOrganization>()
                            .eq("organization_code", "G00000003")
                            .eq("login_name", userName));
                    oneSysUo.setIntegral(oneSysUo.getIntegral().add(orderTotal));
                    sysUserOrganizationService.updateById(oneSysUo);
                }
                //生成记录
//                HsAmassScoreChange asc = new HsAmassScoreChange();
//                Date date = new Date();
//                asc.setCreateTime(date);
//                asc.setChangeDate(date);
//                asc.setChangeType("3");
//                asc.setAmassScore(orderTotal);
//                asc.setUserCode(userName);
//                hsAmassScoreChangeService.save(asc);
//                //生成进度记录
//                HsOrderProcess hop = new HsOrderProcess();
//                hop.setOrderNo(on);
//                hop.setProcessStatus("已完成");
//                hop.setProcessDesc("积分已退还，订单结束");
//                hop.setProcessDate(new Date());
//                hop.setUserCode(userName);
//                orderProcessService.save(hop);
                //修改订单状态
                one.setStatusText("已完成");
                one.setIsNews("1");
                giftOrderService.updateById(one);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }


    @Resource
    private HttpUtils httpUtils;

    @Resource
    private IHsAppUserMsgService userMsgService;

    @Resource
    private IHsOrderProcessService orderProcessService;

    @Resource
    private WxMsgService wxMsgService;

    @Resource
    private IHsEventService eventService;

    /**
     * 积分商城下单
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("giftOrder")
    @ResponseBody
    public AjaxResult giftOrder(@RequestBody GiftCustomPayReq req) {
        //验证用户
        SysUserOrganization sysUserOrganization = sysUserOrganizationService.getBaseMapper().selectOne(new QueryWrapper<SysUserOrganization>()
                .eq("login_name", req.getUserNumber()).eq("organization_code", req.getJgid()));
        if (null == sysUserOrganization) {
            return AjaxResult.error("用户信息不存在");
        }
        if (sysUserOrganization.getIntegral().compareTo(req.getOrderTotal()) < 0) {
            return AjaxResult.error("账户积分不足");
        }
        //生成微信推送模板
        WxMsgTemplateInExcSuccess wxMsgTemplateInExcSuccess = new WxMsgTemplateInExcSuccess();
        //生成审批结果消息列表
        HsAppUserMsg appUserMsg = new HsAppUserMsg();
        StringBuilder content = new StringBuilder();
        //消费标志
        HsGiftOrder hsGiftOrder = new HsGiftOrder();
        hsGiftOrder.setConsumeSign(0);
        hsGiftOrder.setZfbz(req.getOrderType());
        hsGiftOrder.setUserNumber(req.getUserNumber());
        hsGiftOrder.setUserName(req.getUserName());
        hsGiftOrder.setPhone(req.getPhone());
        hsGiftOrder.setPlaceNumber(req.getPlaceNumber());
        hsGiftOrder.setStatusText("已下单");
        //订单
        BeanUtils.copyBeanProp(hsGiftOrder, req);
        //获取id
        hsGiftOrder.setOrderId(IdWorker.getIdStr());
        Date date = new Date();
        hsGiftOrder.setPaytime(date);
        wxMsgTemplateInExcSuccess.setTime5(wxUtils.getFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", date)));
        appUserMsg.setCreateTime(date);
        //订单详情
        if (req.getHsGifts().size() == 0) {
            return AjaxResult.error("订单明细不能为空");
        }
        List<HsGift> hsGifts = new ArrayList<>();
        StringBuilder nameStr = new StringBuilder();
        //获取订单编码
        String data = httpUtils.sendGet(httpUtils.HTTPS + httpUtils.host + ":" + httpUtils.port + httpUtils.path + "/get/onb");
        hsGiftOrder.setOrderNumber(data);
        appUserMsg.setRemark(data);
        //抵扣库存
        for (HsGiftOrderDetail gift : req.getHsGifts()) {
            String giftId = gift.getGiftId();
            Integer amount = gift.getAmount();
            //如果是活动商品
            if (StringUtils.isNotBlank(gift.getEventId())) {
                //获取结束时间
                HsEvent eventbyId = eventService.getById(gift.getEventId());
                long time = eventbyId.getEndTime().getTime();
                //当前时间
                long l = System.currentTimeMillis();
                //结束时间大于当前时间（活动范围内），则支持下单
                if (time < l) {
                    throw new BaseException("活动已结束");
                }
            }
            if (hsGiftService.checkAndReduceGiftInventory(amount, giftId) < 0) {
                throw new BaseException(gift.getGiftName() + "库存不足，下单失败");
            }
            nameStr.append("【").append(gift.getGiftName()).append("】");
            gift.setAmount(gift.getAmount());
            gift.setDetailId(IdWorker.getIdStr());
            gift.setOrderNumber(data);
        }
        //消费积分
        sysUserOrganization.setIntegral(sysUserOrganization.getIntegral().subtract(req.getOrderTotal()));
        try {
            //删除购物车
            for (HsGiftOrderDetail o : req.getHsGifts()) {
                userShopCarService.deleteJson(o.getGiftId(), req.getUserNumber());
            }
            //更新DB数据
            sysUserOrganizationService.updateById(sysUserOrganization);//更新账户信息
            giftOrderService.save(hsGiftOrder);//订单主表
            giftOrderDetailServic.saveBatch(req.getHsGifts());//订单明细
            //发送微信订阅通知
            wxMsgTemplateInExcSuccess.setThing3(wxUtils.getFormat(String.valueOf(req.getOrderTotal())));
            wxMsgTemplateInExcSuccess.setThing6(wxUtils.getFormat(String.valueOf(sysUserOrganization.getIntegral())));
            wxMsgTemplateInExcSuccess.setThing4(wxUtils.getFormat(nameStr.toString()));
            content.append("<p>兑换物品：").append(nameStr).append("</p>")
                    .append("<p>抵扣积分：").append(req.getOrderTotal()).append("</p>")
                    .append("<p>兑换时间：").append(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", date)).append("</p>");
            wxMsgService.sendQRCodeMsg(req.getUserNumber(), wxMsgTemplateInExcSuccess, WxTemplateKeyEnum.INTEGRAL_EXCHANGE_SUCCESS, true);
            hsGiftOrder.setRemark(nameStr.toString());
            //生成订单已下单进度
            List<HsOrderProcess> opList = new ArrayList<>();
            HsOrderProcess op = new HsOrderProcess();
            op.setOrderNo(data);
            op.setProcessNum(1L);
            op.setUserCode(req.getUserNumber());
            op.setProcessDesc("已下单");
            op.setProcessDate(new Date());
            opList.add(op);
            //记录积分变动
            //HsAmassScoreChange hasc = new HsAmassScoreChange();
            //hasc.setChangeDate(new Date());
            //hasc.setAmassScore(req.getOrderTotal());
            //hasc.setChangeType("2");
            //hasc.setUserCode(req.getUserNumber());
            appUserMsg.setMsgTitle("积分兑换成功");
            appUserMsg.setMsgContent(String.valueOf(content));
            appUserMsg.setMsgIsRead("0");
            appUserMsg.setUserCode(req.getUserNumber());
            appUserMsg.setMsgType("6");
            userMsgService.save(appUserMsg);
            //hsAmassScoreChangeService.save(hasc);
            //orderProcessService.saveBatch(opList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("保存失败");
        }
        return AjaxResult.success();
    }

    @Resource
    private IHsGiftTypeService giftTypeService;

    @Resource
    private ISysConfigService sysConfigService;

    /**
     * 获取订单详情
     *
     * @return
     */
    @RequestMapping("/orderInfo")
    @ResponseBody
    public AjaxResult getOrderInfo(String on) {
        HsGiftOrder hco = new HsGiftOrder();
        hco.setOrderNumber(on);
        List<HsGiftOrder> hsGiftOrders = giftOrderService.selectHsCanteenOrderList(hco);
        if (hsGiftOrders == null) {
            return AjaxResult.error();
        }
        return AjaxResult.success(hsGiftOrders.get(0));
    }

    /**
     * 礼品类型
     *
     * @param request
     * @return
     */
    @RequestMapping("/giftType")
    public AjaxResult appSelectHsGiftType(HttpServletRequest request) {
        return AjaxResult.success(giftTypeService.appSelectHsGiftType());
    }

    /**
     * 礼品登记公告
     */
    @GetMapping("/getNotice")
    public AjaxResult getNotice() {
        return AjaxResult.success(sysConfigService.selectConfigByKey("noticeText"));
    }

    /**
     * 公告状态
     */
    @GetMapping("/getNoticeStatus")
    public AjaxResult getNoticeStatus() {
        return AjaxResult.success(sysConfigService.selectConfigByKey("noticeStatus"));
    }

    @Resource
    private IHsUserShopCarService userShopCarService;

    /**
     * 根据用户查询购物车
     *
     * @param request
     * @return
     */
    @RequestMapping("/getUsc")
    public AjaxResult queryShopCarByUser(HttpServletRequest request) {
        return AjaxResult.success(userShopCarService.queryShopCarByUser(request.getHeader("UserName")));
    }

    /**
     * 加入购物车
     *
     * @param userShopCarJsonDoMainVo
     * @return
     */
    @RequestMapping("/addShopCar")
    public AjaxResult addShopCar(@RequestBody UserShopCarJsonDoMainVo userShopCarJsonDoMainVo) {
        return AjaxResult.success(userShopCarService.jsonAdd(userShopCarJsonDoMainVo));
    }

    /**
     * 购物车物品总数
     *
     * @param request
     * @return
     */
    @RequestMapping("/getSCN")
    public AjaxResult getShopCarNum(HttpServletRequest request) {
        return AjaxResult.success(userShopCarService.getShopCarNum(request.getHeader("UserName")));
    }

    @Resource
    private IHsCanteenDiningPlaceService diningPlaceService;

    @RequestMapping("/getGiftReceivePlace")
    public AjaxResult getGiftPlaceOfCollection() {
        return AjaxResult.success(diningPlaceService.getPlaceByConfigKey(IHsCanteenDiningPlaceService.GIFT_PLACE_CONFIG_KEY));
    }
}
