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

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.member.controller.admin.excelImport.vo.*;
import cn.iocoder.yudao.module.member.controller.admin.storegoods.vo.StoreGoodsSaveReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.storegoodstype.StoreGoodsTypeDO;
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.storegoods.StoreGoodsService;
import cn.iocoder.yudao.module.member.service.storegoodstype.StoreGoodsTypeService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.system.api.dish.DishesApi;
import cn.iocoder.yudao.module.system.api.dish.dto.DishExcelDto;
import com.alibaba.excel.EasyExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.crypto.password.PasswordEncoder;
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;


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

    @Resource
    private MemberUserService memberUserService;
    @Resource
    private CashRechargeService cashRechargeService;
    @Resource
    private DishesApi dishesApi;
    @Resource
    private StoreGoodsService storeGoodsService;
    @Resource
    private StoreGoodsTypeService storeGoodsTypeService;
    @Resource
    private PasswordEncoder passwordEncoder;


    @PostMapping("/easyExcelImport")
    public void importExcel(MultipartFile file, HttpServletResponse response,Long storeId) {
        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,storeId);
            ExcelUtils.write(response, "人员不存在.xlsx", "数据", RechargeExcel.class,
                    rechargeExcels);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 最简单的读的监听器
     */
    public List<RechargeExcel> simpleRead(InputStream inputStream,Long storeId) {
        //获取正确数据
        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);
//        System.out.println(users);

        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(),storeId,false);
        }
        return notExist;
    }

    @Operation(summary = "菜品导入")
    @PostMapping("/dishImport")
    public void importExcelDish(MultipartFile file,Long storeId) {
        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()) {
            dishRead(inputStream,storeId);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void dishRead(InputStream inputStream,Long storeId) {
        //获取正确数据
        ArrayList<DishExcel> successArrayList = new ArrayList<>();
        EasyExcel.read(inputStream)
                .head(DishExcel.class)
                .registerReadListener(new DishExcelListener(
                        // 监听器中doAfterAllAnalysed执行此方法；所有读取完成之后处理逻辑
                        successArrayList::addAll))
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题(字段列表)所在行数
                .headRowNumber(1)
                .doRead();
        dishesApi.exportDish(BeanUtils.toBean(successArrayList, DishExcelDto.class),storeId);
    }


    @Operation(summary = "商品导入")
    @PostMapping("/GoodsImport")
    public void importExcelGoods(MultipartFile file,Long storeId) {
        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()) {
            GoodsRead(inputStream,storeId);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void GoodsRead(InputStream inputStream,Long storeId) {
        //获取正确数据
        ArrayList<GoodsExcel> successArrayList = new ArrayList<>();
        EasyExcel.read(inputStream)
                .head(GoodsExcel.class)
                .registerReadListener(new GoodsExcelListener(
                        // 监听器中doAfterAllAnalysed执行此方法；所有读取完成之后处理逻辑
                        successArrayList::addAll))
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题(字段列表)所在行数
                .headRowNumber(1)
                .doRead();
        for (GoodsExcel vo : successArrayList){
            StoreGoodsTypeDO byName = storeGoodsTypeService.getByName(vo.getCategory());
            StoreGoodsSaveReqVO add = new StoreGoodsSaveReqVO();
            add.setGoodsName(vo.getGoodsName());
            add.setPrice(vo.getPrice());
            add.setCarteenId(storeId);
            add.setSalesModel(1);
            add.setCategoryId(ObjectUtil.isNotEmpty(byName)?byName.getId():null);
            storeGoodsService.createStoreGoods(add);
        }
    }

    @Operation(summary = "人员导入")
    @PostMapping("/userImport")
    public void importExcelGoods(MultipartFile file) {
        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()) {
            userRead(inputStream);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void userRead(InputStream inputStream) {
        //获取正确数据
        ArrayList<UserExcel> successArrayList = new ArrayList<>();
        EasyExcel.read(inputStream)
                .head(UserExcel.class)
                .registerReadListener(new UserExcelListener(
                        // 监听器中doAfterAllAnalysed执行此方法；所有读取完成之后处理逻辑
                        successArrayList::addAll))
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题(字段列表)所在行数
                .headRowNumber(1)
                .doRead();
        for (UserExcel vo : successArrayList){

            MemberUserDO userByMobile = memberUserService.getUserByMobile(vo.getMobile());

            if(ObjectUtil.isNotEmpty(userByMobile)){
                continue;
            }

            // 生成密码
            String password = IdUtil.fastSimpleUUID();
            // 插入用户
            MemberUserDO user = new MemberUserDO();
            user.setMobile(vo.getMobile());
            user.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 默认开启
            user.setPassword(passwordEncoder.encode(password)); // 加密密码
            user.setRegisterIp("null");
            user.setNickname(vo.getName()); // 基础信息
            user.setName(vo.getName());
            if (StrUtil.isEmpty(vo.getName())) {
                // 昵称为空时，随机一个名字，避免一些依赖 nickname 的逻辑报错，或者有点丑。例如说，短信发送有昵称时~
                user.setNickname("用户" + RandomUtil.randomNumbers(6));
            }
            memberUserService.insert(user);
        }
    }

}