package com.zjty.tynotes.pas.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.zjty.tynotes.misc.config.AutoDocument;
import com.zjty.tynotes.misc.utils.ExcelUtil;
import com.zjty.tynotes.pas.dao.PasUserDao;
import com.zjty.tynotes.pas.entity.Address;
import com.zjty.tynotes.pas.entity.User;
import com.zjty.tynotes.pas.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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;

import static org.springframework.http.ResponseEntity.ok;

/**
 * @Author gwj
 * @create 2020/4/24 9:36
 * excel导入视图层
 */
@Api(tags = "用户管理权限管理模块",protocols = "http")
@RestController
@RequestMapping("/pas/excel")
@AutoDocument
public class ExcelController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private PasUserDao pasUserDao;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private String addressUrl = "address.xls";

    @ApiOperation(value = "上传excel通讯录")
    @PostMapping("/import")
    public List<Address> upload(@RequestParam("file") MultipartFile multipartFile,HttpServletRequest request,HttpServletResponse response) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(4);
//        params.setNeedVerfiy(true);
//         params.setTitleRows(1);
        List<Address> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                Address.class, params);
        List<User> users = new ArrayList<>();
        System.out.println(result);
        if(result!=null){
            result.forEach(address -> {
                User user = pasUserDao.findByUsername(address.getName());
                if(user==null){
                    User user1 = new User(address);
                    user1.setPassword(bCryptPasswordEncoder.encode("qwer1234"));

                    boolean flag = true;
                    if(users!=null){
                        for (User user2 : users) {
                            if(user2.getUsername().equals(address.getName())){
                                flag = false;
                            }
                        }
                    }
                    if(flag){
                        users.add(user1);
                    }
                }
            });
        }
        pasUserDao.saveAll(users);
        return result;
    }

    @ApiOperation(value = "导出所有人的excel通讯录")
    @PostMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        //把要导出的信息放在map里面
        List<Map<String, Object>> excelList = new ArrayList<>();
        //构建创建导出excel表格所需要的Workbook对象的map
        //源数据
        List<User> users = iUserService.findAll();
        List<Address> addresses = new ArrayList<>();
        if(users!=null){
            int i = 1;
            for (User user : users) {
                if(!user.getUsername().equals("HR")){
                    Address address = new Address(user);
                    address.setId(i+"");
                    addresses.add(address);
                    i++;
                }
            }
        }
        Map<String, Object> map = new HashMap<>(8);
        String FpName="用户通讯录";
        map.put("subFpName", FpName);
        ExportParams exportParams = new ExportParams(FpName, FpName);
//        exportParams.setAddIndex(true);
        map.put("title", exportParams);
        map.put("entity", Address.class);
        map.put("data",addresses);
        excelList.add(map);

        Workbook workbook = ExcelExportUtil.exportExcel(excelList, ExcelType.HSSF);

        ExcelUtil.downloadExcel(request, response, workbook, FpName);
    }

    @ApiOperation(value = "下载通讯录模板")
    @PostMapping("/download")
    public ResponseEntity download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filename= "address.xls";
        File file = ResourceUtils.getFile("classpath:address.xls");
//        File file = new File("src/main/resources/address.xls");
//        System.out.println(addressUrl);
//        System.out.println("存在？？");
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
                return ok("下载成功");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return ok("下载失败");
    }

//    public static void main(String[] args) {
//        File file = new File("a.txt");
//        if(!file.exists()){
//            try {
//                file.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

}
