package com.controller;

import com.alibaba.fastjson.JSON;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.model.*;
import com.model.Reader;
import com.service.*;
import com.tools.JwtUtils;
import com.utils.*;
import com.validator.ReaderValidator;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@ControllerInterface(path="/reader")
public class ReaderController extends BaseController {
    ReaderService service = ReaderService.me;
    EquipmentFace equipmentFaceDao = new EquipmentFace().dao();
    DictService dictService = DictService.me;
    OrgDept orgDeptDao = new OrgDept().dao();
    OrgDeptService orgDeptService = OrgDeptService.me;
    ReaderAuth readerAuthDao = new ReaderAuth().dao();
    ReaderAuthService readerAuthService= ReaderAuthService.me;

    SysConfigService sysConfigService=SysConfigService.me;

    public void index() {
        render("/view/reader/reader.html");
    }

    public void curdate(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        success(sdf.format(new Date()));
    }

    public void readerauthdate(){
        int year = getParaToInt("year");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, year);
        success(DateUtils.getTimeToDay(cal.getTime()));
    }

    public void list(){
        Reader bean = getBean(Reader.class,"bean");
        String deptname = getPara("deptname");
        success(service.paginate(this.getParaToInt("pageNumber"),getParaToInt("pageSize"),bean,deptname));
    }
    public void getById(){
        int id =this.getParaToInt("bean.id", 0);
        if(id == 0){
            fail();
            return;
        }
        success(service.findById(id));
    }
    //增加或修改
    @Before(ReaderValidator.class)
    public void addOrUpdate(){

        Reader reader = getBean(Reader.class,"bean");
        String token = this.getPara("token");
        try {
            Map userinfo = JwtUtils.validateJWTForMap(token);
            int orgid = (Integer) userinfo.get("orgid");
            int operatorid = JwtUtils.validateJWTForUserId(token);
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }
            if(service.findReaderByCardNumber(reader.getCardnumber(),reader.getId(),reader.getOrgid())){
                logger.info("读者证号重复！");
                fail(1,"读者证号重复");
                return;
            }
            OrgSetting orgSetting = sysConfigService.findOrgSetting(reader.getOrgid());
            //reader.setCardnumber(CommonUtils.formatCardnumber(reader.getCardnumber(),orgSetting));
            //reader.setCardnumber()
            service.addOrUpdate(reader,operatorid);

            new Thread(){
                public void run(){
                    List<EquipmentFace> list = equipmentFaceDao.find("select * from t_equipment_face where orgid=? ",orgid);
                    for(EquipmentFace bean : list){
                        try {
                            OrgDept orgDept = orgDeptDao.findById(reader.getOrgdeptid());

                            String orgname = "";
                            String auth = "";
                            if(orgDept != null){
                                orgname = orgDept.getDeptname();
                                //ReaderAuth readerAuth = readerAuthDao.findById(orgDept.getReaderauthid());
                                //auth = "可借"+readerAuth.getJieyueshuliang()+"本";
                            }
                            String msgid = orgid + bean.getDeviceNo() + System.currentTimeMillis();
                            Map map = new HashMap();
                            map.put("msgType", "registerPersonInfo");
                            map.put("msgID", msgid);
                            map.put("deviceNo", bean.getDeviceNo());
                            map.put("personInfoCount", "1");
                            List<Map> l = new ArrayList();
                            Map m = new HashMap();
                            l.add(m);
                            map.put("personInfoData", l);
                            m.put("operateType", "0");
                            m.put("idNumber", orgid + "_" + reader.getId());
                            m.put("name", orgname+","+reader.getRealname());
                            m.put("sex", reader.getSex());
                            m.put("priority", "0");
                            m.put("validDateStart","2020_01_01");
                            m.put("validDateEnd","2060_01_01");
                            m.put("registerPhoto1", reader.getFaceimage().substring(22));
                            m.put("registerPhotoID1", reader.getId());
                            m.put("voiceSpecialMode", "2");
                            m.put("displaySpecialMode", "1");
                            //System.out.println("想设备注册："+JSON.toJSONString(map));


                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }.start();


            success();
        }catch(Exception e){
            e.printStackTrace();
            fail(0,e.getMessage());
        }
    }

    public void registReaderToFaceDevice(int orgid,Reader reader){




    }
    public void faceSearch(){
        try {
            String token = this.getPara("token");
            int operatorid = JwtUtils.validateJWTForUserId(token);
            if (operatorid == 0) {
                fail(3, "token错误");
                return;
            }
            String orgid =getPara("orgid");
            String json= FaceUtil.search(getPara("FaceBaseStr64").substring(22),orgid);
            success(json);
        }catch (Exception e){
            fail();
        }
    }

    //删除
    public void delete(){
        int id =this.getParaToInt("bean.id");
        service.deleteById(this.getParaToInt("bean.id", 0));
        success();
    }
    //下拉选
    public void selectType(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        Map map = service.selectType(operatorid);
        success(map);
    }

    /**
     * 批量修改读者权限
     */
    public void resetrole(){
        String[] ids=getParaValues("idlist[]");
        int roleid = this.getParaToInt("roleid");
        int orgid = this.getParaToInt("orgid");
        for (String id : ids){
            Db.update("update t_reader set readerauthid = ? where id = ? and orgid = ?",roleid,id,orgid);
        }
        success();
    }

    /**
     * 批量修改读者部门
     */
    public void resetdept(){
        String[] ids=getParaValues("idlist[]");
        int deptid = this.getParaToInt("deptid");
        int orgid = this.getParaToInt("orgid");
        for (String id : ids){
            Db.update("update t_reader set orgdeptid = ? where id = ? and orgid = ?",deptid,id,orgid);
        }
        success();
    }

    /**
     * 批量修改读者权限
     */
    public void batchresetReaderStatus(){
        String token = this.getPara("token");
        Map userinfo = JwtUtils.validateJWTForMap(token);
        int orgid = (Integer) userinfo.get("orgid");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        String cardnumberstr = this.getPara("cardnumberstr");
        String cardnumbers[] = cardnumberstr.split(",");
        //String resetroleselecttoreader = this.getPara("resetroleselecttoreader");
        String errorinfo = "";
        int status = getParaToInt("status", 1);
        for(String cardnumber : cardnumbers) {
            try {
                if (CommonUtils.isNullOrEmpty(cardnumber)) {
                    continue;
                }
                Db.update("update t_reader set status=? where orgid=? and (cardnumber=? or readcardcode=?) ",status, orgid, cardnumber, cardnumber);
            /*Record record = Db.findFirst("select * from t_reader where orgid = ? and cardnumber =? ",orgid,cardnumber);
            if(CommonUtils.isNullOrEmpty(record)){
                errorinfo+=cardnumber+" ";
                continue;
            }*/
                //Db.update("update t_reader set readerauthid = ? where id = ?",resetroleselecttoreader,record.getInt("id"));
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        success(errorinfo);

    }


    //注销或停用
    public void status(){
        String[] ids=getParaValues("idlist[]");
        int status = this.getParaToInt("status");
        for (String id : ids){
            service.status(Integer.parseInt(id),status);
        }
        success();
    }

    //更新失效日期
    public void updatelosedate(){
        String[] ids=getParaValues("idlist[]");
        String lostdate = this.getPara("lostdate");
        service.updatelosedate(ids,lostdate);
        success();
    }

    //重置密码
    public void resetStatus(){
        int id =this.getParaToInt("id");
        service.resetStatus(this.getParaToInt("id", 0));
        success();
    }

    public void readerAccessImport(){
        success(PropKit.use("config.txt").getBoolean("ReaderAccessImport"));
    }

    public void upload(){
        try{
            String token = this.getPara("token");
            int operatorid = JwtUtils.validateJWTForUserId(token);
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }
            int orgid = getParaToInt("orgid");


            Map<String,Integer> dictMap=dictService.dictmap();
            Map<String,Integer>  readerAuthMap=readerAuthService.findReaderAuthByName(orgid);
            List<OrgDept> orgDeptList=orgDeptService.findOrgDept(orgid);

            OrgSetting orgSetting=sysConfigService.findOrgSetting(orgid);

            UploadFile file =getFile();
            List<Map<String,String>> errorDataList = new ArrayList<Map<String,String>>();

            List<Map<String,String>> readerList=null;

            if ("Excel".equals(getPara("ImportType"))){
                readerList=  ExcelUtil.readExcel(new FileInputStream(file.getFile()));
            }else if ("Access".equals(getPara("ImportType"))){
                readerList=  AccessUtil.getAccessData(file.getFile().getAbsolutePath());
            }else if ("Foxpro".equals(getPara("ImportType"))){
                readerList= FoxproUtil.getFoxProData(file.getFile().getAbsolutePath());
            }else {
                fail(0,"错误的导入方式！");
                return;
            }

            Set<String> cardNumberSet =new HashSet<String>();
            StringBuffer cards = new StringBuffer();
            for (Map<String,String> readermap:readerList){
                if (readermap.get("读者证号") ==null || readermap.get("读者证号").trim().equals("")){
                    fail(0,"读者证号不能为空！");
                    return;
                }
                while (orgSetting !=null &&orgSetting.getJieshuzhengweishu() !=null && readermap.get("读者证号").length()<orgSetting.getJieshuzhengweishu()){
                    readermap.put("读者证号","0"+readermap.get("读者证号"));
                }
                if (orgSetting !=null && orgSetting.getJieshuzhengqianzhui() !=null && !orgSetting.getJieshuzhengqianzhui().equals("")){
                    readermap.put("读者证号",orgSetting.getJieshuzhengqianzhui()+readermap.get("读者证号"));
                }
                int size = cardNumberSet.size();
                cardNumberSet.add(readermap.get("读者证号"));
                if(size == cardNumberSet.size()){
                    cards = cards.append(readermap.get("读者证号")).append(" ");
                }
            }
            if (cardNumberSet.size() != readerList.size()){
                fail(0,"上传文件内读者证号重复！"+cards.toString());
                return;
            }

            List<Record> list = service.findReaderByCardNumber(cardNumberSet,orgid);
            if (list.size()>0){
                StringBuffer cards1 = new StringBuffer();
                for(Record record : list){
                    cards1 = cards1.append(record.getStr("cardnumber")).append(" ");
                }
                fail(0,cards1 + "读者证号重复！不能导入");
                return;
            }


            for (Map<String,String> readermap: readerList) {
                try{
                    Reader reader=new Reader();
                    reader.setOrgid(orgid); //所属机构
                    reader.setReadertypeid(dictMap.get(readermap.get("读者类型")));
                    if (reader.getReadertypeid() ==null){
                        readermap.put("未导入原因","读者类型不正确!");
                        errorDataList.add(readermap);
                        continue;
                    }

                    reader.setCardnumber(readermap.get("读者证号")); //'借书证号'
                    if(reader.getCardnumber()==null || reader.getCardnumber().trim().equals("")){
                        readermap.put("未导入原因","读者证号不能为空!");
                        errorDataList.add(readermap);
                        continue;
                    }



                    reader.setRealname(readermap.get("姓名")); // 真实姓名
                    reader.setSex(readermap.get("性别"));
                    reader.setPassword(CommonUtils.getMD5String(CommonUtils.getMD5String(PropKit.get("initPassword"))));

                    for (OrgDept orgDept : orgDeptList){
                        if (orgDept.getDeptname().equals(readermap.get("所属部门/班级"))){
                            reader.setOrgdeptid(orgDept.getId());
                            break;
                        }
                    }
                    if (reader.getOrgdeptid()==null){
                        readermap.put("未导入原因","所属部门/班级不正确!");
                        OrgDept orgDept = new OrgDept();
                        orgDept.setDeptname(readermap.get("所属部门/班级")).setOrgid(orgid).save();
                        reader.setOrgdeptid(orgDept.getId());
                        //errorDataList.add(readermap);
                        orgDeptList=orgDeptService.findOrgDept(orgid);
                        //continue;
                    }

                    reader.setReaderauthid(readerAuthMap.get(readermap.get("借阅权限")));
                    if(reader.getReaderauthid() ==null){
                        readermap.put("未导入原因","借阅权限不正确!");
                        errorDataList.add(readermap);
                        continue;
                    }

                    if (readermap.get("失效日期") !=null ){
                        reader.setLosedate(DateUtils.getSimpleDateFormat("yyyy-MM-dd").parse(readermap.get("失效日期")));
                    }

                    reader.setCertificatetypeid(dictMap.get(readermap.get("有效证件"))); //证件类型id
                    reader.setCertificate(readermap.get("证件号码"));
                    if (readermap.get("出生日期") !=null && !readermap.get("出生日期").equals("")){
                        reader.setBirthday(DateUtils.getSimpleDateFormat("yyyy-MM-dd").parse(readermap.get("出生日期")));
                    }

                    reader.setPhone(readermap.get("联系电话"));
                    reader.setEmail(readermap.get("'邮箱'"));
                    reader.setCreatetime(new Date());
                    reader.setOperatorid(operatorid);
                    reader.setStatus(1);

                    reader.save();
                    Map map = new HashMap();
                    map.put("orgid",reader.getOrgid()+"");
                    map.put("realname",reader.getRealname());
                    map.put("sex",reader.getSex());
                    if(CommonUtils.isNotNullOrNotEmpty(reader.getBirthday())){
                        map.put("birthday",format3.format(reader.getBirthday()));
                    }
                    map.put("readertypeid",reader.getReadertypeid()+"");
                    map.put("createtime",format3.format(reader.getCreatetime()));
                    Thread t = new Thread() {
                        public void run() {
                            HttpKit.get(PropKit.get("addReaderServiceUrl"), map);
                        }
                    };
                    t.start();
                }catch (Exception e){
                    e.printStackTrace();
                    if (e instanceof ParseException){
                        readermap.put("未导入原因","日期格式不正确");
                    }else{
                        readermap.put("未导入原因",e.getMessage());
                    }
                    errorDataList.add(readermap);
                }
            }
            String filename="";
            if (errorDataList.size()>0){
                filename="读者未导入列表"+ DateUtils.getNowTimeNo()+".xls";
                File targetFile =new File(getRequest().getRealPath("upload")+ File.separator+filename);
                ExcelUtil.writeExcel(targetFile,errorDataList,"读者未导入列表");
            }
            success(filename);
        }catch (Exception e){
            e.printStackTrace();
            fail(0,e.getMessage());
        }
    }


    public void export(){
        String path =getRequest().getRealPath("upload")+"/template/读者信息导入模板.xls";
        try{
            File targetFile =new File(path);
            Workbook workbook = WorkbookFactory.create(new FileInputStream(targetFile));
            Sheet sheet = workbook.getSheetAt(0);

            Reader bean = getBean(Reader.class,"bean");
            List<Record> readerList=service.export(bean);
            int rowindex=3;
            for (Record reader :readerList){
                Row row =sheet.getRow(rowindex);
                if (row==null){
                    row = sheet.createRow(rowindex);
                }
                row.createCell(0).setCellValue(reader.getStr("cardtypename"));
                row.createCell(1).setCellValue(reader.getStr("cardnumber"));
                row.createCell(2).setCellValue(reader.getStr("realname"));
                row.createCell(3).setCellValue(reader.getStr("sex"));
                row.createCell(4).setCellValue(reader.getStr("deptname"));
                row.createCell(5).setCellValue(reader.getStr("authname"));
                row.createCell(6).setCellValue(reader.getStr("losedate")==null?"":reader.getStr("losedate").split(" ")[0]);
                row.createCell(7).setCellValue(reader.getStr("certificatetypename"));
                row.createCell(8).setCellValue(reader.getStr("certificate"));
                rowindex++;
            }
            File tempFile =File.createTempFile("读者信息"+DateUtils.getSimpleDateFormat("yyyy-MM-dd").format(new Date()),".xls", new File(getRequest().getRealPath("upload")));
            FileOutputStream outputStream=new FileOutputStream(tempFile);
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
            renderFile(tempFile);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        Thread.sleep(100*60);
                        tempFile.delete();
                    }catch (Exception e){
                    }
                }
            }).start();
        }catch (Exception e){
            e.printStackTrace();
            fail();
        }
    }


    public void readerBioKey(){
        Integer orgid = getParaToInt("orgid");
        success(service.findBioKey(orgid));
    }

    public void uploadreaderinfopage(){
        render("/view/uploadorginfo/uploadreaderinfopage.html");
    }

    public void uploadreaderinfo(){
        UploadFile file = getFile();
        String token = this.getPara("token");
        Integer operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0) {
            fail(0,"权限异常");
            return;
        }
        User user = (User)getSession().getAttribute("userInfo");
        Integer orgid = user.getOrgid();
        if(CommonUtils.isNullOrEmpty(orgid)){
            fail(0,"orgid不能为空");
            return;
        }

        Record orgrecord = Db.findById("t_org",orgid);
        if(CommonUtils.isNullOrEmpty(orgrecord)){
            fail(0,"获取不到机构信息");
            return;
        }
        Calendar calendar = Calendar.getInstance();
        Calendar lostCalendar = Calendar.getInstance();
        lostCalendar.add(Calendar.YEAR,3);
        Record readerAuthRecord = Db.findFirst("select * from t_reader_auth where orgid = ? order by jieyueshuliang asc",orgid);
        List<Map<String,String>> errorDataList = new ArrayList<Map<String,String>>();
        try {
            List<Map<String,String>> readerList= readExcel(new FileInputStream(file.getFile()));
            for(Map map : readerList) {
                if (CommonUtils.isNullOrEmpty(map.get("所属用户"))){
                    map.put("未导入原因","所属用户不能为空!");
                    errorDataList.add(map);
                    continue;
                }
                if (CommonUtils.isNullOrEmpty(map.get("班级/部门"))){
                    map.put("未导入原因","班级/部门不能为空!");
                    errorDataList.add(map);
                    continue;
                }
                if (CommonUtils.isNullOrEmpty(map.get("卡序列号"))){
                    map.put("未导入原因","卡序列号不能为空!");
                    errorDataList.add(map);
                    continue;
                }
                Reader reader = new Reader();
                String cardnumber = map.get("卡序列号").toString();
//                long valueTen = Long.parseLong(cardnumber);
                //将其转换为十六进制并输出
//                char a[] = Long.toHexString(valueTen).toUpperCase().toCharArray();
                try{
//                    cardnumber = ""+a[6]+a[7]+a[4]+a[5]+a[2]+a[3]+a[0]+a[1];
                    cardnumber = CommonUtils.toHexFormat(cardnumber,8);
                    Record readerre = Db.findFirst("select id from t_reader where orgid = ? and (cardnumber = ? or readcardcode = ?)",orgid,cardnumber,cardnumber);
                    if(CommonUtils.isNotNullOrNotEmpty(readerre)){
                        map.put("未导入原因","读者重复!"+cardnumber);
                        errorDataList.add(map);
                        continue;
                    }
                }catch (Exception e) {
                    logger.info("条码转换异常",e);
                    map.put("未导入原因","条码转换异常!");
                    errorDataList.add(map);
                    continue;
                }
                reader.setOrgid(orgid);
                String className = map.get("班级/部门").toString();
                String replaceClassName = map.get("班级/部门").toString();
                if(className.indexOf("C") == 0){
                    replaceClassName = replaceClassName.replace("C","初");
                } else if(className.indexOf("G") == 0){
                    replaceClassName = replaceClassName.replace("G","高");
                } else {
                    replaceClassName = "默认部门";
                }
                Record orgdeptRecord = Db.findFirst("select * from t_org_dept where (deptname = ? or deptname = ?) and orgid = ?",replaceClassName,className,orgid);
                if(CommonUtils.isNullOrEmpty(orgdeptRecord)) {
                    replaceClassName = "默认部门";
                    orgdeptRecord = Db.findFirst("select * from t_org_dept where (deptname = ? or deptname = ?) and orgid = ?",replaceClassName,className,orgid);
                }
                if(CommonUtils.isNullOrEmpty(orgdeptRecord)){
                    OrgDept newRecord = new OrgDept();
                    newRecord.set("deptname","默认部门");
                    newRecord.set("orgid",orgid);
                    newRecord.set("readerauthid",0); //机构暂无默认权限
                    newRecord.set("createtime",new Date());
                    newRecord.set("operatorid",0);
                    newRecord.save();
                    reader.setOrgdeptid(newRecord.getId());
                } else {
                    reader.setOrgdeptid(orgdeptRecord.getInt("id"));
                }
                reader.setCardnumber(cardnumber);
                reader.setRealname(map.get("所属用户").toString());
                reader.setPassword(cardnumber);
                reader.setReadcardcode(cardnumber);
                reader.setCreatetime(calendar.getTime());
                reader.setLosedate(lostCalendar.getTime());
                reader.setStatus(1);
                reader.setReadertypeid(62);
                reader.setReaderauthid(readerAuthRecord.getInt("id"));
                reader.setOverdue(0);
                reader.save();

                Map dateplatMap = new HashMap();
                dateplatMap.put("orgid",reader.getOrgid()+"");
                dateplatMap.put("realname",reader.getRealname());
                dateplatMap.put("sex",reader.getSex());
                if(CommonUtils.isNotNullOrNotEmpty(reader.getBirthday())){
                    dateplatMap.put("birthday",format3.format(reader.getBirthday()));
                }
                dateplatMap.put("readertypeid",reader.getReadertypeid()+"");
                dateplatMap.put("createtime",format3.format(reader.getCreatetime()));
                Thread t = new Thread() {
                    public void run() {
                        HttpKit.get(PropKit.get("addReaderServiceUrl"), dateplatMap);
                    }
                };
                t.start();
//                logger.info("读者保存成功 realname:"+reader.getRealname()+"  cardnumber:"+reader.getCardnumber());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String filename="";
        if (errorDataList.size()>0){
            filename="未导入列表"+ DateUtils.getNowTimeNo()+".xls";
            File targetFile =new File(getRequest().getRealPath("upload")+ File.separator+filename);
            ExcelUtil.writeExcel(targetFile,errorDataList,"未导入列表");
        }
        success(filename);
    }


    public List<Map<String,String>> readExcel(InputStream in){
        List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
        try{
            // 获得工作簿
            Workbook workbook = WorkbookFactory.create(in);
            // 获得工作表个数
            int sheetCount = workbook.getNumberOfSheets();
            // 遍历工作表
            for (int i = 0; i < sheetCount; i++)
            {
                Sheet sheet = workbook.getSheetAt(i);
                // 获得行数
                int rows = sheet.getLastRowNum() + 1;
                // 读取数据
                for (int rownum = 1; rownum < rows; rownum++)                {
                    Map<String,String> rowMap = new LinkedHashMap<String, String>();
                    Row r = sheet.getRow(rownum);
                    if(r ==null) continue;
                    boolean flag = false; //行数据全部为空，不继续读
                    for (int col = 0; col < sheet.getRow(2).getLastCellNum(); col++)
                    {
                        Cell cell = r.getCell(col);
                        if(cell !=null){
                            String value = getCellValue(cell);
                            if (!"".equals(value.trim())){
                                flag=true;
                            }
                            rowMap.put(getCellValue(sheet.getRow(0).getCell(col)),value);
                        }else {
                            rowMap.put(getCellValue(sheet.getRow(0).getCell(col)),"");
                        }

                    }
                    if (flag){
                        dataList.add(rowMap);
                    }
                }
            }
        }catch (Exception e) {
        }
        return dataList;
    }

    public String getCellValue(Cell cell){
        if(cell.getCellType() == CellType.NUMERIC){
            short format = cell.getCellStyle().getDataFormat();
            SimpleDateFormat sdf = null;
            if(format == 14 || format == 31 || format == 57 || format == 58){
                //日期
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            }else if (format == 20 || format == 32) {
                //时间
                sdf = new SimpleDateFormat("HH:mm");
            }else { // 不是日期格式
                NumberFormat nf = NumberFormat.getInstance();
                String s = nf.format(cell.getNumericCellValue());
                if (s.indexOf(",") >= 0) {
                    s = s.replace(",", "");
                }
                return s;
            }
            double value = cell.getNumericCellValue();
            Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
            return sdf.format(date);
        } else if (cell.getCellType() == CellType.BOOLEAN){
            return cell.getBooleanCellValue()+"";
        }else {
            return cell.getStringCellValue();
        }

    }


}
