package com.yihu.jw.base.endpoint.open.nologin;

import com.yihu.jw.base.service.doctor.BaseDoctorService;
import com.yihu.jw.base.service.doctor.excelImport.BaseDoctorExcelDO;
import com.yihu.jw.base.service.doctor.excelImport.BaseDoctorExcelDOReader;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/excelControl")
@Api(value = "不走网关接口", description = "不走网关接口", tags = {"base基础服务 - 不走网关接口"})
public class BaseServiceNologin extends EnvelopRestEndpoint {
    @Autowired
    private BaseDoctorService baseDoctorService;
    @Autowired
    private BaseDoctorExcelDOReader doctorExcelDOReader;
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {

        try {

            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("/home/医生模板信息.xls"));

// 根据页面index 获取sheet页

            HSSFSheet sheet = wb.getSheet("Sheet1");

            for (int i = 0; i < 2; i++) {

// 创建HSSFRow对象

                HSSFRow row = sheet.createRow(i + 1);

// 创建HSSFCell对象 设置单元格的值

                row.createCell(0).setCellValue("张三" + i);

                row.createCell(1).setCellValue("1");

                row.createCell(2).setCellValue("1");

                row.createCell(3).setCellValue("210503199507250333");
                row.createCell(4).setCellValue("18841409773");
                row.createCell(5).setCellValue("350211A1002/0000001/1303");
                row.createCell(6).setCellValue("1302");
                row.createCell(7).setCellValue("admin");
                row.createCell(8).setCellValue("1");

            }

// 输出Excel文件

            OutputStream output = new BufferedOutputStream(response.getOutputStream());

            response.reset();

// 设置文件头

            /*response.setHeader("Content-Disposition",

                    "attchement;filename=" + new String("人员信息.xls".getBytes("gb2312"), "ISO8859-1"));

            response.setContentType("application/msexcel");*/
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload");
            /*response.setHeader("Content-Disposition", "attachment; filename="
                    + new String( "医生模板信息".getBytes("gb2312"), "ISO8859-1" )+".xls");*/
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode("医生模板信息.xls","UTF-8"));
            wb.write(output);

            wb.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }
    /**
     * 判断文件格式
     * @param in
     * @param fileName
     * @return
     */
    private static Workbook getWorkbook(InputStream in, String fileName) throws Exception {

        Workbook book = null;
        String filetype = fileName.substring(fileName.lastIndexOf("."));

        if(".xls".equals(filetype)) {
            book = new HSSFWorkbook(in);
        } else if (".xlsx".equals(filetype)) {
            book = new XSSFWorkbook(in);
        } else {
            throw new Exception("请上传excel文件！");
        }

        return book;
    }
    @PostMapping(value = BaseRequestMapping.BaseDoctor.DOCTOR_INFO_IMPORT)
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "基础医生信息列表导入")
    public Envelop importData(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestPart(value = "file") MultipartFile file,
            HttpServletRequest request) throws IOException, ManageException {
        try {
            request.setCharacterEncoding("UTF-8");
//            AExcelReader excelReader = new BaseDoctorExcelDOReader();
            InputStream inputStream = file.getInputStream();
            Workbook workbook = getWorkbook(inputStream,file.getOriginalFilename());
            doctorExcelDOReader.read(workbook);
            //验证未通过（暂无验证）
            List<BaseDoctorExcelDO> errorLs = doctorExcelDOReader.getErrorLs();
            List<BaseDoctorExcelDO> correctLs = doctorExcelDOReader.getCorrectLs();
            if(correctLs.size()>0){
                Map<String, Object> result = baseDoctorService.batchInsertDoctor(correctLs);
                result.put("errorLs", errorLs);
                int errors = errorLs.size();
                int corrects = correctLs.size();
                String msg = "当前导入成功"+corrects+"条数据"+";失败"+errors+"条数据";
                return success(msg, result);
            }
        }catch (Exception e){
            e.printStackTrace();
            return failed("导入异常,请检查导入文件格式" + e.getMessage());
        }
        return failed("导入失败");
    }
}
