package com.tourism.webadmin.app.website.controller;

import com.tourism.common.additional.config.ApplicationConfig;
import com.tourism.common.additional.utils.StringUtils;
import com.tourism.common.additional.utils.UrlConvertUtils;
import com.tourism.common.core.annotation.MyRequestBody;
import com.tourism.common.core.constant.ErrorCodeEnum;
import com.tourism.common.core.object.*;
import com.tourism.common.core.util.MyCommonUtil;
import com.tourism.common.core.util.MyModelUtil;
import com.tourism.common.core.util.MyPageUtil;
import com.tourism.common.log.annotation.OperationLog;
import com.tourism.common.log.model.constant.SysOperationLogType;
import com.tourism.webadmin.app.website.vo.WebSiteTourNoticeVo;
import com.tourism.webadmin.back.dto.TourNoticeDto;
import com.tourism.webadmin.back.model.TourNotice;
import com.tourism.webadmin.back.model.TourUser;
import com.tourism.webadmin.back.model.TourismProjectTravelNotesWrite;
import com.tourism.webadmin.back.model.constant.TourBeenRead;
import com.tourism.webadmin.back.service.TourNoticeService;
import com.tourism.webadmin.back.service.TourUserService;
import com.tourism.webadmin.back.service.TourismProjectTravelNotesWriteService;
import com.tourism.webadmin.back.vo.TourNoticeVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.tourism.webadmin.app.model.constant.TourNoticeType;

import java.util.ArrayList;
import java.util.List;

/**
 * 个人消息。
 *
 * @author chenchen
 * @date 2024-11-20
 */
@Tag(name = "个人消息接口")
@Slf4j
@RestController
@RequestMapping("/website/tourism/tourNotice")
public class TourNoticeController {

    @Autowired
    private TourNoticeService tourNoticeService;
    @Autowired
    private TourUserService tourUserService;
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TourismProjectTravelNotesWriteService tourismProjectTravelNotesWriteService;

