/**
 * @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.config.WillalpConfig;
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.common.utils.file.FileUploadUtils;
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.domain.HsEventImg;
import com.willalp.event.domain.HsWelfareApplyRecord;
import com.willalp.event.service.*;
import com.willalp.files.service.IHsOrgPersonnelFilesService;
import com.willalp.flow.service.IHsFlowCcService;
import com.willalp.msg.service.IHsAppUserMsgService;
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.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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;

    @Resource
    private IHsEventImgService eventImgService;

    @Resource
    private IHsWelfareApplyRecordService welfareApplyRecordService;

    @Resource
    private IHsAppUserMsgService userMsgService;

    /**
     * 全部已读
     *
     * @return
     */
    @RequestMapping("/doAllRead")
    public AjaxResult doAllRead() {
        userMsgService.doAllRead(getUsername());
        return AjaxResult.success();
    }

    /**
     * 员工档案信息
     *
     * @param opfUserPhone
     * @return
     */
    @RequestMapping("/getOpfInfo")
    public AjaxResult getOpfInfo(@RequestParam String opfUserPhone) {
        return AjaxResult.success(opfService.appGetHsOrgPersonnelFilesByPhone(opfUserPhone));
    }

    /**
     * 抄送记录
     *
     * @param request
     * @return
     */
    @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");
    }

    /**
     * 物资分类
     *
     * @param type
     * @return
     */
    @RequestMapping("/goodsType")
    public AjaxResult getGoodsType(String type) {
        return AjaxResult.success(goodsTypeService.appGetGoodsType(type));
    }

    /**
     * 物资库信息
     *
     * @param type
     * @param name
     * @return
     */
    @RequestMapping("/goodses")
    public AjaxResult goodses(String type, String name) {
        return AjaxResult.success(goodsStorageService.appGetGoodsByType(type, name));
    }

    /**
     * 所有部门信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/deptInfo")
    public AjaxResult deptInfo(String id) {
        return AjaxResult.success(deptService.selectChildrenDeptByParentId(id));
    }

    @Resource
    private ISysPostService postService;

    /**
     * 所有岗位
     *
     * @return
     */
    @RequestMapping("/posts")
    public AjaxResult getPosts() {
        return AjaxResult.success(postService.selectPostAll());
    }

    /**
     * 社团（项目）列表
     *
     * @return
     */
    @RequestMapping("/clubs")
    public AjaxResult clubs() {
        return AjaxResult.success(associationsInfoService.appGetClubs(getUsername()));
    }

    /**
     * 活动列表
     *
     * @param associationsInfoId
     * @return
     */
    @RequestMapping("/events")
    public TableDataInfo events(String associationsInfoId) {
        startPage();
        return getDataTable(eventService.appGetEvents(associationsInfoId));
    }


    /**
     * 上传地址
     */
    @Value("${imgServer.url}")
    public String baseUrl;

    /**
     * 活动风采上传
     */
    @PostMapping("/eventImg/upload")
    public AjaxResult uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {
        try {
            // 上传文件路径
            String filePath = WillalpConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = file.getOriginalFilename();
            String url = FileUploadUtils.upload(filePath, file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", baseUrl + url);
            HsEventImg eventImg = new HsEventImg();
            eventImg.setEventId(request.getHeader("eventId"));
            eventImg.setType(fileName.split("\\.")[1]);
            eventImg.setUrl(baseUrl + url);
            eventImg.setCreateTime(new Date());
            eventImgService.save(eventImg);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 活动风采
     *
     * @param eventId
     * @return
     */
    @RequestMapping("/eventsImg")
    public AjaxResult eventsImg(String eventId) {
        if (StringUtils.isBlank(eventId)) {
            return AjaxResult.error();
        }
        return AjaxResult.success(eventImgService.getBaseMapper().selectList(new QueryWrapper<HsEventImg>()
                .eq("event_id", eventId).orderByDesc("create_time")));
    }


    /**
     * 活动预约记录
     *
     * @return
     */
    @RequestMapping("/eventOrders")
    public TableDataInfo eventOrders() {
        startPage();
        return getDataTable(activityAppointService.appGetRecord(getUsername()));
    }

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

    /**
     * 预约社团活动操作
     *
     * @param eventId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @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("活动不存在或已经结束");
        }
        if ("3".equals(hsEvent.getEventStatus())) {
            return AjaxResult.error("活动进行中，已无法预约");
        }
        if ("4".equals(hsEvent.getEventStatus())) {
            return AjaxResult.error("活动已结束");
        }
        //限额验证
        int count = Math.toIntExact(activityAppointService.getBaseMapper().selectCount(new QueryWrapper<HsActivityAppoint>()
                .eq("activity_id", eventId)
                .eq("create_by", getUsername())));
        if (count > 0) {
            return AjaxResult.error("您已经预约过了，不能重复预约");
        }
        //更新预约数量
        if (eventService.eventAppointOrder(eventId) > 0) {
            //生成预约记录
            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 {
            int sum = Math.toIntExact(activityAppointService.getBaseMapper().selectCount(new QueryWrapper<HsActivityAppoint>()
                    .eq("activity_id", eventId)));
            if (sum == hsEvent.getLimitNum()) {
                return AjaxResult.error("名额已满");
            }
            return AjaxResult.error("预约失败，请联系管理员");
        }
    }

    /**
     * 社团预约 取消预约操作
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @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 eventStartTime = hsEvent.getEventStartTime();
            //禁止取消预约时限
            Integer banCancelSubscribeTimeLimit = hsEvent.getBanCancelSubscribeTimeLimit();
            long msTime = banCancelSubscribeTimeLimit * (1000 * 60 * 60);
            long timeMillis = System.currentTimeMillis();
            msTime = eventStartTime.getTime() - msTime;
            if ("3".equals(hsEvent.getEventStatus())) {
                return AjaxResult.error("活动进行中，无法取消预约");
            }
            if ("4".equals(hsEvent.getEventStatus())) {
                return AjaxResult.error("活动已结束，无法取消预约");
            }
            if (timeMillis < msTime) {
                //更新预约数量
                if (eventService.eventAppointBack(hsEvent.getId()) > 0) {
                    //删除预约记录
                    return toAjax(activityAppointService.removeById(id));
                } else {
                    return AjaxResult.error("取消失败，请联系管理员");
                }
            } else {
                return AjaxResult.error("已过可退时间");
            }
        }
        return AjaxResult.error("取消失败");
    }

    /*福利领取部分*/

    /**
     * 查询可领取的福利列表
     *
     * @return
     */
    @RequestMapping("/welfareOrders")
    public TableDataInfo welfareOrders() {
        startPage();
        return getDataTable(welfareApplyRecordService.list(new QueryWrapper<HsWelfareApplyRecord>()
                .eq("user_code", getUsername())
                .groupBy("source")));
    }

    /**
     * 福利领取报名操作
     *
     * @param welfareApplyRecord
     * @return
     */
    @RequestMapping("/sumbitWelfare")
    public AjaxResult submitWelfare(@RequestBody HsWelfareApplyRecord welfareApplyRecord) {
        if (null == welfareApplyRecord) {
            return AjaxResult.error();
        }
        if (StringUtils.isBlank(welfareApplyRecord.getId())) {
            return AjaxResult.error();
        }
        HsWelfareApplyRecord applyRecord = welfareApplyRecordService.getById(welfareApplyRecord.getId());
        if ("2".equals(applyRecord.getNowStatus())) {
            return AjaxResult.error("不可重复报名");
        }
        welfareApplyRecord.setNowStatus("2");
        return toAjax(welfareApplyRecordService.updateById(welfareApplyRecord));
    }

    /**
     * 报名数据回显
     *
     * @param id
     * @return
     */
    @RequestMapping("/getApplyData")
    public AjaxResult getApplyData(String id) {
        if (StringUtils.isBlank(id)) {
            return AjaxResult.error();
        }
        HsWelfareApplyRecord welfareApplyRecord = welfareApplyRecordService.getById(id);
        if (null == welfareApplyRecord) {
            return AjaxResult.error();
        }
        return AjaxResult.success(welfareApplyRecord);
    }

}
 