package xyz.wbsite.action.ajax.admin;

import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import xyz.wbsite.frame.base.Error;
import xyz.wbsite.frame.excel.WExcel;
import xyz.wbsite.frame.utils.LogUtil;
import xyz.wbsite.frame.base.LocalData;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.utils.ResponseUtil;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.frame.excel.exception.TemplateNotMatchException;
import xyz.wbsite.module.admin.ent.Config;
import xyz.wbsite.module.admin.mgr.ConfigManager;
import xyz.wbsite.module.admin.req.ConfigCreateRequest;
import xyz.wbsite.module.admin.req.ConfigDeleteRequest;
import xyz.wbsite.module.admin.req.ConfigFindRequest;
import xyz.wbsite.module.admin.req.ConfigUpdateRequest;
import xyz.wbsite.module.admin.rsp.ConfigCreateResponse;
import xyz.wbsite.module.admin.rsp.ConfigDeleteResponse;
import xyz.wbsite.module.admin.rsp.ConfigFindResponse;
import xyz.wbsite.module.admin.rsp.ConfigUpdateResponse;

import java.io.IOException;
import java.util.List;

public class ConfigAjax{

    @Autowired
    private ConfigManager configManager;

    public ConfigCreateResponse create(ConfigCreateRequest request) {
        return configManager.create(request, LocalData.getToken());
    }

    public ConfigDeleteResponse delete(ConfigDeleteRequest request) {
        return configManager.delete(request, LocalData.getToken());
    }

    public ConfigUpdateResponse update(ConfigUpdateRequest request) {
        return configManager.update(request, LocalData.getToken());
    }

    public ConfigFindResponse find(ConfigFindRequest request) {
        return configManager.find(request, LocalData.getToken());
    }

    public Object template(){
        return ResponseUtil.apply(new WExcel<>(Config.class));
    }

    public Object exports(ConfigFindRequest request) {
        ConfigFindResponse response = configManager.find(request, LocalData.getToken());
        if (response.hasError()) {
            return response;
        } else if (response.getTotalCount() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "导出数据为空");
            return response;
        }
        return ResponseUtil.apply(new WExcel<>(Config.class).addDatas(response.getResult()));
    }

    public Object imports(MultipartFile file) {
        BaseResponse baseResponse = new BaseResponse();
        try {
            // 检查文件格式
            String originalFilename = file.getOriginalFilename() != null ? file.getOriginalFilename() : "";
            if (!originalFilename.matches(".+(.xlsx?|.XLSX?)$")) {
                baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件格式错误！");
                return baseResponse;
            }
            // 兼容2003以前老版本.xls
            ExcelTypeEnum excelTypeEnum = originalFilename.matches(".+(.xlsx|.XLSX)$") ? ExcelTypeEnum.XLSX : ExcelTypeEnum.XLS;
            WExcel sheet = new WExcel<>(Config.class).read(file.getBytes(), excelTypeEnum, new WExcel.Processor<Config>() {
                @Override
                public List<String> exec(Config o, int index) {
                    ConfigCreateRequest request = MapperUtil.map(o, ConfigCreateRequest.class);
                    List<String> validate = ValidationUtil.validate(request);
                    if (validate == null || validate.size() == 0) {
                        ConfigCreateResponse configCreateResponse = configManager.create(request, LocalData.getToken());
                        if (configCreateResponse.hasError()) {
                            for (Error error : configCreateResponse.getErrors()) {
                                validate.add(error.getMessage());
                            }
                        }
                    }
                    return validate;
                }
            });
            // 当导入出现错误时可以将存在标注错误的Excel返回给用户改正
            if (sheet.hasError()) {
                return ResponseUtil.apply(sheet.getBytes(), sheet.getName() + "-检查.xlsx");
            } else {
                return baseResponse;
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.dumpException(e);
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件出错");
        } catch (TemplateNotMatchException e) {
            baseResponse.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
        }
        return baseResponse;
    }
}
