package com.ag.demo;


import cn.hutool.core.collection.CollUtil;
import com.ag.base.BaseService;
import com.ag.base.DefaultBussniessImpl;
import com.ag.demo.entity.Student;
import com.ag.log.OperLogServcie;
import com.ag.log.UserDefineLogService;
import com.ag.log.entity.LogParam;
import com.ag.util.Base64Util;
import com.ag.util.ExcelPoiUtil;
import com.ag.util.UUIDUtil;
import com.alibaba.fastjson.JSON;
import com.opencsv.CSVWriter;
import com.wb.util.WebUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;

/**
 * Created by yangxh on 2021/5/28.
 */
@Service
public class DemoService extends BaseService {

    @Autowired
    private DefaultBussniessImpl bizDao;
    @Autowired
    private OperLogServcie logServcie;
    @Autowired
    private UserDefineLogService userDefineLogService;

    public void testRequest(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
        try {
            WebUtil.send(response, "ok");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void save(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
        Student stu = JSON.parseObject(param.getString("data"), Student.class);
        //Student stu = new ParamUtil<Student>().packPOJO(super.getRequestMap(request), Student.class);
        stu.setsId(UUIDUtil.getUUID());
        bizDao.save(stu);
        try {
            LogParam logParam = new LogParam(param, stu.getName(), "tstudent", "C", "data");
            logParam.setMenuName("日志示例");
            logParam.setPrimaryKeyColName("S_ID");
            logParam.setCreateDataId(stu.getsId());
            logServcie.saveLogPanel(logParam, response);
            /*LogParam logParam = new LogParam(param, stu.getName(), "tstudent", "save~~~~~~~~~~~~~~~~~~");
            userDefineLogService.saveLog(logParam);*/
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 单条数据修改记录日志示例
     * @param param
     * @param response
     * @param request
     */
    public void update(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
        Student stu = JSON.parseObject(param.getString("data"), Student.class);
        //super.setUpdateUser(param, stu);
        //Student stu = new ParamUtil<Student>().packPOJO(super.getRequestMap(request), Student.class);
        //bizDao.update(stu, "S_ID");
        stu = (Student) bizDao.findById(stu, Student.class, "S_ID");
        try {
            LogParam logParam = new LogParam(param, stu.getName(), "tstudent", "U", "data");
            logParam.setUpdate(CollUtil.newArrayList(stu));//包装更新前的原始数据
            logParam.setMenuName("日志示例");
            logParam.setPrimaryKeyColName("S_ID");//如果主键为ID，可不指定
            logServcie.saveLogPanel(logParam, response);
            /*logParam = new LogParam(param, stu.getName(), "tstudent", "update~~~~~~~~~~~~~~~~~~");
            userDefineLogService.saveLog(logParam);*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量修改记录日志示例
     * @param param
     * @param response
     * @param request
     */
    public void updateAll(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<Student> stus = JSON.parseArray(param.getString("data"), Student.class);
        //Student stu = new ParamUtil<Student>().packPOJO(super.getRequestMap(request), Student.class);
        bizDao.updateAll(stus, "S_ID");
        if (CollUtil.isEmpty(stus)){
            return;
        }
        try {
            LogParam logParam = new LogParam(param, stus.get(0).getName(), "tstudent", "U", "data");
            logParam.setMenuName("日志示例");
            logParam.setPrimaryKeyColName("S_ID");
            logServcie.saveLogPanel(logParam, response);
            /*logParam = new LogParam(param, stu.getName(), "tstudent", "update~~~~~~~~~~~~~~~~~~");
            userDefineLogService.saveLog(logParam);*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> row1 = CollUtil.newArrayList("aa", "bb", "cc", "dd");
        List<String> row2 = CollUtil.newArrayList("aa1", "bb1", "cc1", "dd1");
        List<List<?>> rows = CollUtil.newArrayList(row1, row2);
        ExcelPoiUtil.downloadXlsx(rows, "excelName", false, response);
    }

    /**
     * 批量删除记录日志示例
     * @param param
     * @param response
     * @param request
     */
    public void del(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
        //Student stu = new ParamUtil<Student>().packPOJO(super.getRequestMap(request), Student.class);
        List<Student> stus = JSON.parseArray(param.getString("data"), Student.class);
        if (CollUtil.isEmpty(stus)){
            return;
        }
        bizDao.deleteAll(stus, "S_ID");
        try {
            LogParam logParam = new LogParam(param, stus.get(0).getName(), "tstudent", "D", "data");
            logParam.setMenuName("日志示例");
            logParam.setPrimaryKeyColName("S_ID");
            logServcie.saveLogPanel(logParam, response);
            /*logParam = new LogParam(param, stu.getName(), "tstudent", "delete~~~~~~~~~~~~~~~~~~");
            userDefineLogService.saveLog(logParam);*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void upload(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        MultipartFile file = multipartRequest.getFile("fileName");//file是页面input的name名
        String basePath = "e:/upload";
        try {
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (resolver.isMultipart(request)) {
                //随机生成文件名
                String randomName = UUIDUtil.getUUID().substring(10);
                String uploadFileName = file.getOriginalFilename();
                if (StringUtils.isNotBlank(uploadFileName)) {
                    //截取文件格式名
                    String suffix = uploadFileName.substring(uploadFileName.indexOf("."));
                    //重新拼装文件名
                    String newFileName = randomName + suffix;
                    String savePath = basePath + "/" + newFileName;
                    File saveFile = new File(savePath);
                    File parentFile = saveFile.getParentFile();
                    if (saveFile.exists()) {
                        saveFile.delete();
                    } else {
                        if (!parentFile.exists()) {
                            parentFile.mkdirs();
                        }
                    }
                    //复制文件到指定路径
                    FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void download(org.json.JSONObject param, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] row1 = new String[]{"aa", "bb", "cc", "dd"};
        String[] row2 = new String[]{"aa1", "bb1", "cc1", "dd1"};
        List<String[]> rows = CollUtil.newArrayList(row1, row2);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename="+fileName+".csv");
//        response.setHeader("Content-disposition", "attachment;filename=test.csv");
        //CsvUtil.writeToCsv(response.getWriter(), rows);
        CSVWriter csvWriter = new CSVWriter(response.getWriter());
        csvWriter.writeAll(rows);
        csvWriter.flush();

    }


    public static void main(String[] args) {
        /*int level = 0, split = 0;
        for (int i=0; i<500; i++ ){
            split += 20;
            level += split;
            System.out.println("等级"+(i+1)+"==exp=="+split+"==total exp=="+level);
        }*/
        String str = "海邦国际 or 1=1";
        String encode = Base64Util.encode(str);
        System.out.println(encode);
        String decode = Base64Util.decode(encode);
        System.out.println(decode);

    }
}
