package com.th.demo.service.impl.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.th.demo.mapping.common.CommonFilePathMapper;
import com.th.demo.mapping.common.CommonImagePathMapper;
import com.th.demo.mapping.common.CommonMapper;
import com.th.demo.mapping.system.SysDicMapper;
import com.th.demo.mapping.system.SysUserMapper;
import com.th.demo.model.common.CommonFilePath;
import com.th.demo.model.common.CommonImagePath;
import com.th.demo.model.develop.DevUpdown;
import com.th.demo.model.develop.DevUpdownPaths;
import com.th.demo.model.system.*;
import com.th.demo.service.common.CommonService;
import com.th.demo.tools.JSONTools;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("CommonService")
public class CommonServiceImpl implements CommonService {

    @Autowired
    CommonMapper commonMapper;
    @Autowired
    CommonImagePathMapper commonImagePathMapper;
    @Autowired
    CommonFilePathMapper commonFilePathMapper;
    @Autowired
    SysDicMapper sysDicMapper;
    String result = Type.FAIL;
    String rowsTotal = "0";

    @Override
    public String queryPrimaryKey() {
        String primaryKey = commonMapper.selectPrimaryKey();
        result = JSON.toJSONString(new ResultJSON(ResponseCodeMsg.CODE_OK, ResponseCodeMsg.MSG_OK, primaryKey));
        return result;
    }


    @Override
    public String doProc(String procName, String param) {
        List<String> list = JSON.parseArray(param, String.class);
        String s_result = "";
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("procName", procName);
        map.put("param", list);
        map.put("results", "");
        commonMapper.updateProc(map);
        s_result = (String) map.get("results");
        return JSON.toJSONString(new ResultJSON(ResponseCodeMsg.CODE_OK, ResponseCodeMsg.MSG_OK, s_result));
    }


    @Override
    public String doProcQuery(String procName, String param) {
        result = Type.FAIL;
        rowsTotal = "0";

        List<String> listParam = JSON.parseArray(param, String.class);
        HashMap<String, Object> mapList = new HashMap<String, Object>();
        List<HashMap<String, String>> listResult = new ArrayList<HashMap<String, String>>();
        mapList.put("procName", procName);
        mapList.put("param", listParam);
        mapList.put("results", null);
        commonMapper.selectProc(mapList);
        listResult = (List<HashMap<String, String>>) mapList.get("results");

        result = JSON.toJSONString(new ResultJSON(ResponseCodeMsg.CODE_OK, ResponseCodeMsg.MSG_OK, listResult));
        return result;
    }


    @Override
    public String doProcQueryPage(String procName, int page, int rows, String param) {
        result = Type.FAIL;
        rowsTotal = "0";

        List<String> listParam = JSON.parseArray(param, String.class);


        HashMap<String, Object> mapRows = new HashMap<String, Object>();
        mapRows.put("procName", procName + "Rows");
        mapRows.put("param", listParam);
        mapRows.put("results", "");
        commonMapper.selectProcRows(mapRows);
        rowsTotal = (String) mapRows.get("results");

        HashMap<String, Object> mapList = new HashMap<String, Object>();
        List<HashMap<String, String>> listResult = new ArrayList<HashMap<String, String>>();
        mapList.put("procName", procName + "List");
        mapList.put("param", listParam);
        mapList.put("startRows", ((page - 1) * rows) + 1);
        mapList.put("endRows", page * rows);
        mapList.put("results", null);
        commonMapper.selectProcList(mapList);
        listResult = (List<HashMap<String, String>>) mapList.get("results");

        JSONObject ob = new JSONObject();
        ob.put("rows", Integer.parseInt(rowsTotal));
        ob.put("list", listResult);
        result = JSON.toJSONString(new ResultJSON(ResponseCodeMsg.CODE_OK, ResponseCodeMsg.MSG_OK, ob));
        return result;
    }

    @Transactional
    @Override
    public String uploadImage(HttpServletRequest request) throws IOException {
        String result = Type.FAIL;
        String realPath = "";
        String relativePath = "";
        String projectPath = request.getSession().getServletContext().getRealPath("");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String param = multipartRequest.getParameter("fid");
        MultiValueMap<String, MultipartFile> files = multipartRequest.getMultiFileMap();
        for (int i = 0; i < files.get("file").size(); i++) {
            String primaryKey = commonMapper.selectPrimaryKey();

            MultipartFile mf = files.get("file").get(i);
            int index = mf.getOriginalFilename().lastIndexOf(".");
            String front = mf.getOriginalFilename().substring(0, index);
            String last = mf.getOriginalFilename().substring(index + 1);
            realPath = projectPath + "/pic/" + primaryKey + "." + last;//mf.getOriginalFilename();
            relativePath = "/pic/" + primaryKey + "." + last;//mf.getOriginalFilename();

            File tempFile = new File(realPath);
            mf.transferTo(tempFile);
            // Thumbnails.of(front+"_normal."+behind).size(80, 80).toFile(front+"_small."+behind);

            CommonImagePath commonImagePath = new CommonImagePath();

            commonImagePath.setId(primaryKey);
            commonImagePath.setfId(param);
            commonImagePath.setImageName(front + "." + last);
            commonImagePath.setImagePath(relativePath);
            commonImagePathMapper.insert(commonImagePath);

//            CommonImagePath commonImagePathSmall = new CommonImagePath();
//            commonImagePathSmall.setfId(param);
//            commonImagePathSmall.setImagePath(front+"_small."+behind);
//            commonImagePathMapper.insert(commonImagePathSmall);
        }
        result = JSONTools.toString(Type.SUCCESS);
        return result;
    }

