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.Rules;
import xyz.wbsite.module.admin.mgr.RulesManager;
import xyz.wbsite.module.admin.req.RulesCreateRequest;
import xyz.wbsite.module.admin.req.RulesDeleteRequest;
import xyz.wbsite.module.admin.req.RulesFindRequest;
import xyz.wbsite.module.admin.req.RulesUpdateRequest;
import xyz.wbsite.module.admin.rsp.RulesCreateResponse;
import xyz.wbsite.module.admin.rsp.RulesDeleteResponse;
import xyz.wbsite.module.admin.rsp.RulesFindResponse;
import xyz.wbsite.module.admin.rsp.RulesUpdateResponse;

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

public class RulesAjax{

    @Autowired
    private RulesManager rulesManager;

    public RulesCreateResponse create(RulesCreateRequest request) {
        return rulesManager.create(request, LocalData.getToken());
    }

    public RulesDeleteResponse delete(RulesDeleteRequest request) {
        return rulesManager.delete(request, LocalData.getToken());
    }

    public RulesUpdateResponse update(RulesUpdateRequest request) {
        return rulesManager.update(request, LocalData.getToken());
    }

    public RulesFindResponse find(RulesFindRequest request) {
        return rulesManager.find(request, LocalData.getToken());
    }

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

    public Object exports(RulesFindRequest request) {
        RulesFindResponse response = rulesManager.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<>(Rules.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<>(Rules.class).read(file.getBytes(), excelTypeEnum, new WExcel.Processor<Rules>() {
                @Override
                public List<String> exec(Rules o, int index) {
                    RulesCreateRequest request = MapperUtil.map(o, RulesCreateRequest.class);
                    List<String> validate = ValidationUtil.validate(request);
                    if (validate == null || validate.size() == 0) {
                        RulesCreateResponse rulesCreateResponse = rulesManager.create(request, LocalData.getToken());
                        if (rulesCreateResponse.hasError()) {
                            for (Error error : rulesCreateResponse.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;
    }
}
