TaxDocumentController.java 12.6 KB
Newer Older
chase's avatar
chase committed
1 2
package pwc.taxtech.atms.controller;

chase's avatar
chase committed
3 4
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
chase's avatar
chase committed
5 6 7
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
chase's avatar
chase committed
8
import net.sf.json.JSONNull;
chase's avatar
chase committed
9
import org.apache.commons.lang3.StringUtils;
chase's avatar
chase committed
10 11 12 13 14 15
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
chase's avatar
chase committed
16 17 18 19 20 21 22 23 24 25 26 27
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pwc.taxtech.atms.common.PageResultVo;
import pwc.taxtech.atms.common.util.DateUtils;
import pwc.taxtech.atms.dto.TaxDocumentDto;
import pwc.taxtech.atms.entity.TaxDocument;
import pwc.taxtech.atms.service.impl.TaxDocumentServiceImpl;
import pwc.taxtech.atms.thirdparty.ExcelUtil;

import javax.servlet.http.HttpServletResponse;
chase's avatar
chase committed
28 29 30
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
chase's avatar
chase committed
31
import java.text.SimpleDateFormat;
chase's avatar
chase committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/api/v1/taxDoc")
public class TaxDocumentController {

    @Autowired
    private TaxDocumentServiceImpl taxDocumentService;

    @PostMapping("selectList")
    @ResponseBody
    public PageResultVo<TaxDocument> selectTaxDocumentList(@RequestBody TaxDocumentDto taxDocumentDto) {
        Page<TaxDocument> page = PageHelper.startPage(taxDocumentDto.getCurrentPage(), taxDocumentDto.getPageSize());
        taxDocumentService.selectTaxDocumentList(taxDocumentDto);
        PageInfo<TaxDocument> taxDocumentPageInfo = page.toPageInfo();
        List<TaxDocument> list = taxDocumentPageInfo.getList();
        return PageResultVo.getPageResultVo(taxDocumentPageInfo, list);
    }

    @PostMapping("/queryWhetherData")
    @ResponseBody
    public boolean queryWhetherData(@RequestBody TaxDocument taxDocument) {
        return taxDocumentService.queryWhetherData(taxDocument);
    }

    @PostMapping("add")
    @ResponseBody
chase's avatar
chase committed
62 63
    public boolean addTaxDocument(TaxDocument taxDocument,
                                  @RequestParam("file") MultipartFile file) {
chase's avatar
chase committed
64
        return taxDocumentService.addTaxDocumentList(file,taxDocument);
chase's avatar
chase committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    }

    @PostMapping("delete")
    @ResponseBody
    public boolean deleteTaxDocument(@RequestBody TaxDocument taxDocument) {
        return taxDocumentService.deleteTaxDocument(taxDocument.getId());
    }

    @PostMapping("/batchDelete")
    @ResponseBody
    public boolean batchDelete(@RequestBody TaxDocumentDto taxDocumentDto) {
        return taxDocumentService.batchDelete(taxDocumentDto.getIds());
    }

