package jnpf.personnels.controller.web.compatibility;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.ActionResult;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.model.personnels.dto.emp.ExcelImprotEmpDTO;
import jnpf.model.personnels.dto.staff.field.FormFieldDto;
import jnpf.model.personnels.dto.staff.field.FormTypeDto;
import jnpf.model.personnels.po.FtbPersonnelsStaffArchivesHistory;
import jnpf.model.personnels.po.FtbPersonnelsStaffRegistrationFormData;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.model.personnels.po.FtbPersonnelsTurnoverManagement;
import jnpf.personnels.mapper.FtbPersonnelsStaffRosterMapper;
import jnpf.personnels.service.FtbPersonnelsStaffArchivesHistoryService;
import jnpf.personnels.service.FtbPersonnelsStaffRegistrationFormDataService;
import jnpf.personnels.service.FtbPersonnelsTurnoverManagementService;
import jnpf.util.EasyExcelUtil;
import jnpf.util.NoDataSourceBind;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 兼容性问题
 * @Author: peng.hao
 * @create: 2025/9/12
 */
@RestController
@RequestMapping("/web/compatibilityIssue")
public class CompatibilityIssueController {

    @Resource
    FtbPersonnelsStaffRegistrationFormDataService dataService;

    @Resource
    FtbPersonnelsStaffArchivesHistoryService archivesHistoryService;

    @Resource
    FtbPersonnelsTurnoverManagementService turnoverManagementService;

    @Resource
    FtbPersonnelsStaffRosterMapper staffRosterMapper;


    /**
     * 处理离职历史数据变更问题
     * @param tenantIds 需要处理的租户ids
     */
    @PostMapping("/processLeaveHistoryData")
    @NoDataSourceBind
    @Transactional
    public ActionResult<Boolean> processLeaveHistoryData(@RequestBody List<String> tenantIds) {
        tenantIds.forEach(v->{
            try {
                TenantDataSourceUtil.switchTenant(v);
            } catch (LoginException e) {
                throw new RuntimeException(e);
            }
            List<FtbPersonnelsStaffArchivesHistory> archivesHistories = archivesHistoryService.list();
            LambdaQueryWrapper<FtbPersonnelsTurnoverManagement> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(FtbPersonnelsTurnoverManagement::getUserId,archivesHistories.stream().map(FtbPersonnelsStaffArchivesHistory::getUserId).collect(Collectors.toList()));
            List<FtbPersonnelsTurnoverManagement> turnoverManagements = turnoverManagementService.list(queryWrapper);
            Map<String, FtbPersonnelsTurnoverManagement> turnoverManagementMap = turnoverManagements.stream().collect(Collectors.toMap(FtbPersonnelsTurnoverManagement::getUserId, Function.identity(), (k1, k2) -> k1));
            // 处理单个人的数据
            archivesHistories.forEach(archivesHistory->{
                if (!turnoverManagementMap.containsKey(archivesHistory.getUserId())) return;
                List<FormTypeDto> list = JSONUtil.toList(archivesHistory.getArchives(), FormTypeDto.class);
                list.forEach(ft -> {
                    if (ft.getGroupFieldDataDtoList() == null) return;
                    List<FtbPersonnelsStaffRegistrationFormData> registrationFormData = ft.getGroupFieldDataDtoList().stream().filter(field -> Objects.nonNull(field) && field.getFormFieldDto() != null).map(field -> {
                        FormFieldDto fieldDto = field.getFormFieldDto();
                        FtbPersonnelsStaffRegistrationFormData formData = new FtbPersonnelsStaffRegistrationFormData();
                        formData.setId(IdWorker.getIdStr());
                        formData.setPhone(turnoverManagementMap.get(archivesHistory.getUserId()).getPhoneNumber());
                        formData.setFormTypeId(fieldDto.getFormTypeId());
                        formData.setFormFieldId(fieldDto.getId());
                        formData.setValue(fieldDto.getUserValue());
                        return formData;
                    }).collect(Collectors.toList());
                    dataService.saveBatch(registrationFormData);
                });
            });
        });
        return ActionResult.success();
    }
}
