package com.fs.app.controller;

import com.fs.common.annotation.Log;
import com.fs.common.config.LoginContextManager;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.project.domain.ProjectStandard;
import com.fs.project.service.IProjectStandardService;
import com.fs.project.vo.CompanyIntegralRangesReqParams;
import com.fs.project.vo.ProjectStandardDTO;
import com.fs.project.vo.ProjectStandardVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/project/standard")
public class ProjectStandardController extends BaseController {

    @Autowired
    private IProjectStandardService projectStandardService;

    /**
     * 查询列表 - 返回 VO（自动转换 levelConfigList）
     */
    @PreAuthorize("@ss.hasPermi('project:standard:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectStandard projectStandard) {
        startPage();
        Long currentCompanyId = LoginContextManager.getCurrentCompanyId();
        projectStandard.setCompanyId(currentCompanyId);
        List<ProjectStandardVO> voList = projectStandardService.listVo(projectStandard);
        return getDataTable(voList);
    }

    /**
     * 导出（暂保持原逻辑，导出字符串 JSON）
     */
    @PreAuthorize("@ss.hasPermi('project:standard:export')")
    @Log(title = "项目标准配置", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ProjectStandard projectStandard) {
        Long currentCompanyId = LoginContextManager.getCurrentCompanyId();
        projectStandard.setCompanyId(currentCompanyId);
        List<ProjectStandard> list = projectStandardService.selectProjectStandardList(projectStandard);
        ExcelUtil<ProjectStandard> util = new ExcelUtil<>(ProjectStandard.class);
        return util.exportExcel(list, "项目标准配置数据");
    }

    /**
     * 获取详情 - 返回 VO
     */
    @PreAuthorize("@ss.hasPermi('project:standard:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ProjectStandardVO vo = projectStandardService.getDetailVo(id);
        return AjaxResult.success(vo);
    }

    /**
     * 新增 - 接收 DTO
     */
    @PreAuthorize("@ss.hasPermi('project:standard:add')")
    @Log(title = "项目标准配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProjectStandardDTO dto) {
        Long currentCompanyId = LoginContextManager.getCurrentCompanyId();
        dto.setCompanyId(currentCompanyId);
        // 校验唯一性
        String projectType = dto.getProjectType();
        ProjectStandard exist = projectStandardService.selectProjectStandardByCompanyIdAndProjectType(currentCompanyId,projectType);
        if (exist != null) {
            throw new ServiceException("该企业已存在项目标准规则，请编辑已有规则");
        }
        dto.setDelFlag(0);
        projectStandardService.saveOrUpdate(dto);
        return AjaxResult.success();
    }

    /**
     * 修改 - 接收 DTO
     */
    @PreAuthorize("@ss.hasPermi('project:standard:edit')")
    @Log(title = "项目标准配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProjectStandardDTO dto) {
        Long currentCompanyId = LoginContextManager.getCurrentCompanyId();
        dto.setCompanyId(currentCompanyId);
        projectStandardService.saveOrUpdate(dto);
        return AjaxResult.success();
    }

    /**
     * 删除（逻辑删除）
     */
    @PreAuthorize("@ss.hasPermi('project:standard:remove')")
    @Log(title = "项目标准配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(projectStandardService.deleteProjectStandardByIds(ids));
    }


    /**
     * 获取项目允许的最大积分额度
     * @param projectId 项目ID（必填）
     * @return { "maxIntegral": 500.00 }，若未配置则返回 null
     */
    @PreAuthorize("@ss.hasPermi('project:standard:query')")
    @GetMapping("/checkIntegralLimit")
    public AjaxResult checkIntegralLimit(@RequestParam Long projectId,@RequestParam Long doctorId,@RequestParam Integer pointNum,@RequestParam Long companyId) {
        return AjaxResult.success(projectStandardService.getCompanyIntegralLimit(projectId,doctorId,pointNum,companyId));
    }



    /**
     * 批量获取指定项目下多个医生的可积分范围
     */
    @PostMapping("/getCompanyIntegralRanges")
    public AjaxResult getCompanyIntegralRanges(@RequestBody CompanyIntegralRangesReqParams companyIntegralRangesReqParams) {
        return AjaxResult.success(projectStandardService.getCompanyIntegralRanges(companyIntegralRangesReqParams));
    }

}