package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LawyerUser;
import shop.alien.entity.store.vo.LawyerUserLogoutListVo;
import shop.alien.entity.store.vo.LawyerUserVo;
import shop.alien.store.service.LawyerUserService;
import shop.alien.util.myBaticsPlus.QueryBuilder;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 律师用户 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"律师平台-律师用户"})
@ApiSort(10)
@CrossOrigin
@RestController
@RequestMapping("/lawyer/user")
@RequiredArgsConstructor
public class LawyerUserController {

    private final LawyerUserService lawyerUserService;

    @ApiOperation("新增律师用户")
    @ApiOperationSupport(order = 1)
    @PostMapping("/addLawyerUser")
    public R<LawyerUser> addLawyerUser(@RequestBody LawyerUser lawyerUser) {
        log.info("LawyerUserController.addLawyerUser?lawyerUser={}", lawyerUser);
        return lawyerUserService.addLawyerUser(lawyerUser);
    }

    @ApiOperation("编辑律师用户")
    @ApiOperationSupport(order = 2)
    @PostMapping("/editLawyerUser")
    public R<LawyerUser> editLawyerUser(@RequestBody LawyerUser lawyerUser) {
        log.info("LawyerUserController.editLawyerUser?lawyerUser={}", lawyerUser);
        return lawyerUserService.editLawyerUser(lawyerUser);
    }

    @ApiOperation("删除律师用户")
    @ApiOperationSupport(order = 3)
    @DeleteMapping("/deleteLawyerUser")
    public R<Boolean> deleteLawyerUser(@RequestParam(value = "id") Integer id) {
        log.info("LawyerUserController.deleteLawyerUser?id={}", id);
        return lawyerUserService.deleteLawyerUser(id);
    }

    @ApiOperation("保存或更新律师用户")
    @ApiOperationSupport(order = 4)
    @PostMapping("/saveOrUpdate")
    public R<LawyerUser> saveOrUpdate(@RequestBody LawyerUser lawyerUser) {
        log.info("LawyerUserController.saveOrUpdate?lawyerUser={}", lawyerUser);
        boolean result = lawyerUserService.saveOrUpdate(lawyerUser);
        if (result) {
            return R.data(lawyerUser);
        }
        return R.fail("操作失败");
    }

