package com.css.txw.gxzx.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.css.ggzc.framework.cache.vo.DmbDTO;
import com.css.ggzc.framework.common.exception.ServiceException;
import com.css.ggzc.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.css.ggzc.framework.common.pojo.CommonResult;
import com.css.ggzc.framework.common.pojo.PageResult;
import com.css.ggzc.framework.common.util.gy.GyUtils;
import com.css.txw.gxzx.pojo.lsjr.BatchDeleteReqVO;
import com.css.txw.gxzx.pojo.lsjr.CpsxjReqVO;
import com.css.txw.gxzx.pojo.lsjr.DownloadFileInfoVO;
import com.css.txw.gxzx.pojo.lsjr.DspXdbxcpcxRequestVO;
import com.css.txw.gxzx.pojo.lsjr.GxzxDkbxsqxxDto;
import com.css.txw.gxzx.pojo.lsjr.GxzxDkbxsqxxVO;
import com.css.txw.gxzx.pojo.lsjr.GxzxLsjrcpxxDto;
import com.css.txw.gxzx.pojo.lsjr.KxtsjRequestVO;
import com.css.txw.gxzx.pojo.lsjr.KxtsjResponseDataDto;
import com.css.txw.gxzx.pojo.lsjr.XdbxcpcxRequestVO;
import com.css.txw.gxzx.pojo.lsjr.XdbxcpsqRequestVO;
import com.css.txw.gxzx.pojo.lsjr.YhBxjgcxRequestVO;
import com.css.txw.gxzx.pojo.vo.GxspReqVO;
import com.css.txw.gxzx.pojo.vo.ShqkxxVO;
import com.css.txw.gxzx.pojo.vo.lsjr.ProductApplyVO;
import com.css.txw.gxzx.service.lsjr.GxzxLsjrService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Tag(name = "绿色金融")
@RequestMapping("lsjr")
public class LsjrController {

    @Resource
    private GxzxLsjrService lsjrService;

    @Operation(summary = "获取银行/保险机构列表")
    @PostMapping("/queryJgList")
    public CommonResult queryJgList(@Validated @RequestBody YhBxjgcxRequestVO requestVO) {
        List<DmbDTO> list = lsjrService.queryJgList(requestVO);
        return CommonResult.success(list);
    }

    @Operation(summary = "获取信贷、保险产品（分页）")
    @PostMapping("/queryXdbxcpList")
    public CommonResult queryXdbxcpList(@Validated @RequestBody XdbxcpcxRequestVO requestVO) {
        PageResult<GxzxLsjrcpxxDto> pageData = lsjrService.queryXdbxcpList(requestVO);
        return CommonResult.success(pageData);
    }

    @Operation(summary = "获取信贷、保险产品详情")
    @GetMapping("/queryXdbxcpxq")
    public CommonResult queryXdbxcpxq(@RequestParam String cpid) {
        if (GyUtils.isNull(cpid)) {
            return CommonResult.error("产品id不能为空");
        }
        GxzxLsjrcpxxDto xdbxcpDto = lsjrService.queryXdbxcpxq(cpid);
        return CommonResult.success(xdbxcpDto);
    }

    @Operation(summary = "获取企业已存证可信碳数据")
    @PostMapping("/queryKxtsj")
    public CommonResult queryKxtsj(@Validated @RequestBody KxtsjRequestVO requestVO) {
        KxtsjResponseDataDto kxtsjResponseDataDto = lsjrService.queryKxtsj(requestVO);
        return CommonResult.success(kxtsjResponseDataDto);
    }

    @Operation(summary = "保存信贷申请信息")
    @PostMapping("/saveDksqxx")
    public CommonResult saveDksqxx(@ModelAttribute GxzxDkbxsqxxDto dto, @RequestParam("file") @NotNull @NotBlank MultipartFile file) {
        String squuid = lsjrService.saveDksqxx(dto, file);
        return CommonResult.success(squuid);
    }

    @Operation(summary = "保存投保申请信息")
    @PostMapping(path = "/saveTbsqxx", consumes = "multipart/form-data")
    public CommonResult saveTbsqxx(@ModelAttribute GxzxDkbxsqxxDto dto, @RequestParam("file") @NotNull @NotBlank MultipartFile file) {
        String squuid = lsjrService.saveTbsqxx(dto, file);
        return CommonResult.success(squuid);
    }