    @PostMapping("edit")
    @ResponseBody
    public boolean editTaxDocument(@RequestBody TaxDocument taxDocument) {
        return taxDocumentService.editFilesType(taxDocument);
    }

chase's avatar
chase committed
85

chase's avatar
chase committed
86 87
    @RequestMapping("exportExcel")
    @ResponseBody
chase's avatar
chase committed
88
    public void exportExcelFile(HttpServletResponse response, @RequestBody TaxDocumentDto taxDocumentDto) {
chase's avatar
chase committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        try {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("id", "id");
            headers.put("file_attr", "档案属性");
            headers.put("file_type", "档案类型");
            headers.put("file_name", "档案名称");
            headers.put("business_line", "业务线");
            headers.put("company_name", "公司名称");
            headers.put("tax_type", "税种");
            headers.put("file_time", "文件日期");
            headers.put("effective_time", "有效日期");
            headers.put("creator", "创建人");
            headers.put("create_time", "创建时间");
            headers.put("upload_time", "上传日期");
            headers.put("storage_area", "实物存放地点");
            headers.put("keeper", "保管人");
            headers.put("remark", "档案备注");
            headers.put("file_position_url", "文件存储的位置");
            List<TaxDocument> TaxDocument = taxDocumentService.selectTaxDocumentList(taxDocumentDto);
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String("".getBytes("GB2312"), "ISO-8859-1"));
            OutputStream ouputStream = response.getOutputStream();
            ExcelUtil.exportExcel(headers, TaxDocument, ouputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传接口 createByZhangzezheng
     *
     * @param picture 图片文件
     * @param modual  模块名
     * @return
     */
    @RequestMapping("upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture, @RequestParam(required = false) String modual) {
chase's avatar
chase committed
127 128 129 130 131 132
        return getUploadUrl(picture, modual);
    }

    /**
     * 生成上传url
     *
chase's avatar
chase committed
133
     * @param file
chase's avatar
chase committed
134 135 136
     * @param modual
     * @return
     */
chase's avatar
chase committed
137 138
    private String getUploadUrl(MultipartFile file, String modual) {
        String fileName = file.getOriginalFilename();
chase's avatar
chase committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        String pictureName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String dir = DateUtils.getStringDateShort();
        String typePath = "";
        try {
            String fileSavePath = File.separator + "images";
            if (StringUtils.isBlank(modual)) {
                modual = "default";
            }
            if (StringUtils.isNotBlank(modual)) {
                typePath = modual + File.separator + dir;
            }
            File basePath = new File(fileSavePath + File.separator + typePath);
            if (!basePath.exists()) {
                basePath.mkdirs();
            }
chase's avatar
chase committed
154
            file.transferTo(new File(fileSavePath + File.separator + typePath + File.separator + pictureName));
chase's avatar
chase committed
155 156 157 158 159
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "images" + File.separator + typePath + File.separator + pictureName;
    }
chase's avatar
chase committed
160 161


chase's avatar
chase committed
162 163
    /**
     * 读取Excel转换成 Json
chase's avatar
chase committed
164
     * @param taxDocumentDto 文件的路径
chase's avatar
chase committed
165 166 167
     */
    @PostMapping("/previewExcelToJson")
    @ResponseBody
chase's avatar
chase committed
168
    public String previewExcel(@RequestBody TaxDocumentDto taxDocumentDto) {
chase's avatar
chase committed
169 170
        try {
            JSONArray dataArray = new JSONArray();
chase's avatar
chase committed
171
            URL httpurl=new URL(taxDocumentDto.getPath());
chase's avatar
chase committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
            InputStream is;
            HttpURLConnection httpConn=(HttpURLConnection)httpurl.openConnection();
            httpConn.setDoOutput(true);// 使用 URL 连接进行输出
            httpConn.setDoInput(true);// 使用 URL 连接进行输入
            httpConn.setUseCaches(false);// 忽略缓存
            httpConn.setRequestMethod("GET");// 设置URL请求方法
            //可设置请求头
            httpConn.setRequestProperty("Content-Type", "application/octet-stream");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            httpConn.setRequestProperty("Charset", "UTF-8");
            httpConn.connect();
            if (httpConn.getResponseCode() >= 400 ) {
                is = httpConn.getErrorStream();
            }
            else{
                is = httpConn.getInputStream();
            }
            InputStream inStream =is;
chase's avatar
chase committed
190

chase's avatar
chase committed
191
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inStream);
chase's avatar
chase committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
                XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
                String sheetName = xssfSheet.getSheetName();
                if (xssfSheet == null) {
                    continue;
                }
                //当前sheet的json文件
                JSONObject sheetJson = new JSONObject();
                //当前sheet的array,作为sheetJson 的value值
                JSONArray sheetArr = new JSONArray();
                //sheet的第一行,获取作为json的key值
                JSONArray key = new JSONArray();
                int xssfLastRowNum = xssfSheet.getLastRowNum();
                // 循环行Row
                for (int rowNum = 0; rowNum <= xssfLastRowNum; rowNum++) {
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                    if (xssfRow == null) {
                        continue;
                    }

                    // 循环列Cell,在这里组合json文件
                    int firstCellNum = xssfRow.getFirstCellNum();
                    int lastCellNum = xssfRow.getLastCellNum();
                    JSONObject rowJson = new JSONObject();
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        XSSFCell cell = null;
                        try {
                            cell = xssfRow.getCell(cellNum);
                            if (cell == null) {
                                rowJson.put(key.getString(cellNum), "");
                                continue;
                            }
                            if (rowNum == 0)
                                key.add(toString(cell));
                            else {
                                //若是列号超过了key的大小,则跳过
                                if (cellNum >= key.size()) continue;
                                rowJson.put(key.getString(cellNum), toString(cell));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (rowJson.keySet().size() > 0)
                        sheetArr.add(rowJson);
                }
                sheetJson.put(sheetName, shuffleData(sheetArr));
                dataArray.add(sheetJson);
            }
            return dataArray.toString();
chase's avatar
chase committed
243
        } catch (Exception e) {
chase's avatar
chase committed
244 245 246 247 248
            e.printStackTrace();
            return JSONNull.getInstance().toString();
        }
    }

chase's avatar
chase committed
249 250 251 252 253 254 255
    /**
     * 下载全部附件
     */
    @PostMapping(value = "/downloadAllFile")
    public void  downloadAllFile(HttpServletResponse response, @RequestBody TaxDocumentDto taxDocumentDto) {
        taxDocumentService.downloadAllFile(response,taxDocumentDto.getIds());
    }
chase's avatar
chase committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

    /**
     * 解析json
     * @param cell
     * @return
     */
    private static Object toString(XSSFCell cell) {
        switch (cell.getCellTypeEnum()) {
            case _NONE:
                cell.setCellType(CellType.STRING);
                return "";
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    return sdf.format(cell.getDateCellValue());
                }
                cell.setCellType(CellType.STRING);
                return cell.getStringCellValue();
            case STRING:
                String val = cell.getStringCellValue();
                if ("无".equalsIgnoreCase(val)) return "";
                //将其中的map格式和数组格式的字符串,转化为相应的数据类型
                if (val.indexOf("{") > -1) {
//                    JSONObject jsonObject = JSONObject.parseObject(val);
                    Map<String, Integer> mapJson = JSONObject.parseObject(val,HashMap.class);
                    return mapJson;
                }
                if (val.indexOf("[") > -1) {
                    val = val.substring(1, val.length() - 1);
                    String[] array = val.split(",");
                    return array;
                }
                return val;
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            case BOOLEAN:
                return cell.getBooleanCellValue() + "";
            case ERROR:
                return "非法字符";
            default:
                return "未知字符";
        }
    }

    /**
     * 输出数据
     */
    private static JSONArray shuffleData(JSONArray sheetArr) {
        JSONArray array = new JSONArray();
        for (int i = 0; i < sheetArr.size(); i++) {
            JSONObject object = sheetArr.getJSONObject(i);
            int count = 0;
            int length = 0;
            for (Object key : object.keySet()) {
                Object o = object.get((String) key);
                length++;
                boolean b = StringUtils.isEmpty(o.toString());
                if (b) {
                    count++;
                }
            }
            if (count != length) {
                array.add(object);
            }
        }
        return array;
    }
chase's avatar
chase committed
325
}