package com.yihu.jw.base.endpoint.dict;

import com.yihu.jw.base.service.dict.*;
import com.yihu.jw.base.service.dict.importManage.*;
import com.yihu.jw.base.service.doctor.excelImport.BaseDoctorExcelDO;
import com.yihu.jw.base.service.doctor.excelImport.BaseDoctorExcelDOReader;
import com.yihu.jw.entity.base.dict.DictDiseaseDO;
import com.yihu.jw.entity.base.dict.DiseaseManageDO;
import com.yihu.jw.exception.business.ManageException;
import com.yihu.jw.restmodel.base.dict.DictDiseaseVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
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.commons.lang3.StringUtils;
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.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/templateManage")
@Api(value = "字典模板维护", description = "字典模板维护", tags = {"字典模板维护"})
public class TemplateManageEndpoint  extends EnvelopRestEndpoint {
    @Autowired
    private TemplateManageService templateManageService;
    @Autowired
    private BaseDrugDictService baseDrugDictService;
    @Autowired
    private BaseDrugExcelDOReader baseDrugExcelDOReader;
    @Autowired
    private BaseDrugUseExcelDOReader baseDrugUseExcelDOReader;
    @Autowired
    private BaseDrugUseService baseDrugUseService;
    @Autowired
    private BaseFrequencyExcelDOReader baseFrequencyExcelDOReader;
    @Autowired
    private BaseFrequencyService baseFrequencyService;
    @Autowired
    private BaseIcd10ExcelDOReader icd10ExcelDOReader;
    @Autowired
    private DictIcd10Service dictIcd10Service;

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

