package com.chinaweal.aiccs.crgs.transfor.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.crgs.transfor.entity.OtNpermitUploadLog;
import com.chinaweal.aiccs.crgs.transfor.entity.OtUploadBatchLog;
import com.chinaweal.aiccs.crgs.transfor.sdk.UploadSDK;
import com.chinaweal.aiccs.crgs.transfor.service.OtNpermitUploadLogService;
import com.chinaweal.aiccs.crgs.transfor.service.OtUploadBatchLogService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 行政许可信息上传清单记录 前端控制器
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-11-02
 */
@Slf4j
@RestController
@RequestMapping("/npermit")
public class OtNpermitUploadLogController extends BaseController {

    @Value("${ot.uploadPath}")
    private String uploadPath;

    @Autowired
    private OtUploadBatchLogService otUploadBatchLogService;

    @Autowired
    private OtNpermitUploadLogService otNpermitUploadLogService;

    @Autowired
    private UploadSDK uploadSDK;

    @Resource
    private FileStorageService fileStorageService;

    @Value("${ot.bakPermitUploadPath}")
    private String bakPermitUploadPath;

    /**
     * 上传接口
     *
     * @param file 上传
     * @return 上传结果
     * @author lroyia
     * @since 2021年11月2日 17:01:25
     */
    @Transactional
    @PostMapping("upload")
    public RestResult<?> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        AICUser loginUser = getLoginUser(request);
        String primaryKey = loginUser.getPrimaryKey();

        LocalDateTime now = LocalDateTime.now();
        // 批次id
        String originalName = file.getOriginalFilename();
        String ext = originalName.lastIndexOf(".") > -1 ? originalName.substring(originalName.lastIndexOf(".")) : ".xls";
        String batchId = UUID.randomUUID().toString().replace("-", StringUtils.EMPTY);
        // 保存文件
//        String filePath = File.separator + "npermit" +
//                File.separator + primaryKey + File.separator + batchId + ext;
//        String savePath = uploadPath + filePath;
        long day = System.currentTimeMillis();
        Date date = new Date(day);
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sbf.format(date);
        String ftpUploadPath = bakPermitUploadPath + File.separator + dateStr + File.separator + primaryKey;

        String tempPath = ftpUploadPath + File.separator + originalName ;
        OtUploadBatchLog otUploadBatchLog = new OtUploadBatchLog()
                .setBatchid(batchId)
                .setFilename(originalName)
                .setFilepath(tempPath)
                .setUploaderid(primaryKey)
                .setUploaddate(now)
                .setIsdeleted(Constant.FALSE_0_STR)
                .setUploadtype(Constant.TRUE_1_STR)
                .setIsuploaded(Constant.FALSE_0_STR);
        File uploadFile = new File(tempPath);
        if(!uploadFile.getParentFile().exists()) uploadFile.getParentFile().mkdirs();
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            log.error("文件保存失败");
            RestResult<Object> error = RestResult.error(ResultCode.MYSTERIOUS_ERROR);
            error.setMsg("文件保存失败");
            return error;
        }
        otUploadBatchLogService.save(otUploadBatchLog);

        // 读取文件中的信息
        List<OtNpermitUploadLog> list;
        try {
            list = readData(batchId, uploadFile);
        } catch (IOException e) {
            log.error("读取文件的数据失败", e);
            RestResult<Object> error = RestResult.error(ResultCode.MYSTERIOUS_ERROR);
            error.setMsg("读取文件的数据失败");
            return error;
        }
        for (OtNpermitUploadLog each : list) {
            otNpermitUploadLogService.save(each);
        }

        // 调用上传接口
        String jsonStr = uploadSDK.uploadNCase(tempPath);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        JSONObject errorInfo = jsonObject.getJSONObject("errorInfo");
        OtNpermitUploadLog uploadRecord = new OtNpermitUploadLog()
                .setIsSuccess(Constant.TRUE_1_STR);
        otNpermitUploadLogService.update(uploadRecord, new LambdaQueryWrapper<OtNpermitUploadLog>()
                .eq(OtNpermitUploadLog::getBatchid, batchId));
        // 更新失败原因
        for (String id : errorInfo.keySet()) {
            uploadRecord = new OtNpermitUploadLog()
                    .setIsSuccess(Constant.FALSE_0_STR)
                    .setFailReason(errorInfo.getString(id));
            otNpermitUploadLogService.update(uploadRecord, new LambdaQueryWrapper<OtNpermitUploadLog>()
                    .eq(OtNpermitUploadLog::getBatchid, batchId).eq(OtNpermitUploadLog::getLicid, id));
        }

        // 上传ftp
//        long day = System.currentTimeMillis();
//        Date date = new Date(day);
//        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd");
//        String dateStr = sbf.format(date);
//        String ftpUploadPath = bakPermitUploadPath + File.separator + dateStr + File.separator + primaryKey;
//        String fileName = uploadFile.getName();
//        String tempPath = ftpUploadPath + File.separator + fileName ;
//        try {
//            InputStream inputStream = new FileInputStream(uploadFile);
//            Boolean isSuccess = fileStorageService.writeFromStream(ftpUploadPath,fileName,inputStream);
//            if (isSuccess) {
//                otUploadBatchLog.setFilepath(tempPath);
//                otUploadBatchLogService.updateById(otUploadBatchLog);
//                // 删除本地文件
//                uploadFile.delete();
//            }
//        } catch (FileNotFoundException e) {
//            log.error("上传文件到ftp失败");
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        return RestResult.ok(batchId);
    }

    /**
     * 加载上传记录分页
     * @param pageRequestDto    分页参数与
     * @return  查询结果
     * @author lroyia
     * @since  2021年11月2日 20:16:52
     */
    @ApiOperation("上传记录分页")
    @PostMapping("log/page")
    public RestResult<?> loadUploadLogList(@RequestBody PageRequestDto pageRequestDto){
        IPage<OtNpermitUploadLog> page = otNpermitUploadLogService.defaultPaging(pageRequestDto, null, null);
        return RestResult.ok(page);
    }


    /**
     * 读取数据
     *
     * @param batchId 批次id
     * @param file    文件
     * @return 获取结果
     * @throws IOException IO异常
     * @author lroyia
     * @since 2021年11月2日 18:20:58
     */
    private List<OtNpermitUploadLog> readData(String batchId, File file) throws IOException {
        List<Map<String, String>> maps = otUploadBatchLogService.readTempData(file);
        List<OtNpermitUploadLog> result = otUploadBatchLogService.transferResult2Bean(maps, OtNpermitUploadLog.class);
        for (OtNpermitUploadLog atom : result) {
            atom.setBatchid(batchId);
        }
        return result;
    }
}

