package com.kcim.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kcim.common.constants.NumberConstant;
import com.kcim.common.exception.CostException;
import com.kcim.common.util.BeanUtil;
import com.kcim.common.util.PageUtils;
import com.kcim.common.util.UserContext;
import com.kcim.common.util.excel.ExcelStyleUtil;
import com.kcim.common.util.excel.entity.DiseaseTypeImportEntity;
import com.kcim.dao.model.DiseaseType;
import com.kcim.dao.repository.DiseaseTypeRepository;
import com.kcim.service.DiseaseTypeService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @program: CostAccount
 * @description: 病种管理接口实现类
 * @author: Wang.YS
 * @create: 2023-11-07 17:09
 **/
@Service("DiseaseTypeService")
@Slf4j
@AllArgsConstructor
public class DiseaseTypeServiceImpl implements DiseaseTypeService {

    DiseaseTypeRepository repository;

    /**
     * 获取病种列表
     * @param current 当前页
     * @param pageSize 页容量
     * @param name 病种名称
     * @return 病种列表
     */
    @Override
    public Object getDiseaseTypeList(Integer current, Integer pageSize, String name) {
        Page<DiseaseType> page = repository.getPage(current, pageSize, name);
        List<DiseaseType> records = page.getRecords();
        if(CollectionUtils.isEmpty(records)){
            return new PageUtils(new ArrayList<>(), NumberConstant.ZERO,pageSize,current);
        }

        return new PageUtils(records, Math.toIntExact(page.getTotal()),pageSize,current);    }

    /**
     * 新增病种信息
     * @param request 入参
     */
    @Override
    public void addDiseaseType(DiseaseType request) {
        request.setHospId(UserContext.getCurrentLoginHospId());
        request.setCreateTime(new Date());
        request.setCreateUser(String.valueOf(UserContext.getCurrentUser().getId()));

        repository.save(request);
    }

    /**
     * 编辑病种信息
     * @param request 入参
     */
    @Override
    public void editDiseaseType(DiseaseType request) {
        Integer id = request.getId();
        if(id ==null){
            throw new CostException("编辑病种时，主键必填");
        }
        DiseaseType diseaseType = repository.getById(id);
        if(Objects.nonNull(diseaseType)){
            BeanUtil.convertObj(request,diseaseType);
            diseaseType.setUpdateTime(new Date());
            diseaseType.setUpdateUser(String.valueOf(UserContext.getCurrentUser().getId()));
            repository.updateById(diseaseType);
        }

    }

    /**
     * 删除病种信息
     * @param id 主键
     */
    @Override
    public void deleteDiseaseType(Integer id) {
        repository.deleteDiseaseType(id);
    }

    /**
     * 导出病种信息模板
     * @param response 出参
     * @return excel出参
     */
    @SneakyThrows
    @Override
    public Object exportDiseaseType(HttpServletResponse response) {
        try {
            //配置excel 文件信息
            ExportParams params = new ExportParams();

            params.setTitle("说明：1、为了保证成功导入，请勿修改模板格式\n" +
                    "      2、说明字段为非必填字段，可以为空\t\t");
            //设置导出样式
            params.setStyle(ExcelStyleUtil.class);
            //设置sheetName
            params.setSheetName("病种项目");
//            FileOutputStream outputStream = new FileOutputStream("E:\\病种项目导入模版.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, DiseaseTypeImportEntity.class,new ArrayList<>());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            String fileName ="病种项目导入模版";
            response.setHeader("Content-Disposition",  URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
//                workbook.write(outputStream);
//                outputStream.close();
            workbook.close();
            log.info("导出文件：{}",fileName);
        } catch (FileNotFoundException e) {
            throw new CostException(e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return response.getOutputStream();
    }

    /**
     * 导入病种信息
     * @param file excel文件
     */
    @Override
    public void importDiseaseType(MultipartFile file) {
        try {
            if (ObjectUtils.isEmpty(file) || file.getSize() == 0){
                throw new CostException("未获取到导入的excel文件内容");
            }
            log.info("接收到文件：{}",file.getOriginalFilename());
            // 参数1：文件流
            InputStream stream = file.getInputStream();
            // 参数2：导入类型
            ImportParams params = new ImportParams();
            //校验Excel 去掉空行
            params.setNeedVerify(true);
            IExcelVerifyHandler<DiseaseTypeImportEntity> handler = val ->{
                if(StringUtils.isEmpty(val.getCode())){
                    return new ExcelVerifyHandlerResult(false,"病种编码不能为空");
                }
                if(StringUtils.isEmpty(val.getName())){
                    return new ExcelVerifyHandlerResult(false,"病种名称不能为空");
                }
                return new ExcelVerifyHandlerResult(true);
            };
            params.setVerifyHandler(handler);
            // 标题占用多少行
            params.setTitleRows(1);
            // 头部属性占用多少行
            params.setHeadRows(1);
            List<DiseaseTypeImportEntity> diseaseTypeImportEntities  = ExcelImportUtil.importExcel(stream, DiseaseTypeImportEntity.class,params);
            if(!CollectionUtils.isEmpty(diseaseTypeImportEntities)){
                List<DiseaseType> saveList = new ArrayList<>();
                DiseaseType diseaseType =new DiseaseType();
                diseaseType.setHospId(UserContext.getHospId());
                diseaseType.setCreateTime(new Date());
                diseaseType.setCreateUser(String.valueOf(UserContext.getCurrentUser().getId()));
                for (DiseaseTypeImportEntity entity : diseaseTypeImportEntities) {
                    DiseaseType type = BeanUtil.convertObj(diseaseType, DiseaseType.class);
                    type.setCode(entity.getCode());
                    type.setName(entity.getName());
                    type.setDescription(entity.getDescription());
                    saveList.add(type);
                }
                if(!CollectionUtils.isEmpty(saveList)){
                    check();
                    repository.saveBatch(saveList,50);
                }
            }
        } catch (Exception e) {
            throw new CostException(e.getMessage());
        }
    }

    private void check() {
        List<DiseaseType> list = repository.getList();
        if(!CollectionUtils.isEmpty(list)){
            repository.removeList(list);
        }
    }
}
