package com.njcn.gather.icd.controller;

import com.alibaba.fastjson.JSON;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.LogUtil;
import com.njcn.gather.icd.pojo.enums.IcdResponseEnum;
import com.njcn.gather.icd.pojo.param.PqIcdPathParam;
import com.njcn.gather.icd.pojo.po.PqIcdPath;
import com.njcn.gather.icd.service.IPqIcdPathService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import javax.validation.Valid;
import java.time.LocalDate;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author caozehui
 * @date 2025-02-10
 */
@Slf4j
@Api(tags = "icd管理")
@RestController
@RequestMapping("/icd")
@RequiredArgsConstructor
public class PqIcdPathController extends BaseController {
    private final IPqIcdPathService pqIcdPathService;

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/listAll")
    @ApiOperation("获取全部icd")
    public HttpResult<List<PqIcdPath>> listAll() {
        String methodDescribe = getMethodDescribe("listAll");
        List<PqIcdPath> result = pqIcdPathService.listAll();
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo
    @PostMapping("/list")
    @ApiOperation("分页查询icd")
    @ApiImplicitParam(name = "param", value = "查询参数", required = true)
    public HttpResult<Page<PqIcdPath>> list(@RequestBody @Validated PqIcdPathParam.QueryParam param) {
        String methodDescribe = getMethodDescribe("list");
        LogUtil.njcnDebug(log, "{}，查询数据为：{}", methodDescribe, param);
        Page<PqIcdPath> result = pqIcdPathService.listIcd(param);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
    @PostMapping("/add")
    @ApiOperation("新增icd")
    @ApiImplicitParam(name = "param", value = "icd新增参数", required = true)
    public HttpResult<Boolean> add(@Validated PqIcdPathParam.CreateParam param) {
        String methodDescribe = getMethodDescribe("add");
        LogUtil.njcnDebug(log, "{}，新增数据为：{}", methodDescribe, param);

        boolean result = pqIcdPathService.addIcd(param);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
    @PostMapping("/external/add")
    @ApiOperation("外部系统新增icd")
    @ApiImplicitParam(name = "param", value = "外部系统icd新增参数", required = true)
    public HttpResult<Boolean> externalAdd(@RequestBody List<PqIcdPathParam.ExternalCreateParam> param) {
        String methodDescribe = getMethodDescribe("externalAdd");
        LogUtil.njcnDebug(log, "{}，外部新增数据为：{}", methodDescribe, param);

        boolean result = pqIcdPathService.addUpstreamIcd(param);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
    @PostMapping("/update")
    @ApiOperation("修改icd")
    @ApiImplicitParam(name = "param", value = "icd修改参数", required = true)
    public HttpResult<Boolean> update(@Validated PqIcdPathParam.UpdateParam param) {
        String methodDescribe = getMethodDescribe("update");
        LogUtil.njcnDebug(log, "{}，修改数据为：{}", methodDescribe, param);

        boolean result = pqIcdPathService.updateIcd(param);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/standard-list")
    @ApiOperation("获取标准ICD列表")
    public HttpResult<List<PqIcdPath>> standardList() {
        String methodDescribe = getMethodDescribe("standardList");
        List<PqIcdPath> result = pqIcdPathService.listStandardIcd();
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/getById")
    @ApiOperation("根据id获取ICD详情")
    public HttpResult<PqIcdPath> getById(@RequestParam String id) {
        String methodDescribe = getMethodDescribe("getById");
        PqIcdPath result = pqIcdPathService.getIcdById(id);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
    @PostMapping("/delete")
    @ApiOperation("删除icd")
    @ApiImplicitParam(name = "ids", value = "icd的id列表", required = true)
    public HttpResult<Boolean> delete(@RequestBody List<String> ids) {
        String methodDescribe = getMethodDescribe("delete");
        LogUtil.njcnDebug(log, "{}，删除数据为：{}", methodDescribe, String.join(StrUtil.COMMA, ids));
        boolean result = pqIcdPathService.deleteIcd(ids);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/export/{id}")
    @ApiOperation("导出icd")
    public ResponseEntity<ByteArrayResource> export(@PathVariable String id) {
        PqIcdPath detail = pqIcdPathService.getIcdById(id);
        byte[] body = pqIcdPathService.exportIcd(id);
        String fileName = UriUtils.encode(detail.getName() + ".zip", StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(body.length)
                .body(new ByteArrayResource(body));
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @PostMapping("/export/json")
    @ApiOperation("导出icd json")
    @ApiImplicitParam(name = "ids", value = "id集合", required = true)
    public ResponseEntity<ByteArrayResource> exportJson(@RequestBody List<String> ids) {
        byte[] body = pqIcdPathService.exportIcdJson(ids);
        String fileName = UriUtils.encode(LocalDate.now() + ".json", StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
                .contentType(MediaType.APPLICATION_JSON)
                .contentLength(body.length)
                .body(new ByteArrayResource(body));
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
    @PostMapping("/import/json")
    @ApiOperation("导入icd json")
    @ApiImplicitParam(name = "file", value = "json文件", required = true)
    public HttpResult<Boolean> importJson(@RequestParam("file") MultipartFile file) {
        String methodDescribe = getMethodDescribe("importJson");
        LogUtil.njcnDebug(log, "{}，导入文件为：{}", methodDescribe, file == null ? null : file.getOriginalFilename());

        List<PqIcdPathParam.ExternalCreateParam> param = parseExternalCreateParams(file);
        boolean result = pqIcdPathService.addUpstreamIcd(param);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    private List<PqIcdPathParam.ExternalCreateParam> parseExternalCreateParams(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(IcdResponseEnum.ICD_FILE_NOT_NULL);
        }
        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.toLowerCase().endsWith(".json")) {
            throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
        }
        try {
            String content = new String(file.getBytes(), StandardCharsets.UTF_8);
            List<PqIcdPathParam.ExternalCreateParam> params = JSON.parseArray(content, PqIcdPathParam.ExternalCreateParam.class);
            if (params == null) {
                throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
            }
            return params;
        } catch (BusinessException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new BusinessException(IcdResponseEnum.JSON_FORMAT_ERROR);
        }
    }
}