    /**
     * 个人未读消息数量(总)。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/unreadNoticeCount")
    public ResponseResult<Long> UnreadNoticeCount() {

        TourNotice tourNotice = new TourNotice();
        Long userId = TokenData.takeFromRequest().getUserId();
        tourNotice.setUserId(userId);
        //0未读；1已读
        tourNotice.setBeenRead(TourBeenRead.UNREAD);
        long count = tourNoticeService.getCountByFilter(tourNotice);
        return ResponseResult.success(count);
    }

    /**
     *  个人消息列表(noticeType 消息类型：1消息回复；2收藏提醒；3游记审核)。
     *  param type 消息类型：1系统消息 2互动消息
     *  type:1=====>noticeType:1消息回复；2收藏提醒；type:2===========>3游记审核
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.LIST)
    @GetMapping("/noticeList")
    public ResponseResult<MyPageData<WebSiteTourNoticeVo>> noticeList(@RequestParam("noticeType") Integer type) {

        TourNotice tourNotice = new TourNotice();
        Long userId = TokenData.takeFromRequest().getUserId();
        tourNotice.setUserId(userId);
        List<Integer> noticeTypeList = new ArrayList<>();
        if(type.equals(1)){
            noticeTypeList.add(1);
            noticeTypeList.add(2);
        }else if(type.equals(2)){
            noticeTypeList.add(3);
        }
        tourNotice.setNoticeTypeList(noticeTypeList);

        MyOrderParam myOrderParam = new MyOrderParam();
        myOrderParam.add(new MyOrderParam.OrderInfo("sendTime",false,null));
        myOrderParam.add(new MyOrderParam.OrderInfo("beenRead",false,null));
        String orderBy = MyOrderParam.buildOrderBy(myOrderParam, TourNotice.class);
        List<TourNotice> tourNoticeList = tourNoticeService.getTourNoticeListWithRelation(tourNotice, orderBy);

        MyPageData<WebSiteTourNoticeVo> tourNoticeMyPageData = MyPageUtil.makeResponseData(tourNoticeList, WebSiteTourNoticeVo.class);

        List<WebSiteTourNoticeVo> dataList = tourNoticeMyPageData.getDataList();
        for(WebSiteTourNoticeVo item:dataList){
            if(item.getNoticeType().equals(TourNoticeType.NOTICE_REPLY)){
                item.setNoticeTitle("回复了我的评论");
            }else if(item.getNoticeType().equals(TourNoticeType.COLLECTION_REMINDER)){
                item.setNoticeTitle("收藏了我的游记");
            }else if(item.getNoticeType().equals(TourNoticeType.TRAVEL_REVIEW)){

            }
            //关联头像不为空的话
            if(item.getCreateUserIdHeadImageUrlDictMap().get(String.valueOf(item.getCreateUserId())) != null){
                String headImageUrlConvertSingle = UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), (String) item.getCreateUserIdHeadImageUrlDictMap().get(String.valueOf(item.getCreateUserId())));
                item.setHeadImageUrl(headImageUrlConvertSingle);
            }else {
                //赋值默认头像
                item.setHeadImageUrl(applicationConfig.getDefaultAvatar());
            }
            //完善游记信息
            TourismProjectTravelNotesWrite tourismProjectTravelNotesWrite = tourismProjectTravelNotesWriteService.getById(item.getRelationId());
            item.setProjectTitle(tourismProjectTravelNotesWrite.getProjectTitle());

            String tourismUrlConvertSingle = UrlConvertUtils.urlConvertSingle(applicationConfig.getHostIpPort(), tourismProjectTravelNotesWrite.getTourismUrl());
            item.setTourismUrlsAfterConvert(tourismUrlConvertSingle);
        }

        return ResponseResult.success(tourNoticeMyPageData);
    }

    /**
     *  个人消息单条已读。
     *  param noticeId 消息id
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/noticeReadById")
    public ResponseResult<Void> noticeReadAll(@RequestParam("noticeId") String noticeId) {

        TourNotice tourNotice = new TourNotice();
        tourNotice.setId(Long.valueOf(noticeId));
        tourNotice.setBeenRead(TourBeenRead.READ);
        tourNoticeService.updateById(tourNotice);
        return ResponseResult.success();
    }

    /**
     *  个人消息全部已读(noticeType 消息类型：1消息回复；2收藏提醒；3游记审核)。
     *  param noticeType 消息类型：1消息回复；2收藏提醒；3游记审核。
     * @return 应答结果对象，包含查询结果集。
     */
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/noticeReadAll")
    public ResponseResult<Void> noticeReadAll(@RequestParam("noticeType") Integer noticeType) {

        TourNotice tourNotice = new TourNotice();
        tourNotice.setUserId(TokenData.takeFromRequest().getUserId());
        tourNotice.setNoticeType(noticeType);
        tourNotice.setBeenRead(TourBeenRead.UNREAD);
        List<TourNotice> tourNoticeList = tourNoticeService.getTourNoticeList(tourNotice, "");

        for (TourNotice notice : tourNoticeList) {
            notice.setBeenRead(TourBeenRead.READ);
            tourNoticeService.updateById(notice);
        }
        return ResponseResult.success();
    }

    //1.消息回复；2收藏提醒；3游记审核(新增消息表中的记录)

    /**
     * 新增消息通知表数据。
     *
     * @param tourNoticeDto 新增对象。  relationId为游记id
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody TourNoticeDto tourNoticeDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(tourNoticeDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        //类型为消息回复时,commentId必传
        if(tourNoticeDto.getNoticeType().equals(TourNoticeType.NOTICE_REPLY)){
            if(tourNoticeDto.getCommentId() == null){
                return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "消息回复时，回复的哪条评论的id必传");
            }
        }
        TourNotice tourNotice = MyModelUtil.copyTo(tourNoticeDto, TourNotice.class);
        // 验证关联Id的数据合法性
        CallResult callResult = tourNoticeService.verifyRelatedData(tourNotice, null);
        if (!callResult.isSuccess()) {
            return ResponseResult.errorFrom(callResult);
        }
        tourNotice = tourNoticeService.saveNew(tourNotice);
        return ResponseResult.success(tourNotice.getId());
    }


}