    @Override
    public String queryImage(String fid) {
        List<CommonImagePath> list = commonImagePathMapper.selectByFid(fid);
        result = JSONTools.toString(list);
        return result;
    }

    @Transactional
    @Override
    public String uploadFile(HttpServletRequest request) throws IOException {
        String result = Type.FAIL;
        String realPath = "";
        String relativePath = "";
        String projectPath = request.getSession().getServletContext().getRealPath("");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String param = multipartRequest.getParameter("fid");
        String fileType = multipartRequest.getParameter("fileType");
        MultiValueMap<String, MultipartFile> files = multipartRequest.getMultiFileMap();
        for (int i = 0; i < files.get("file").size(); i++) {
            String primaryKey = commonMapper.selectPrimaryKey();

            MultipartFile mf = files.get("file").get(i);
            int index = mf.getOriginalFilename().lastIndexOf(".");
            String front = mf.getOriginalFilename().substring(0, index);
            String last = mf.getOriginalFilename().substring(index + 1);
            realPath = projectPath + "/doc/" + primaryKey + "." + last;//mf.getOriginalFilename();
            relativePath = "/doc/" + primaryKey + "." + last;//mf.getOriginalFilename();

            File tempFile = new File(realPath);
            mf.transferTo(tempFile);

            CommonFilePath commonFilePath = new CommonFilePath();
            commonFilePath.setId(primaryKey);
            commonFilePath.setfId(param);
            commonFilePath.setFileName(front + "." + last);
            commonFilePath.setFilePath(relativePath);
            commonFilePath.setFileType(fileType);
            commonFilePathMapper.insert(commonFilePath);

        }
        result = JSONTools.toString(Type.SUCCESS);
        return result;
    }


    @Override
    public String uploadOneFileWithResult(HttpServletRequest request) throws IOException {
        String result = Type.FAIL;
        String realPath = "";
        String relativePath = "";
        String projectPath = request.getSession().getServletContext().getRealPath("");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String param = multipartRequest.getParameter("fid");
        MultiValueMap<String, MultipartFile> files = multipartRequest.getMultiFileMap();
        if (files.get("file").size() > 1) {
            result = JSONTools.toString(1,"请上传单个文件！");
        } else {

                String primaryKey = commonMapper.selectPrimaryKey();
                MultipartFile mf = files.get("file").get(0);
                int index = mf.getOriginalFilename().lastIndexOf(".");
                String front = mf.getOriginalFilename().substring(0, index);
                String last = mf.getOriginalFilename().substring(index + 1);
                realPath = projectPath + "/doc/" + primaryKey + "." + last;//mf.getOriginalFilename();
                relativePath = "/doc/" + primaryKey + "." + last;//mf.getOriginalFilename();
                File tempFile = new File(realPath);
                mf.transferTo(tempFile);
                CommonFilePath commonFilePath = new CommonFilePath();
                commonFilePath.setId(primaryKey);
                commonFilePath.setfId(param);
                commonFilePath.setFileName(front + "." + last);
                commonFilePath.setFilePath(relativePath);
                commonFilePathMapper.insert(commonFilePath);

            result = JSONTools.toString(commonFilePath);
        }

        return result;
    }

    @Override
    public void downloadByStream(String id,HttpServletRequest request, HttpServletResponse response) {
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            String fileName = null;
        CommonFilePath commonFilePath = commonFilePathMapper.selectByPrimaryKey(id);
        String projectPath = request.getSession().getServletContext().getRealPath("");
        String realPath =projectPath+commonFilePath.getFilePath();
        System.out.println("realPath:"+realPath);
      //String path = realPath + File.separator + name;
        File file = new File(realPath);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String( commonFilePath.getFileName().getBytes("gb2312"), "ISO8859-1" ) );
        byte[] buff = new byte[1024];


            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    @Override
    public String queryFile(String fid) {
        List<CommonFilePath> list = commonFilePathMapper.selectByFid(fid);
        result = JSONTools.toString(list);
        return result;
    }

    @Override
    public String removeFile(String id, HttpServletRequest request) {
        CommonFilePath commonFilePath = commonFilePathMapper.selectByPrimaryKey(id);
        String projectPath = request.getSession().getServletContext().getRealPath("");
        File file = new File(projectPath + commonFilePath.getFilePath());
        if (file.exists()) {
            file.delete();
        }
        commonFilePathMapper.deleteByPrimaryKey(id);
        return JSONTools.toString(Type.SUCCESS);
    }

    @Override
    public String removeImage(String id, HttpServletRequest request) {
        return null;
    }

    @Override
    public String querySelector(String type) {
        List<SysDic> list = sysDicMapper.selectByDicType(type);
        result = JSONTools.toString(list);
        return result;
    }


}
