package com.yd.csf.api.controller;

import com.yd.auth.core.dto.AuthUserDto;
import com.yd.auth.core.utils.SecurityUtil;
import com.yd.common.enums.CommonEnum;
import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.common.utils.RandomStringGenerator;
import com.yd.csf.service.dto.FnaFormAddRequest;
import com.yd.csf.service.dto.FnaFormUpdateRequest;
import com.yd.csf.service.enums.FnaStatusEnum;
import com.yd.csf.service.model.Fna;
import com.yd.csf.service.model.FnaForm;
import com.yd.csf.service.service.FnaFormService;
import com.yd.csf.service.service.FnaService;
import com.yd.csf.service.vo.FnaFormVO;
import com.yd.user.feign.client.sysuser.ApiSysUserFeignClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Fna表单接口
 *
 * @author jianan
 * @since 2025-08-31
 */
@RestController
@RequestMapping("/FnaForm")
@Tag(name = "Fna表单接口")
public class ApiFnaFormController {

    @Resource
    private FnaFormService fnaFormService;

    @Resource
    private ApiSysUserFeignClient apiSysUserFeignClient;

    @Resource
    private FnaService fnaService;

    /**
     * 创建 Fna表单
     *
     * @param fnaFormAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> addFnaForm(@RequestBody FnaFormAddRequest fnaFormAddRequest, HttpServletRequest request) {

        if (fnaFormAddRequest == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMessage());
        }
        String saveType = fnaFormAddRequest.getSaveType();
        if (StringUtils.isBlank(saveType)) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), "保存方式必传");
        }

        // 转换为数据库实体
        FnaForm fnaForm = fnaFormService.getFnaForm(fnaFormAddRequest);
        // 表单状态
        fnaForm.setFnaFormStatus("save".equals(saveType)? "1" : "0");
        // Fna 状态
        fnaService.lambdaUpdate()
                .set(Fna::getStatus, "save".equals(saveType)? FnaStatusEnum.APPOINTMENT_FILLING.getItemValue() : FnaStatusEnum.FNA_FILLING.getItemValue())
                .eq(Fna::getFnaFormBizId, fnaForm.getFnaFormBizId())
                .update();

        // 获取Security上下文当前用户的登录信息
        AuthUserDto authUserDto = SecurityUtil.getCurrentLoginUser();
        String userBizId = authUserDto.getUserBizId();

        fnaForm.setUserBizId(userBizId);
        fnaForm.setFnaFormBizId(RandomStringGenerator.generateBizId16(CommonEnum.UID_TYPE_FNA_FORM.getCode()));

        fnaForm.setCreatorId(userBizId);
        fnaForm.setUpdaterId(userBizId);
        // 写入数据库
        boolean result = fnaFormService.save(fnaForm);
        if (!result) {
            return Result.fail(ResultCode.FAIL.getCode(), ResultCode.FAIL.getMessage());
        }

        // 返回新写入的数据 id
        String newFnaFormId = fnaForm.getFnaFormBizId();
        Map<String, Object> map = new HashMap<>();
        map.put("fnaFormBizId", newFnaFormId);
        return Result.success(map);
    }

    /**
     * 删除fna
     *
     * @param deleteRequest
     * @param request
     * @return
     */
//    @PostMapping("/delete")
//    public Result<Boolean> deleteFna(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BusinessException(ResultCode.PARAMS_ERROR);
//        }
//        User user = userService.getLoginUser(request);
//        long id = deleteRequest.getId();
//        // 判断是否存在
//        FnaForm oldFna = fnaFormService.getById(id);
//        ThrowUtils.throwIf(oldFna == null, ResultCode.NULL_ERROR);
//        // 仅本人或管理员可删除
//        if (!oldFna.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
//            throw new BusinessException(ResultCode.NO_AUTH_ERROR);
//        }
//        // 操作数据库
//        boolean result = fnaFormService.removeById(id);
//        ThrowUtils.throwIf(!result, ResultCode.FAIL);
//        return Result.success(true);
//    }

