package cn.iocoder.yudao.module.member.controller.admin.excelImport;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.member.controller.admin.excelImport.vo.RechargeExcel;
import cn.iocoder.yudao.module.member.controller.admin.excelImport.vo.RechargeExcelListener;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.amount.CashRechargeService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import com.alibaba.excel.EasyExcel;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Tag(name = "管理后台 - 表格导入")
@RestController
@RequestMapping("/member/excelImport")
@Validated
public class ExcelImportController {

    @Resource
    private MemberUserService memberUserService;
    @Resource
    private CashRechargeService cashRechargeService;

    @PostMapping("/easyExcelImport")
    public void importExcel(MultipartFile file, HttpServletResponse response) {
        if (!file.isEmpty()) {
            //文件名称
            int begin = Objects.requireNonNull(file.getOriginalFilename()).indexOf(".");
            //文件名称长度
            int last = file.getOriginalFilename().length();
            //判断文件格式是否正确
            String fileName = file.getOriginalFilename().substring(begin, last);
            if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
                throw new IllegalArgumentException("上传文件格式错误");
            }
        } else {
            throw new IllegalArgumentException("文件不能为空");
        }
        try (InputStream inputStream = file.getInputStream()) {
            List<RechargeExcel> rechargeExcels = simpleRead(inputStream);
            ExcelUtils.write(response, "人员不存在.xlsx", "数据", RechargeExcel.class,
                    rechargeExcels);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 最简单的读的监听器
     */
    public List<RechargeExcel> simpleRead(InputStream inputStream) {
        //获取正确数据
        ArrayList<RechargeExcel> successArrayList = new ArrayList<>();
        EasyExcel.read(inputStream)
                .head(RechargeExcel.class)
                .registerReadListener(new RechargeExcelListener(
                        // 监听器中doAfterAllAnalysed执行此方法；所有读取完成之后处理逻辑
                        successArrayList::addAll))
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题(字段列表)所在行数
                .headRowNumber(2)
                .doRead();
        List<String> mobiles = successArrayList.stream().map(RechargeExcel::getMobile).collect(Collectors.toList());
        List<MemberUserDO> users = memberUserService.getByMobiles(mobiles);


        List<RechargeExcel> notExist = new ArrayList<>();
        for (RechargeExcel excel:successArrayList){
            MemberUserDO userByMobile = memberUserService.getUserByMobile(excel.getMobile());
            if(ObjectUtil.isEmpty(userByMobile)){
                notExist.add(excel);
                continue;
            }
            List<Long> ids = new ArrayList<>();
            ids.add(userByMobile.getId());
            cashRechargeService.rechargeByAdmin(ids,null,excel.getMoney());
        }
        return notExist;
    }

}