package com.ruoyi.web.modules.booking.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.modules.booking.domain.AppMyAppointmentQuery;
import com.ruoyi.web.modules.booking.domain.AppMyAppointmentReviewBody;
import com.ruoyi.web.modules.booking.service.IAppMyAppointmentService;
import com.ruoyi.web.modules.booking.support.AppBookingPageSupport;
import com.ruoyi.web.modules.booking.support.AppMyAppointmentQuerySupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 移动端我的预约。
 */
@RestController
@RequestMapping("/app/myAppointment")
public class BizAppMyAppointmentController extends BaseController
{
    @Autowired
    private IAppMyAppointmentService appMyAppointmentService;

    /**
     * 当前用户的预约列表（按 providerType、statusTab 筛选）。
     */
    @GetMapping("/list")
    public TableDataInfo list(AppMyAppointmentQuery query)
    {
        AppMyAppointmentQuery effective = AppMyAppointmentQuerySupport.normalize(query,
                SecurityUtils.getUsername());
        AppBookingPageSupport.startPage(effective.getPageNum(), effective.getPageSize());
        return getDataTable(appMyAppointmentService.selectMyAppointmentList(effective));
    }

    /**
     * 取消预约（已完成不可取消）。
     */
    @Log(title = "移动端取消预约", businessType = BusinessType.UPDATE)
    @PostMapping("/cancel/{id}")
    public AjaxResult cancel(@PathVariable("id") Long id)
    {
        return toAjax(appMyAppointmentService.cancelAppointment(id, SecurityUtils.getUsername(),
                SecurityUtils.getUsername()));
    }

    /**
     * 查看本次预约评价（专家、已完成）。
     */
    @GetMapping("/{id}/review")
    public AjaxResult getReview(@PathVariable("id") Long id)
    {
        return success(appMyAppointmentService.selectAppointmentReview(id, SecurityUtils.getUsername()));
    }

    /**
     * 提交评价（专家、已完成）；仅写入评价表，expert_rating 由每日 23:00 定时任务更新。
     */
    @Log(title = "移动端提交预约评价", businessType = BusinessType.INSERT)
    @PostMapping("/{id}/review")
    public AjaxResult submitReview(@PathVariable("id") Long id, @RequestBody AppMyAppointmentReviewBody body)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String reviewerName = user.getNickName() != null ? user.getNickName() : user.getUserName();
        Long reviewId = appMyAppointmentService.submitAppointmentReview(id, body, SecurityUtils.getUsername(),
                reviewerName);
        return success(reviewId);
    }
}
