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.Services;
import xyz.wbsite.module.admin.mgr.ServicesManager;
import xyz.wbsite.module.admin.req.ServicesCreateRequest;
import xyz.wbsite.module.admin.req.ServicesDeleteRequest;
import xyz.wbsite.module.admin.req.ServicesFindRequest;
import xyz.wbsite.module.admin.req.ServicesUpdateRequest;
import xyz.wbsite.module.admin.rsp.ServicesCreateResponse;
import xyz.wbsite.module.admin.rsp.ServicesDeleteResponse;
import xyz.wbsite.module.admin.rsp.ServicesFindResponse;
import xyz.wbsite.module.admin.rsp.ServicesUpdateResponse;

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

public class ServicesAjax{

    @Autowired
    private ServicesManager servicesManager;

    public ServicesCreateResponse create(ServicesCreateRequest request) {
        return servicesManager.create(request, LocalData.getToken());
    }

    public ServicesDeleteResponse delete(ServicesDeleteRequest request) {
        return servicesManager.delete(request, LocalData.getToken());
    }

    public ServicesUpdateResponse update(ServicesUpdateRequest request) {
        return servicesManager.update(request, LocalData.getToken());
    }

    public ServicesFindResponse find(ServicesFindRequest request) {
        return servicesManager.find(request, LocalData.getToken());
    }

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

    public Object exports(ServicesFindRequest request) {
        ServicesFindResponse response = servicesManager.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<>(Services.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<>(Services.class).read(file.getBytes(), excelTypeEnum, new WExcel.Processor<Services>() {
                @Override
                public List<String> exec(Services o, int index) {
                    ServicesCreateRequest request = MapperUtil.map(o, ServicesCreateRequest.class);
                    List<String> validate = ValidationUtil.validate(request);
                    if (validate == null || validate.size() == 0) {
                        ServicesCreateResponse servicesCreateResponse = servicesManager.create(request, LocalData.getToken());
                        if (servicesCreateResponse.hasError()) {
                            for (Error error : servicesCreateResponse.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;
    }
}
