package com.casic.PgInterface.construction.manager;

import com.casic.PgInterface.construction.domain.PgConstruction;
import com.casic.PgInterface.construction.domain.PgCsDocument;
import com.casic.PgInterface.construction.dto.PgCsDocumentDto;
import com.casic.PgInterface.core.hibernate.HibernateEntityDao;

import org.apache.commons.codec.binary.Base64;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by zxh on 2018/3/28.
 */
@Service
public class PgCsDocumentManager extends HibernateEntityDao<PgCsDocument>{

    private PgConstructionManager pgConstructionManager;

    @Resource
    public void setPgConstructionManager(PgConstructionManager pgConstructionManager) {
        this.pgConstructionManager = pgConstructionManager;
    }

    public  String saveFiles(String fileBuffer, String fileName, String fileType){

        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String strDirPath = request.getSession().getServletContext().getRealPath("");

            FileOutputStream fos = null;
            String image_toDir = strDirPath + "\\"+fileType;//存储路径
            String imageName = "";
            imageName += fileType+"/"+fileName;
            byte[] buffer = Base64.decodeBase64(fileBuffer.getBytes());
//            byte[] buffer = new BASE64Decoder().decodeBuffer(fileBuffer);//对android传过来的图片字符串进行解码
            File destDir = new File(image_toDir);
            if (!destDir.exists())
                destDir.mkdirs();
            File imageFile = new File(destDir, fileName);
            fos = new FileOutputStream(imageFile);//保存文件
            fos.write(buffer);
            fos.flush();
            fos.close();
            return imageName;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return "";
        }
    }

    /*下载文件*/
    public ResponseEntity<byte[]> downloadFile(PgCsDocument pgCsDocument) throws Exception {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String path = request.getSession().getServletContext().getRealPath("");
            String filePath = path + "\\"+pgCsDocument.getConstruct_doc();
            File file = new File(filePath);//找到具体的文件
            byte[] body = null;
            InputStream inputStream = new FileInputStream(file);
            body = new byte[inputStream.available()];
//            body=readInputStream(inputStream);
            inputStream.read(body);

            HttpHeaders headers = new HttpHeaders();
            /*MediaType mediaType = new MediaType("text", "html", Charset.forName("UTF-8"));*/
            headers.add("Content-Disposition",file.getName());
            /*headers.set("contentType","text/html;charset=utf-8");
            headers.setContentType(mediaType);*/
            HttpStatus status = HttpStatus.OK;
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, status);

            return entity;
            //inputStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
//        inStream.close();
        return outStream.toByteArray();
    }

    /*查询*/
    public List<PgCsDocumentDto> getAllDocData(String cs_name) {

        List<PgCsDocumentDto> pgCsDocumentDtoList = new ArrayList<>();
        try {
            PgConstruction pgConstruction = pgConstructionManager.getPgContructionByName(cs_name);
            if(pgConstruction==null)
                return null;
            else
            {
                String sql="select id,doc_name from PG_CSDOCUMENT where PGCONSTRUCTION_ID = " + pgConstruction.getId() +" and active = 1";
                List<Object[]> objectList=this.getSession().createSQLQuery(sql).list();

                for(Object[] objectArray : objectList)
                {
                    pgCsDocumentDtoList.add(getDtoByObject(objectArray,pgConstruction));
                }

                return pgCsDocumentDtoList;
            }
        } catch (Exception ex) {
            return null;
        }
    }

    private PgCsDocumentDto getDtoByObject(Object[] objectArray,PgConstruction pgConstruction){
        PgCsDocumentDto pgCsDocumentDto=new PgCsDocumentDto();

        pgCsDocumentDto.setId(objectArray[0]==null?"":objectArray[0].toString());
        pgCsDocumentDto.setDoc_name(objectArray[1]==null?"":objectArray[1].toString());
        pgCsDocumentDto.setCs_name(pgConstruction.getCs_name());
        pgCsDocumentDto.setCs_type(pgConstruction.getCs_type());

        return pgCsDocumentDto;
    }


}