    @ApiOperation("通用列表查询")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "用户状态, 0:禁用, 1:启用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "certificationStatus", value = "资质认证状态, 0:未认证, 1:认证中, 2:已认证, 3:认证失败", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getList")
    public R<List<LawyerUser>> getList(@ModelAttribute LawyerUser lawyerUser) {
        log.info("LawyerUserController.getList?lawyerUser={}", lawyerUser);
        List<LawyerUser> list = QueryBuilder.of(lawyerUser)
                .likeFields("name", "phone")  // 姓名和手机号支持模糊查询
                .build()
                .list(lawyerUserService);
        return R.data(list);
    }

    @ApiOperation("通用分页查询")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页容（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "主键", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号（支持模糊查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "用户状态, 0:禁用, 1:启用", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "certificationStatus", value = "资质认证状态, 0:未认证, 1:认证中, 2:已认证, 3:认证失败", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_Start", value = "创建时间开始（范围查询）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "createdTime_End", value = "创建时间结束（范围查询）", dataType = "String", paramType = "query")
    })
    @GetMapping("/getPage")
    public R<IPage<LawyerUser>> getPage(@ModelAttribute LawyerUser lawyerUser,
                                         @RequestParam(defaultValue = "1") int page,
                                         @RequestParam(defaultValue = "10") int size) {
        log.info("LawyerUserController.getPage?lawyerUser={},page={},size={}", lawyerUser, page, size);
        int pageNum = page > 0 ? page : 1;
        int pageSize = size > 0 ? size : 10;
        IPage<LawyerUser> pageResult = QueryBuilder.of(lawyerUser)
                .likeFields("name", "phone")  // 姓名和手机号支持模糊查询
                .page(pageNum, pageSize)
                .build()
                .page(lawyerUserService);
        return R.data(pageResult);
    }

    @ApiOperation("获取律师详情")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawyerId", value = "律师ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/detail")
    public R<Map<String, Object>> getLawyerDetail(@RequestParam Integer lawyerId) {
        log.info("LawyerUserController.getLawyerDetail?lawyerId={}", lawyerId);
        return lawyerUserService.getLawyerDetail(lawyerId);
    }

    @ApiOperation("获取律师在线状态")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lawyerIds", value = "律师ID数组（逗号分隔）", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/onlineStatus")
    public R<Map<Integer, Boolean>> getLawyerOnlineStatus(@RequestParam String lawyerIds) {
        log.info("LawyerUserController.getLawyerOnlineStatus?lawyerIds={}", lawyerIds);
        return lawyerUserService.getLawyerOnlineStatus(lawyerIds);
    }

    @ApiOperation("获取推荐律师列表")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "分类ID（可选）", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/recommend/list")
    public R<IPage<LawyerUser>> getRecommendedLawyerList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer categoryId) {
        log.info("LawyerUserController.getRecommendedLawyerList?page={},pageSize={},categoryId={}",
                page, pageSize, categoryId);
        return lawyerUserService.getRecommendedLawyerList(page, pageSize, categoryId);
    }

    @ApiOperation("根据会话获取推荐律师列表")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionId", value = "会话ID", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "messageId", value = "消息ID（可选）", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/recommend/bySession")
    public R<IPage<LawyerUser>> getRecommendedLawyersBySession(
            @RequestParam String sessionId,
            @RequestParam(required = false) Integer messageId) {
        log.info("LawyerUserController.getRecommendedLawyersBySession?sessionId={},messageId={}", sessionId, messageId);
        return lawyerUserService.getRecommendedLawyersBySession(sessionId, messageId);
    }

    @ApiOperation("通过昵称模糊查询律师（并保存搜索历史）")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "律师昵称（支持模糊查询，为空时返回所有律师）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "page", value = "页码（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量（默认10）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "clientUserId", value = "客户端用户ID（可选，用于保存搜索历史）", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/searchByName")
    public R<IPage<LawyerUser>> searchLawyerByName(
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer clientUserId) {
        log.info("LawyerUserController.searchLawyerByName?name={},page={},pageSize={},clientUserId={}", name, page, pageSize, clientUserId);
        return lawyerUserService.searchLawyerByName(name, page, pageSize, clientUserId);
    }


    @ApiOperation("根据AI返回场景获取推荐律师列表")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数量（默认5）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "categoryId", value = "场景ID（必传）", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/aiRecommendList")
    public R<IPage<LawyerUser>> getAiRecommendList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "5") int size,
            @RequestParam(required = true) Integer categoryId) {
        log.info("LawyerUserController.aiRecommendList?page={},pageSize={},categoryId={}",
                page, size, categoryId);
        return lawyerUserService.getAiRecommendList(page, size, categoryId);
    }

    @ApiOperation("中台律师列表")
    @ApiOperationSupport(order = 17)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名（支持模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "phone", value = "手机号（支持模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "firmId", value = "律所ID", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "practiceStartDate", value = "从业时间", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "startTime", value = "开始日期（用于查询执业开始日期practice_start_date，格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endTime", value = "结束日期（用于查询执业开始日期practice_start_date，格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "page", value = "页码（默认1）", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数量（默认10）", dataType = "int", paramType = "query")
    })
    @GetMapping("/getLawyerList")
    public R<IPage<LawyerUserVo>> getLawyerList(@RequestParam(required = false) String name,
                                                @RequestParam(required = false) String phone,
                                                @RequestParam(required = false) String practiceStartDate,
                                                @RequestParam(required = false) Integer firmId,
                                                @RequestParam(required = false) String startTime,
                                                @RequestParam(required = false) String endTime,
                                                @RequestParam int page,
                                                @RequestParam int size) {
        log.info("LawyerUserController.getLawyerList?name={},phone={},practiceStartDate={},firmId={},startTime={},endTime={},page={},size={}",
                name, phone, practiceStartDate, firmId, startTime, endTime, page, size);
        return lawyerUserService.getLawyerList(name, phone, practiceStartDate, firmId, startTime, endTime, page, size);
    }

    @ApiOperation(value = "律师注销列表", notes = "中台系统管理-律师管理-律师注销数据，数据源 lawyer_user")
    @ApiOperationSupport(order = 18)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "int", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "name", value = "律师姓名（lawyer_user.name）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "logoutFlag", value = "注销标记：1已注销，2注销冷静期", dataType = "int", paramType = "query")
    })
    @GetMapping("/lawyer_user")
    public R<IPage<LawyerUserLogoutListVo>> getLawyerUserLogoutPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer logoutFlag) {
        log.info("LawyerUserController.getLawyerUserLogoutPage?pageNum={},pageSize={},name={},phone={},logoutFlag={}",
                pageNum, pageSize, name, phone, logoutFlag);
        return R.data(lawyerUserService.getLawyerUserLogoutPage(pageNum, pageSize, name, phone, logoutFlag));
    }

    @ApiOperation("导出中台律师列表")
    @ApiOperationSupport(order = 19)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名（支持模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "phone", value = "手机号（支持模糊查询）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "firmId", value = "律所ID", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "startTime", value = "开始日期（用于查询执业开始日期practice_start_date，格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endTime", value = "结束日期（用于查询执业开始日期practice_start_date，格式：yyyy-MM-dd）", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "pageNum", value = "页码（可选，不传或传0则导出全部，传值则导出本页）", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页容（可选，与pageNum配合使用）", dataType = "Integer", paramType = "query")
    })
    @GetMapping(value = "/exportLawyerList", produces = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    public void exportLawyerList(
            HttpServletResponse response,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String practiceStartDate,
            @RequestParam(required = false) Integer firmId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize) throws Exception {
        log.info("LawyerUserController.exportLawyerList?name={},phone={},practiceStartDate={},firmId={},startTime={},endTime={},pageNum={},pageSize={}",
                name, phone, firmId, startTime, endTime, pageNum, pageSize);
        try {
            lawyerUserService.exportLawyerList(response, name, phone, practiceStartDate, firmId, startTime, endTime, pageNum, pageSize);
        } catch (Exception e) {
            log.error("导出律师列表异常", e);
            if (!response.isCommitted()) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
            }
            throw e;
        }
    }

}

