package com.qmth.sop.business.templete.execute;

import cn.hutool.core.date.DateUtil;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.sop.business.bean.dto.CustomImportDto;
import com.qmth.sop.business.entity.TBTask;
import com.qmth.sop.business.service.TBTaskService;
import com.qmth.sop.business.templete.importData.AsyncImportTaskTemplete;
import com.qmth.sop.business.templete.service.TaskLogicService;
import com.qmth.sop.business.util.excel.BasicExcelListener;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.TaskResultEnum;
import com.qmth.sop.common.enums.TaskStatusEnum;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

/** 
* @Description: 客户表导入
* @Param:  
* @return:  
* @Author: wangliang
* @Date: 2023/8/1 
*/ 
@Service
public class AsyncSysCustomImportService extends AsyncImportTaskTemplete {
    private final static Logger log = LoggerFactory.getLogger(AsyncSysCustomImportService.class);
    public static final String OBJ_TITLE = "客户信息";

    @Resource
    TaskLogicService taskLogicService;

    @Resource
    TBTaskService tbTaskService;

    @Override
    public Result importTask(Map<String, Object> map) throws Exception {
        TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
        StringJoiner stringJoinerSummary = new StringJoiner("\n").add(MessageFormat.format("{0}{1}{2}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), BEGIN_TITLE, OBJ_TITLE));
        tbTask.setStatus(TaskStatusEnum.RUNNING);
        tbTask.setSummary(stringJoinerSummary.toString());
        tbTaskService.updateById(tbTask);
        try {
            // 执行导入基础用户数据
            Map<String, Object> result = taskLogicService.executeImportCustomLogic(map);
            LinkedMultiValueMap<String, CustomImportDto> customImportDtoLinkedMultiValueMap = (LinkedMultiValueMap<String, CustomImportDto>) result.get(SystemConstant.EXCEL_DATA);
            String errorList = (String) result.get(SystemConstant.EXCEL_DATA_ERROR);
            int successSize = Objects.nonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.SUCCESS)) ? customImportDtoLinkedMultiValueMap.get(BasicExcelListener.SUCCESS).size() : 0;
            int errorSize = Objects.nonNull(customImportDtoLinkedMultiValueMap.get(BasicExcelListener.ERROR)) ? customImportDtoLinkedMultiValueMap.get(BasicExcelListener.ERROR).size() : 0;
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}{4}{5}{6}{7}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), FINISH_TITLE, (successSize + errorSize), FINISH_TOTAL_SIZE, successSize, FINISH_SUCCESS_SIZE, errorSize, FINISH_ERROR_SIZE));
            if (Objects.nonNull(errorList) && !Objects.equals(errorList, "")) {
                tbTask.setResult(TaskResultEnum.ERROR);
                stringJoinerSummary.add(MessageFormat.format("{0}{1}", ERROR_DATA, errorList));
            } else {
                tbTask.setResult(TaskResultEnum.SUCCESS);
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), EXCEPTION_TITLE, EXCEPTION_DATA, e.getMessage()));
            tbTask.setResult(TaskResultEnum.ERROR);
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, ((ApiException) e).getCode(), e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        } finally {//生成txt文件
            tbTask.setSummary(stringJoinerSummary.toString());
            super.createTxt(tbTask);
            tbTaskService.updateById(tbTask);
        }
        return ResultUtil.ok(map);
    }
}