    /**
     * 更新 Fna表单
     *
     * @param fnaUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "更新 Fna表单")
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> updateFnaForm(@RequestBody FnaFormUpdateRequest fnaUpdateRequest) {
        if (fnaUpdateRequest == null || StringUtils.isBlank(fnaUpdateRequest.getFnaFormBizId())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMessage());
        }
        String saveType = fnaUpdateRequest.getSaveType();
        if (StringUtils.isBlank(saveType)) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), "保存方式必传");
        }
        // 判断是否存在
        String fnaFormBizId = fnaUpdateRequest.getFnaFormBizId();
        FnaForm oldFna = fnaFormService.getByFnaFormBizId(fnaFormBizId);
        if (oldFna == null) {
            return Result.fail(ResultCode.NULL_ERROR.getCode(), ResultCode.NULL_ERROR.getMessage());
        }

        // 转换为数据库实体
        FnaForm fnaForm = fnaFormService.getFnaForm(fnaUpdateRequest);
        BeanUtils.copyProperties(fnaForm, oldFna, "id", "fnaFormBizId", "userBizId", "agentBizId", "customerBizId", "creatorId", "updaterId");
        // 表单状态
        oldFna.setFnaFormStatus("save".equals(saveType)? "1" : "0");
        // 操作数据库
        boolean result = fnaFormService.updateById(oldFna);
        if (!result) {
            return Result.fail(ResultCode.FAIL.getCode(), ResultCode.FAIL.getMessage());
        }

        // 如果是保存（非暂存），则更新关联的FNA状态为"预约资料填写"
        fnaService.lambdaUpdate()
                .set(Fna::getStatus, "save".equals(saveType)? FnaStatusEnum.APPOINTMENT_FILLING.getItemValue() : FnaStatusEnum.FNA_FILLING.getItemValue())
                .eq(Fna::getFnaFormBizId, fnaForm.getFnaFormBizId())
                .update();

        return Result.success(true);
    }

    /**
     * 根据 fnaFormBizId 获取fna表单（封装类）
     *
     * @param fnaFormBizId
     * @return
     */
    @GetMapping("/get/vo")
    @Operation(summary = "根据 fnaFormBizId 获取Fna表单详情")
    public Result<FnaFormVO> getFnaFormVOByFnaFormBizId(String fnaFormBizId, HttpServletRequest request) {
        if (fnaFormBizId == null) {
            return Result.fail(ResultCode.PARAMS_ERROR.getCode(), ResultCode.PARAMS_ERROR.getMessage());
        }
        // 查询数据库
        FnaForm fnaForm = fnaFormService.getByFnaFormBizId(fnaFormBizId);
        if (fnaForm == null) {
            return Result.fail(ResultCode.NULL_ERROR.getCode(), ResultCode.NULL_ERROR.getMessage());
        }

        // 获取封装类
        return Result.success(fnaFormService.getFnaFormVO(fnaForm));
    }
    /**
     * 分页获取fna表单列表（仅管理员可用）
     *
     * @param fnaFormQueryRequest
     * @return
     */
//    @PostMapping("/list/page")
//    public Result<Page<FnaForm>> listFnaFormByPage(@RequestBody FnaFormQueryRequest fnaFormQueryRequest) {
//        long current = fnaFormQueryRequest.getPageNo();
//        long size = fnaFormQueryRequest.getPageSize();
//        // 查询数据库
//        Page<FnaForm> fnaPage = fnaFormService.page(new Page<>(current, size),
//                fnaFormService.getQueryWrapper(fnaFormQueryRequest));
//        return Result.success(fnaPage);
//    }

    /**
     * 分页获取fna表单列表（封装类）
     *
     * @param fnaFormQueryRequest
     * @param request
     * @return
     */
//    @PostMapping("/list/page/vo")
//    public Result<Page<FnaForm>> listFnaFormVOByPage(@RequestBody FnaFormQueryRequest fnaFormQueryRequest,
//                                             HttpServletRequest request) {
//        long current = fnaFormQueryRequest.getPageNo();
//        long size = fnaFormQueryRequest.getPageSize();
//
//        // 查询数据库
//        Page<FnaForm> fnaPage = fnaFormService.page(new Page<>(current, size),
//                fnaFormService.getQueryWrapper(fnaFormQueryRequest));
//        // 获取封装类
////        return Result.success(fnaFormService.getFnaVOPage(fnaPage, request));
//
//        return Result.success(fnaPage);
//    }

}