    /**
     * 判断文件格式
     * @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;
    }
    @GetMapping("/getTemplateList")
    @ApiOperation(value = "获取列表")
    public MixEnvelop list (
            @ApiParam(name = "templateType", value = "模板类型")
            @RequestParam(value = "templateType", required = false) String templateType,
            @ApiParam(name = "code", value = "")
            @RequestParam(value = "code", required = false) String code,
            @ApiParam(name = "name", value = "")
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "diseaseName", value = "")
            @RequestParam(value = "diseaseName", required = false) String diseaseName,
            @ApiParam(name = "diseaseId", value = "")
            @RequestParam(value = "diseaseId", required = false) String diseaseId,
            @ApiParam(name = "page", value = "")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pageSize", value = "")
            @RequestParam(value = "pageSize", required = false) Integer pageSize) throws Exception {
        try {
            return templateManageService.findTempalte(templateType,code,name,diseaseName,diseaseId,page,pageSize);
        }catch (Exception e){
            e.printStackTrace();
            return failedMixEnvelopException(e);
        }
    }

    @GetMapping("/addOrRemoveChild")
    @ApiOperation(value = "")
    public Envelop addOrRemoveChild (
            @ApiParam(name = "templateId", value = "模板id")
            @RequestParam(value = "templateId", required = false) String templateId,
            @ApiParam(name = "dictId", value = "")
            @RequestParam(value = "dictId", required = false) String  dictId,
            @ApiParam(name = "del", value = "")
            @RequestParam(value = "del", required = false) String  del) throws Exception {
        try {
            templateManageService.addOrRemoveChildrenDict(templateId,dictId,del);
            return success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return failedException(e);
        }
    }

    @GetMapping("/saveOrUpdateTemplate")
    @ApiOperation(value = "")
    public Envelop saveOrUpdateTemplate (
            @ApiParam(name = "templateId", value = "模板id")
            @RequestParam(value = "templateId", required = false) String templateId,
            @ApiParam(name = "diseaseId", value = "diseaseId")
            @RequestParam(value = "diseaseId", required = false) String diseaseId,
            @ApiParam(name = "diseaseName", value = "diseaseName")
            @RequestParam(value = "diseaseName", required = false) String diseaseName,
            @ApiParam(name = "code", value = "")
            @RequestParam(value = "code", required = false) String  code,
            @ApiParam(name = "name", value = "")
            @RequestParam(value = "name", required = false) String  name,
            @ApiParam(name = "templateType", value = "")
            @RequestParam(value = "templateType", required = false) String  templateType) throws Exception {
        try {
            if (!StringUtils.isNoneBlank(templateId)){
                templateId="1";
            }
            templateManageService.saveOrUpdateTemplate(templateId,code,name,getUID(),getUNAME(),templateType,diseaseId,diseaseName);
            return success("操作成功");
        }catch (Exception e){
            e.printStackTrace();
            return failedException(e);
        }
    }
    @GetMapping("/getTemplateChildList")
    @ApiOperation(value = "获取列表")
    public MixEnvelop getTemplateChildList (
            @ApiParam(name = "templateId", value = "模板id")
            @RequestParam(value = "templateId", required = false) String templateId,
            @ApiParam(name = "name", value = "模板id")
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "code", value = "")
            @RequestParam(value = "code", required = false) String code,
            @ApiParam(name = "isSelectUse", value = "1查询已添加的2查询未添加")
            @RequestParam(value = "isSelectUse", required = false) String isSelectUse,
            @ApiParam(name = "page", value = "")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pageSize", value = "")
            @RequestParam(value = "pageSize", required = false) Integer pageSize) throws Exception {
        try {
            if(StringUtils.isNoneBlank(isSelectUse)&&"1".equalsIgnoreCase(isSelectUse)){
                return templateManageService.findTemlateAddChildList(templateId,name,code,page,pageSize);
            }else if(StringUtils.isNoneBlank(isSelectUse)&&"2".equalsIgnoreCase(isSelectUse)){
                return templateManageService.findTemlateNotAddChildList(templateId,name,code,page,pageSize);
            } else {
                return templateManageService.findTemlateChildList(templateId,name,code,page,pageSize);
            }

        }catch (Exception e){
            e.printStackTrace();
            return failedMixEnvelopException(e);
        }
    }

    @GetMapping("/saveOrgTemplate")
    @ApiOperation(value = "保存租户模板")
    public Envelop saveSaasTemplate (
            @ApiParam(name = "orgCode", value = "orgCode")
            @RequestParam(value = "orgCode", required = false) String orgCode,
            @ApiParam(name = "templateIds", value = "")
            @RequestParam(value = "templateIds", required = false) String templateIds) throws Exception {
        try {
            templateManageService.saveUserTemplateRelation(orgCode,templateIds);
            return success("保存成功");
        }catch (Exception e){
            e.printStackTrace();
            return failedMixEnvelopException(e);
        }
    }

    @GetMapping("/findOrgTemplate")
    @ApiOperation(value = "保存机构模板")
    public Envelop saveSaasTemplate (
            @ApiParam(name = "orgCode", value = "orgCode")
            @RequestParam(value = "orgCode", required = false) String orgCode) throws Exception {
        try {

            return success(templateManageService.findUseTemplate(orgCode));
        }catch (Exception e){
            e.printStackTrace();
            return failedMixEnvelopException(e);
        }
    }


    @PostMapping("/excelControl/importDrugUse")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "基础药品用法列表导入")
    public Envelop importDrugUse(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestPart(value = "file") MultipartFile file,
            @ApiParam(name = "templateId", value = "templateId", required = false)
            @RequestPart(value = "templateId" ,required = false) String  templateId,
            HttpServletRequest request) throws IOException, ManageException {
        try {
            request.setCharacterEncoding("UTF-8");
//            AExcelReader excelReader = new BaseDoctorExcelDOReader();
            InputStream inputStream = file.getInputStream();
            Workbook workbook = getWorkbook(inputStream,file.getOriginalFilename());
            baseDrugExcelDOReader.setTemplateId(templateId);
            baseDrugUseExcelDOReader.read(workbook);
            //验证未通过（暂无验证）
            List<BasDrugUseExcelDO> errorLs = baseDrugUseExcelDOReader.getErrorLs();
            List<BasDrugUseExcelDO> correctLs = baseDrugUseExcelDOReader.getCorrectLs();
            Map<String, Object> result =new HashMap<>();
            String msg ="";
            if(correctLs.size()>0){
                result = baseDrugUseService.batchInsertDrugs(correctLs,templateId);
                result.put("errorLs", errorLs);
                int errors = errorLs==null?0:errorLs.size();
                int corrects = correctLs==null?0:correctLs.size();
                msg = "当前导入成功"+corrects+"条数据"+";失败"+errors+"条数据";
                return success(msg, result);
            }
            return success(msg, result);
        }catch (Exception e){
            e.printStackTrace();
            return failed("导入异常,请检查导入文件格式" + e.getMessage());
        }
    }


    @PostMapping("/excelControl/importfrequency")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "基础药品频次信息列表导入")
    public Envelop importfrequency(
            @ApiParam(name = "file", value = "文件", required = true)
            @RequestPart(value = "file") MultipartFile file,
            @ApiParam(name = "templateId", value = "templateId", required = false)
            @RequestPart(value = "templateId" ,required = false) String  templateId,
            HttpServletRequest request) throws IOException, ManageException {
        try {
            request.setCharacterEncoding("UTF-8");
//            AExcelReader excelReader = new BaseDoctorExcelDOReader();
            InputStream inputStream = file.getInputStream();
            Workbook workbook = getWorkbook(inputStream,file.getOriginalFilename());
            baseDrugExcelDOReader.setTemplateId(templateId);
            baseFrequencyExcelDOReader.read(workbook);
            //验证未通过（暂无验证）
            List<BasFrequencyExcelDO> errorLs = baseFrequencyExcelDOReader.getErrorLs();
            List<BasFrequencyExcelDO> correctLs = baseFrequencyExcelDOReader.getCorrectLs();
            Map<String, Object> result =new HashMap<>();
            String msg ="";
            if(correctLs.size()>0){
                 result = baseFrequencyService.batchInsertDrugs(correctLs,templateId);
                result.put("errorLs", errorLs);
                int errors = errorLs==null?0:errorLs.size();
                int corrects = correctLs==null?0:correctLs.size();
                msg = "当前导入成功"+corrects+"条数据"+";失败"+errors+"条数据";

            }
            return success(msg, result);
        }catch (Exception e){
            e.printStackTrace();
            return failed("导入异常,请检查导入文件格式" + e.getMessage());
        }
    }

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

    @GetMapping("/excelControl/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response,@ApiParam(name = "templateType", value = "templateType", required = true)
    @RequestParam   (value = "templateType") String  templateType) {

        try {
            String filePath="";
            String fileName="";
            if ("frequencyDict".equalsIgnoreCase(templateType)){
                filePath="/home/频次模板.xls";
                fileName="频次模板.xls";
            }else if ("drugUseDict".equalsIgnoreCase(templateType)){
                filePath="/home/用药类型模板.xls";
                fileName="用药类型模板.xls";
            }else if ("drugListDict".equalsIgnoreCase(templateType)){
                filePath="/home/药品字典模板.xls";
                fileName="药品字典模板.xls";
            }else if ("icd10ListDict".equalsIgnoreCase(templateType)){
                filePath="/home/诊断模板.xls";
                fileName="诊断模板.xls";
            }
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(filePath));

// 根据页面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(fileName,"UTF-8"));

            wb.write(output);
            /*ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                wb.write(bos);
            } finally {
                bos.close();
            }
            byte[] bytes = bos.toByteArray();
            output.write(bytes);
            output.close();*/
            wb.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    @GetMapping("/findOneTemplate")
    @ApiOperation(value = "根据药品id查询")
    public Envelop findOneTemplate(@ApiParam(name = "id", value = "药品id")
                               @RequestParam(name = "id", required = true) String id){

        try {

            return success(templateManageService.findOneTemplateById(id));
        }catch (Exception e) {
            return failedException(e);
        }
    }
    @GetMapping("/getTemplateListByDiseaseId")
    @ApiOperation(value = "获取列表")
    public Envelop getTemplateListByDiseaseId (
            @ApiParam(name = "diseaseId", value = "id")
            @RequestParam(value = "diseaseId", required = false) String diseaseId) throws Exception {
        try {
            String doctorId=getUID();
            return success(templateManageService.findTemplateByDisease(doctorId,diseaseId));
        }catch (Exception e){
            e.printStackTrace();
            return failedMixEnvelopException(e);
        }
    }
}
