package jnpf.personnels.controller.web.roster;


import cn.hutool.core.date.DateUtil;
import jnpf.base.ActionResult;
import jnpf.model.personnels.dto.roster.FtbRosterImportDTO;
import jnpf.model.personnels.vo.roster.FtbRosterImportFormFieldsConfigVO;
import jnpf.model.personnels.vo.roster.FtbRosterImportVO;
import jnpf.personnels.service.FtbPersonnelsStaffRosterImportService;
import jnpf.util.UserProvider;
import jnpf.util.excel.EasyExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * web员工花名册导入模块
 *
 * @author fantaibao
 * @date 2024/02/02
 */
@RestController
@RequestMapping("/web/personnels-staff-roster-import")
@Slf4j
public class FtbPersonnelsStaffRosterImportController {

    @Resource
    private FtbPersonnelsStaffRosterImportService ftbPersonnelsStaffRosterImportService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 花名册导入
     *
     * @param ftbRosterImportDTO 文件
     * @return {@link ActionResult}
     */
    @PostMapping("/roster-import")
    public ActionResult<FtbRosterImportVO> rosterImport(@RequestBody @Validated FtbRosterImportDTO ftbRosterImportDTO) throws IOException {
        try (InputStream inputStream = EasyExcelUtils.checkExcelFile(ftbRosterImportDTO.getFileUrl())) {
            FtbRosterImportVO ftbRosterImportVO = ftbPersonnelsStaffRosterImportService.rosterImportNew(inputStream);
            // 设置文件地址临时保存20天，key为roster_import_file_url_yyyy-MM-dd-HH:mm:ss，值为文件地址，方便溯源
            redisTemplate.opsForValue().set("roster_import_file_url_" + DateUtil.format(new Date(), "yyyy-MM-dd-HH:mm:ss"),
                    ftbRosterImportDTO.getFileUrl(), 20, TimeUnit.DAYS);
            return ActionResult.success(ftbRosterImportVO);
        }
    }

    /**
     * 花名册导入（本地调试）
     */
    @PostMapping("/roster-import/local")
    public ActionResult<FtbRosterImportVO> rosterImport(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        try (InputStream inputStream = multipartFile.getInputStream()) {
            FtbRosterImportVO ftbRosterImportVO = ftbPersonnelsStaffRosterImportService.rosterImportNew(inputStream);
            return ActionResult.success(ftbRosterImportVO);
        }
    }

    /**
     * 异常数据导出
     *
     * @param id 导入时返回的唯一标识(必传)，用于导出异常数据
     */
    @GetMapping("/exception-data-export")
    public void exceptionDataExport(String id) throws IOException {
        ftbPersonnelsStaffRosterImportService.exceptionDataExport(id);
    }

    /**
     * 正常数据导入
     *
     * @param id 导入时返回的唯一标识(必传)，用于导出异常数据
     * @return {@link ActionResult}
     */
    @GetMapping("/normal-data-import")
    public ActionResult normalDataImport(String id) {

        String tenantId = UserProvider.getUser().getTenantId();
        String lockKey = "batch_import_" + tenantId + "#" + id;
        if (redisTemplate.opsForValue().setIfAbsent(lockKey, "1", 30, TimeUnit.SECONDS)) {
            try {
                ftbPersonnelsStaffRosterImportService.normalDataImport(id);
            } catch (Exception e) {
                throw e;
            } finally {
                redisTemplate.delete(lockKey);
            }
            return ActionResult.success();
        } else {
            throw new RuntimeException("导入中,请稍候...");
        }
    }

    /**
     * 新版花名册导入模板下载
     *
     * @param formFields 已勾选的登记表选项主键id集合
     * @throws IOException io异常
     */
    @PostMapping("/roster-import-template-download-new")
    public void rosterImportTemplateDownloadNew(@RequestBody List<String> formFields) throws IOException {
        ftbPersonnelsStaffRosterImportService.rosterImportTemplateDownloadNew(formFields);
    }

    /**
     * 模版下载时登记表配置勾选项
     *
     * @param type 类型0表示导出，1表示导入
     * @return {@link ActionResult }<{@link List }<{@link FtbRosterImportFormFieldsConfigVO }>>
     */
    @GetMapping("/form-fields-config")
    public ActionResult<List<FtbRosterImportFormFieldsConfigVO>> formFieldsConfig(Integer type) {
        List<FtbRosterImportFormFieldsConfigVO> result = ftbPersonnelsStaffRosterImportService.formFieldsConfig(type);
        return ActionResult.success(result);
    }


}
