package com.zkqy.web.controller.dragForm;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.zkqy.common.annotation.Anonymous;
import com.zkqy.common.config.ZkqyConfig;
import com.zkqy.common.constant.Constants;
import com.zkqy.common.core.domain.AjaxResult;
import com.zkqy.common.utils.StringUtils;
import com.zkqy.common.utils.file.FileUploadUtils;
import com.zkqy.common.utils.file.FileUtils;
import com.zkqy.framework.config.ServerConfig;
import com.zkqy.system.entity.CommonEntity;
import com.zkqy.system.entity.TableSql;
import com.zkqy.system.service.ICommonService;
import com.zkqy.system.service.IDataSourceService;
import com.zkqy.system.service.ITableSqlService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zkqy.common.core.domain.AjaxResult.success;

/**
 * 通用请求处理
 *
 * @author zkqy
 */

@RestController
@RequestMapping("/common")
public class CommonFileController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Resource
    private IDataSourceService dataSourceService;

    @Resource
    private ICommonService commonService;

    @Resource
    private ITableSqlService iTableSqlService;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用导出excel
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommonEntity commonEntity) throws Exception {
        commonService.export(response, commonEntity);
    }

    /**
     * 通用导出excel模版
     *
     * @param response
     * @param tableName
     * @throws Exception
     */
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response, String tableName, String sqlkey) throws Exception {
        commonService.exportTemplate(response, tableName, sqlkey);
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = zkqyConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = zkqyConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = zkqyConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = zkqyConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 导入execl数据（单个文件）文件名即表名
     */

    @Anonymous
    @ApiOperation("上传文件")
    @PostMapping(value = "/uploadData", headers = "content-type=multipart/form-data")
    public AjaxResult uploadDataFile(String tableName, String sqlKey, @RequestPart("file") MultipartFile file) throws Exception {
        try {
            // 创建一个工作簿对象 解析上传的excel表数据
            List<Map<String, String>> listMap = convertList(EasyExcel.read(file.getInputStream()).sheet().headRowNumber(0).doReadSync());

            if (listMap.size() <= 1) {
                return AjaxResult.warn("请检查表格中的数据！");
            }
            // 得到当前导出入数据的格式k/v
            TableSql tableSql = iTableSqlService.selectTableSqlByTSqlKey(sqlKey);
            // 存储 字段描述：字段列名
            Map<String, Object> fieldMap = (Map<String, Object>) JSON.parse(tableSql.getTableExportField());
            Map<String, Object> endFieldMap = new HashMap<>();
            // 处理导入title对应问题,双重校验
            fieldMap.forEach((mKey, mVal) -> {
                if (!mKey.contains("@")) {
                    endFieldMap.put(mVal.toString(), mKey);
                } else {
                    // 定义新的title map集合
                    Map<String, String> map = listMap.get(0);
                    // 根据val值删除当前map中的k/v（此处是title，理论上不会有重复的val存在）
                    map.values().removeIf(value -> value.contains(mVal.toString()));
                    // 删除旧title
                    listMap.remove(0);
                    // 替换新title
                    listMap.add(0, map);
                }
            });
//            if (listMap.get(0).size() != listMap.get(1).size()) {
//                return AjaxResult.error("请检查表格中的数据是否正确！");
//            }
            // 处理导入title对应问题,双重校验
            fieldMap.forEach((mKey, mVal) -> {
                endFieldMap.put(mVal.toString(), mKey);
                if (!mKey.contains("@")) {
                    endFieldMap.put(mVal.toString(), mKey);
                } else {
                    // 定义新的title map集合
                    Map<String, String> map = listMap.get(0);
                    // 根据val值删除当前map中的k/v（此处是title，理论上不会有重复的val存在）
                    map.values().removeIf(value -> value.contains(mVal.toString()));
                    // 删除旧title
                    listMap.remove(0);
                    // 替换新title
                    listMap.add(0, map);
                }
            });

            Map<String, String> arrangeMap = new HashMap<>();
            for (Map.Entry<String, Object> entry : fieldMap.entrySet()) {
                arrangeMap.put(entry.getValue().toString(), entry.getKey());
            }

            // 挣个excel文件数据
            listMap.forEach(item -> {
                if (listMap.indexOf(item) == 0) return;
                Map<String, String> handleMap = new HashMap<>(item);
                handleMap.forEach((mKey, mVal) -> {
                    // 新增       // 删除当前map中的k/v
                    item.put(arrangeMap.get(listMap.get(0).get(mKey)), item.remove(mKey));
                });
                // 如果value为空就清空
                item.entrySet().removeIf(entry -> entry.getValue() == null);
            });
            listMap.remove(0);
            CommonEntity commonEntity = new CommonEntity();
            commonEntity.setBasicMap(JSONObject.parseObject("{ \"tableName\":\"" + tableName + "\"}", new TypeReference<Map<String, Object>>() {
            }));
            int state = 0;  // 返回状态值
            int batchSize = 1000; // 设置批量新增每次执行添加sql上线为1000条
            for (int i = 0; i < listMap.size(); i += batchSize) {
                int end = Math.min(listMap.size(), i + batchSize);
                commonEntity.setAddListMap(listMap.subList(i, end));
                state = commonService.batchInsert(commonEntity);
            }
            return success(state);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    // map类型转换
    public static List<Map<String, String>> convertList(List<Map<Integer, String>> inputList) {
        List<Map<String, String>> resultList = new ArrayList<>();
        for (Map<Integer, String> inputMap : inputList) {
            Map<String, String> resultMap = new HashMap<>();
            for (Map.Entry<Integer, String> entry : inputMap.entrySet()) {
                Integer key = entry.getKey();
                String value = entry.getValue();
                // 将 Integer 类型的 key 转换为 String 类型
                String convertedKey = key.toString();
                resultMap.put(convertedKey, value);
            }
            resultList.add(resultMap);
        }
        return resultList;
    }
}