    @Operation(summary = "获取信贷、保险产品申请信息文件详情")
    @GetMapping("/querySqFileByid")
    public ResponseEntity<byte[]> querySqFileByid(@RequestParam @NotBlank String squuid) {
        DownloadFileInfoVO downloadFileInfoVO = lsjrService.querySqFileByid(squuid);
        //封装下载文件
        String fileName = downloadFileInfoVO.getFileName();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
			headers.setContentDispositionFormData("attachment",  URLEncoder.encode(fileName, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
		}
        return new ResponseEntity<byte[]>(downloadFileInfoVO.getFileByte(), headers, HttpStatus.OK);
    }

    @Operation(summary = "保存/修改产品信息")
    @PostMapping("/saveOrUpdateCpxx")
    public CommonResult saveOrUpdateCpxx(@RequestBody GxzxLsjrcpxxDto dto) {
        String squuid = lsjrService.saveOrUpdateCpxx(dto);
        return CommonResult.success(squuid);
    }

    @Operation(summary = "删除产品信息")
    @PostMapping("/delete/{cpid}")
    public CommonResult delete(@PathVariable("cpid") @NotBlank String cpid) {
        boolean result = lsjrService.delete(cpid);
        return CommonResult.success(result);
    }

    @Operation(summary = "删除产品信息")
    @PostMapping("/batchDelete")
    public CommonResult batchDelete(@RequestBody BatchDeleteReqVO reqVO) {
        boolean result = lsjrService.batchDelete(reqVO);
        return CommonResult.success(result);
    }

    @Operation(summary = "获取待审批信贷、保险产品（分页）")
    @PostMapping("/queryDspXdbxcpList")
    public CommonResult queryDspXdbxcpList(@Validated @RequestBody DspXdbxcpcxRequestVO requestVO) {
        PageResult<ShqkxxVO> pageData = lsjrService.queryDspXdbxcpList(requestVO);
        return CommonResult.success(pageData);
    }

    @Operation(summary = "审批信贷、保险产品")
    @PostMapping("/cpSp")
    public CommonResult<String> cpSp(@RequestBody GxspReqVO reqVO) {
        return CommonResult.success(lsjrService.cpSp(reqVO));
    }

    @Operation(summary = "产品上下架", description = "产品上下架")
    @PostMapping("/cpsxj")
    public CommonResult<String> cpsxj(@Validated @RequestBody CpsxjReqVO reqVO) {
        return CommonResult.success(lsjrService.cpsxj(reqVO));
    }

    @Operation(summary = "下载导入模板", description = "下载导入模板")
    @GetMapping("/getTemplate")
    public void download(HttpServletResponse response) {
        ClassLoader classLoader = this.getClass().getClassLoader();
        try (ServletOutputStream sos = response.getOutputStream();
             InputStream is = classLoader.getResourceAsStream("template/lscp_import_template.xlsx");) {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("绿色产品导入模板.xlsx", "UTF-8"));
            IOUtils.copy(is, sos);
        } catch (IOException e) {
            log.error("下载导入模板失败", e);
            throw new ServiceException(GlobalErrorCodeConstants.ERROR.getCode(), "下载导入模板失败");
        }
    }

    @Operation(summary = "批量导入产品", description = "批量导入产品")
    @PostMapping("/pldr")
    public CommonResult<String> pldr(@NotNull MultipartFile file) {
        return CommonResult.success(lsjrService.pldr(file));
    }


    @Operation(summary = "获取信贷、保险产品申请信息（分页）")
    @PostMapping("/queryXdbxcpsqList")
    public CommonResult queryXdbxcpsqList(@Validated @RequestBody XdbxcpsqRequestVO requestVO) {
        PageResult<GxzxDkbxsqxxVO> pageData = lsjrService.queryXdbxcpsqList(requestVO);
        return CommonResult.success(pageData);
    }

    @Operation(summary = "获取信贷、保险产品申请详情")
    @GetMapping("/queryXdbxcpsqxq")
    public CommonResult queryXdbxcpsqxq(@RequestParam String squuid) {
        if (GyUtils.isNull(squuid)) {
            return CommonResult.error("申请id不能为空");
        }
        GxzxDkbxsqxxVO dkbxsqxxVO = lsjrService.queryXdbxcpsqxq(squuid);
        return CommonResult.success(dkbxsqxxVO);
    }
    /**
	 * 	查询信贷、保险产品申请信息(单独页面）
	 * @name 查询信贷、保险产品申请信息(单独页面）
	 * @time 2025-12-24
	 * @author 崔学志
	 * @history 修订历史（历次修订内容、修订人、修订时间等）
 	*/
	@Operation(summary ="查询信贷、保险产品申请信息(单独页面）")
	@PostMapping("/queryxdbxcpsqinfo")
	public CommonResult queryXdbxcpsqInfo(@Valid @RequestBody XdbxcpsqRequestVO request ) {
		CommonResult result = CommonResult.success(null);
		if (GyUtils.isNull(request)) {
			String msg = "request is null . ";
			log.info(msg);
			result.setMsg(msg);
			result.setCode(GlobalErrorCodeConstants.ERROR.getCode());
			return result;
		}
		if (GyUtils.isNotNull(request) && GyUtils.isNotNull(request.getType())) {
			String[] strs = StringUtils.commaDelimitedListToStringArray(request.getType());
			request.setTypeList(Arrays.asList(strs)); 
		} 
		PageResult<ProductApplyVO> ret = lsjrService.queryXdbxcpsqInfo(request);
		result.setData(ret);
		result.setCode(GlobalErrorCodeConstants.SUCCESS.getCode());
		return result;
	}

}
