/**
 * @projectName willalp-pns-ml
 * @package com.willalp.web.controller.app
 * @className com.willalp.web.controller.app.AppThreeController
 * @copyright Copyright 2019 HuiShan, Inc All rights reserved.
 */
package com.willalp.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.utils.StringUtils;
import com.willalp.erms.service.IHsGoodsStorageService;
import com.willalp.erms.service.IHsGoodsTypeService;
import com.willalp.event.domain.HsActivityAppoint;
import com.willalp.event.domain.HsEvent;
import com.willalp.event.service.IHsActivityAppointService;
import com.willalp.event.service.IHsAssociationsInfoService;
import com.willalp.event.service.IHsEventService;
import com.willalp.files.service.IHsOrgPersonnelFilesService;
import com.willalp.flow.service.IHsFlowCcService;
import com.willalp.system.service.ISysDeptService;
import com.willalp.system.service.ISysPostService;
import io.swagger.annotations.Api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * AppThreeController
 * @description APP对外接口3
 * @author hs
 * @date 2023/2/6 17:18
 * @version 1.0
 */
@Api("app接口")
@RestController
@RequestMapping("/app")
public class AppThreeController extends BaseController {
    private static final Log LOG = LogFactory.getLog(AppThreeController.class);

    @Resource
    private IHsOrgPersonnelFilesService opfService;

    @Resource
    private IHsFlowCcService flowCcService;

    @Resource
    private IHsGoodsTypeService goodsTypeService;

    @Resource
    private IHsGoodsStorageService goodsStorageService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private IHsEventService eventService;

    @Resource
    private IHsAssociationsInfoService associationsInfoService;

    @Resource
    private IHsActivityAppointService activityAppointService;


    @RequestMapping("/getOpfInfo")
    public AjaxResult getOpfInfo(@RequestParam String opfUserPhone) {
        return AjaxResult.success(opfService.appGetHsOrgPersonnelFilesByPhone(opfUserPhone));
    }

    @RequestMapping("/ccRecord")
    public TableDataInfo getCcRecord(HttpServletRequest request) {
        startPage();
        return getDataTable(flowCcService.selectHsFlowCcListByUserId(request.getHeader("UserName")));
    }

    @RequestMapping("/sendTestMsg")
    public void testSendWebSocketMsg(HttpServletRequest request) {
//        WebSocketUsers.sendMessageToUserByText(WebSocketUsers.getUsers().get("admin"), "user-name");
    }

    @RequestMapping("/goodsType")
    public AjaxResult getGoodsType(String type) {
        return AjaxResult.success(goodsTypeService.appGetGoodsType(type));
    }

    @RequestMapping("/goodses")
    public AjaxResult goodses(String type, String name) {
        return AjaxResult.success(goodsStorageService.appGetGoodsByType(type, name));
    }

    @RequestMapping("/deptInfo")
    public AjaxResult deptInfo(String id) {
        return AjaxResult.success(deptService.selectChildrenDeptByParentId(id));
    }

    @Resource
    private ISysPostService postService;

    @RequestMapping("/posts")
    public AjaxResult getPosts() {
        return AjaxResult.success(postService.selectPostAll());
    }

    @RequestMapping("/clubs")
    public AjaxResult clubs() {
        return AjaxResult.success(associationsInfoService.appGetClubs(getUsername()));
    }

    @RequestMapping("/events")
    public TableDataInfo events(String associationsInfoId) {
        startPage();
        return getDataTable(eventService.appGetEvents(associationsInfoId));
    }

    @RequestMapping("/eventOrders")
    public TableDataInfo eventOrders() {
        startPage();
        return getDataTable(activityAppointService.appGetRecord(getUsername()));
    }

    @RequestMapping("/more")
    public AjaxResult more(String eventId) {
        return AjaxResult.success(eventService.appGetMoreById(eventId));
    }

    @RequestMapping("/eventOrder")
    public AjaxResult eventOrder(String eventId) {
        if (StringUtils.isBlank(eventId)) {
            return AjaxResult.error("预约失败");
        }
        HsEvent hsEvent = eventService.getById(eventId);
        if (hsEvent == null) {
            return AjaxResult.error("活动不存在或已经结束");
        }

        //限额验证
        Integer count = Math.toIntExact(activityAppointService.getBaseMapper().selectCount(new QueryWrapper<HsActivityAppoint>()
                .eq("activity_id", eventId)
                .eq("create_by", getUsername())));
        Integer sum = Math.toIntExact(activityAppointService.getBaseMapper().selectCount(new QueryWrapper<HsActivityAppoint>()
                .eq("activity_id", eventId)));
        if (count > 0) {
            return AjaxResult.error("您已经预约过了，不能重复预约");
        }
        if (sum < hsEvent.getLimitNum()) {
            HsActivityAppoint activityAppoint = new HsActivityAppoint();
            activityAppoint.setActivityId(eventId);
            SysUser user = getLoginUser().getUser();
            if (user == null) {
                return AjaxResult.error("预约失败");
            }
            activityAppoint.setAppointeeName(user.getNickName());
            activityAppoint.setAppointeePhone(user.getPhonenumber());
            activityAppoint.setCreateBy(user.getUserName());
            activityAppoint.setAppointmentTime(new Date());
            activityAppoint.setActivityTime(hsEvent.getEventStartTime());
            activityAppoint.setCreateTime(new Date());
            return AjaxResult.success(activityAppointService.save(activityAppoint));
        } else {
            return AjaxResult.error("名额已满");
        }
    }

    @RequestMapping("/backEventOrder")
    public AjaxResult backEventOrder(String id) {
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error("取消失败");
        }
        HsActivityAppoint appointServiceById = activityAppointService.getById(id);
        if (appointServiceById != null && StringUtils.isNotBlank(appointServiceById.getActivityId())) {
            HsEvent hsEvent = eventService.getById(appointServiceById.getActivityId());
            if (hsEvent == null) {
                return AjaxResult.error("活动不存在或已经结束");
            }
            //时间验证
            Date eventEndTime = hsEvent.getEventEndTime();
            //禁止取消预约时限
            Integer banCancelSubscribeTimeLimit = hsEvent.getBanCancelSubscribeTimeLimit();
            Integer limitNum = hsEvent.getLimitNum();
            long msTime = banCancelSubscribeTimeLimit * (1000 * 60 * 60);
            long timeMillis = System.currentTimeMillis();
            msTime = eventEndTime.getTime() - msTime;
            if (timeMillis < msTime && hsEvent.getLimitNum() > 0) {
                return toAjax(activityAppointService.removeById(id));
            } else {
                return AjaxResult.error("已过可退时间");
            }
        }
        return AjaxResult.error("取消失败");
    }
}
 