package cn.com.ty.lift.business.project.controller;

import cn.com.ty.lift.business.project.dao.entity.model.ProjectImportModel;
import cn.com.ty.lift.business.project.dao.entity.model.request.ProjectImportRequest;
import cn.com.ty.lift.business.project.service.ProjectService;
import cn.com.ty.lift.common.utils.ValuePool;
import cn.com.ty.lift.common.verify.Val;
import cn.com.ty.lift.common.verify.Validate;
import cn.com.ty.lift.common.verify.Validation;
import cn.com.xwy.boot.web.dto.RestResponse;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Objects;

/**
 * @author wcz
 * @date 2019/12/25
 * @description 项目导入
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("project")
public class ProjectImportController {

    private ProjectService projectService;

    /**
     * excel导入项目记录
     * @param request
     * @return
     */
    @PostMapping("import")
    @Validation(fields = {"file","mtCompanyId"})
    public RestResponse importData(@Val @RequestBody ProjectImportRequest request) throws Exception {
        MultipartFile file = request.getFile();
        Long mtCompanyId = request.getMtCompanyId();
        // 1 检查文件有效性
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(ValuePool.DOT)).toLowerCase();

        Validate.isTrue(StrUtil.equalsAny(fileSuffix, ValuePool.EXCEL_IMPORT_FORMATS), ValuePool.EXCEL_IMPORT_FORMAT_SUPPORT);
        // 2 解析文件，转换成bean
        String filename = IdWorker.getIdStr() + fileSuffix;
        log.info("上传项目表格文件，临时文件名: {}",filename);
        File excel = new File(filename);
        file.transferTo(excel);
        ExcelReader reader = ExcelUtil.getReader(excel);
        List<ProjectImportModel> projectImportModels = reader.read(0, 2, reader.getRowCount(), ProjectImportModel.class);
        // 解析完成后，删除临时文件
        FileUtil.del(excel);

        Validate.notTrue(Objects.isNull(projectImportModels) || projectImportModels.size() < 2,ValuePool.EXCEL_IMPORT_DATA_MISSING);
        Validate.notTrue(projectImportModels.size() > ValuePool.EXCEL_IMPORT_MAX_ROWS_ONETIME, ValuePool.EXCEL_IMPORT_MAX_ROWS_DESC);
        // 3 循环遍历，插入数据
        return projectService.assemble(projectImportModels,mtCompanyId);
    }

    @PostMapping("parse")
    public RestResponse parse(){
        String path = "d:/tyu/项目导入模板1.xlsx";
        ExcelReader reader = ExcelUtil.getReader(path);
        Long mtCompanyId = 1l;
        // 第0行：属性名表头，第1行：汉字表头，第2行开始：记录
        List<ProjectImportModel> projectImportModels = reader.read(0,2,reader.getRowCount(),ProjectImportModel.class);
        if(ObjectUtil.isEmpty(projectImportModels)){
            return RestResponse.fail("未解析到有效数据");
        }
        //数据不超过5000条
        int size = projectImportModels.size();
        log.info("导入表格记录总条数：{}",size);
        if(size > 5000){
            return RestResponse.fail("一次性导入不能超过5000条数据");
        }
        return projectService.assemble(projectImportModels,mtCompanyId);
    }
}