package cn.ysk.cashier.controller.shop;

import cn.ysk.cashier.dto.shop.TbDeviceStockDownloadDto;
import cn.ysk.cashier.dto.shop.TbShopInfoDto;
import cn.ysk.cashier.pojo.TbDeviceStock;
import cn.ysk.cashier.pojo.shop.TbShopTable;
import cn.ysk.cashier.service.shop.TbDeviceStockService;
import cn.ysk.cashier.service.shop.TbShopInfoService;
import cn.ysk.cashier.service.shop.TbShopTableService;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.QrCodeUtils;
import cn.ysk.cashier.utils.ZipUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author GYJ
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "/device/台桌码管理")
@RequestMapping("/api/deviceStock")
public class TbDeviceStockController {

    private final TbDeviceStockService tbDeviceStockService;
    private final TbShopTableService shopTableService;
    private final TbShopInfoService shopInfoService;

    @ApiOperation("批量下载二维码")
    @PostMapping(value = "/batchDownload")
    public void batchDownload(HttpServletRequest request, HttpServletResponse response, @RequestBody TbDeviceStockDownloadDto downloadDto) {
        TbShopInfoDto shop = shopInfoService.findById(Integer.valueOf(downloadDto.getShopId()));
        if (shop == null) {
            throw new RuntimeException("店铺不存在");
        }

        // 查询shop下面有多少台桌
        List<TbShopTable> shopTables = shopTableService.queryListByShopId(Integer.valueOf(downloadDto.getShopId()));
        if (shopTables.isEmpty()) {
            throw new RuntimeException("请先添加台桌");
        }

        if (downloadDto.getCount() > 500) {
            throw new RuntimeException("最多可获取500个");
        }

        TbDeviceStock lastRecord = tbDeviceStockService.findLastRecord();

        long startCode = 4000000000L;
        if (lastRecord != null) {
            startCode = Long.parseLong(lastRecord.getSnNo()) + 1;
        }

        List<TbDeviceStock> list = new ArrayList<>();
        for (int i = 0; i < downloadDto.getCount(); i++) {
            TbDeviceStock stock = new TbDeviceStock();
            stock.setCreateTime(new Date());
            stock.setSnNo(String.valueOf(startCode + i));
            stock.setPrice(BigDecimal.ZERO);
            stock.setStatus("1");
            stock.setCode("zm");
            stock.setType("1张");
            stock.setGroupNo("111");
            stock.setDelFlag("1");
            list.add(stock);
        }

        try {
            tbDeviceStockService.saveBatch(list);
        } catch (Exception e) {
            throw new RuntimeException("设备编号重复");
        }

        // 根据code拼接前缀，生成二维码存在本地

        // 二维码存放路径
        String basePath = "/usr/local/tmp/qrCode/" + shop.getShopName();

        String baseUrl = "https://kysh.sxczgkj.cn/codeplate?code=";
        File codeImgFileSaveDir = new File(basePath);
        boolean deleteFlag = false;
        if (codeImgFileSaveDir.exists()) {
            // 先删除内部的文件
            File[] files = codeImgFileSaveDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteFlag = file.delete();
                }
                System.out.println("删除文件结果：" + deleteFlag);
            }

            // 删除文件夹
            deleteFlag = codeImgFileSaveDir.delete();
        }
        for (TbDeviceStock stock : list) {
            // 生成二维码
            QrCodeUtils.createCodeToFile(baseUrl + stock.getSnNo(), codeImgFileSaveDir, stock.getSnNo() + ".png");
        }

        try {
            String zipPath = basePath + ".zip";
            File zipFile = new File(zipPath);
            if (zipFile.exists()) {
                deleteFlag = zipFile.delete();
            }
            System.out.println("删除文件结果：" + deleteFlag);
            ZipUtils.zipDirectory(codeImgFileSaveDir, zipFile);

            FileUtil.downloadFile(request, response, zipFile, true);
        } catch (Exception e) {
            throw new RuntimeException("压缩文件失败");
        }
    }
}
