package com.bonus.material.basic.service.impl;

import com.bonus.common.biz.config.BackstageApplication;
import com.bonus.common.biz.config.DateTimeHelper;
import com.bonus.common.biz.config.QrCodeUtils;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.domain.BmQrBoxInfo;
import com.bonus.material.basic.mapper.BmQrBoxMapper;
import com.bonus.material.basic.service.BmQrBoxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * @Author ma_sh
 * @create 2024/12/10 17:26
 */
@Service
@Slf4j
public class BmQrBoxServiceImpl implements BmQrBoxService {

    @Resource
    private BmQrBoxMapper bmQrBoxMapper;

    /**
     * 查询二维码标准箱管理列表
     * @param bmQrBoxInfo
     * @return
     */
    @Override
    public List<BmQrBoxInfo> selectBmQrBoxInfoList(BmQrBoxInfo bmQrBoxInfo) {
        return bmQrBoxMapper.find(bmQrBoxInfo);
    }

    /**
     * 新增二维码标准箱管理
     * @param bmQrBoxInfo
     * @return
     */
    @Override
    public AjaxResult insertBmQrcodeInfo(BmQrBoxInfo bmQrBoxInfo) {
        //生成二维码
        String code = "BOX-" + DateTimeHelper.getNowTimeFomart();
        bmQrBoxInfo.setBoxCode(code);
        bmQrBoxInfo.setCreateBy(SecurityUtils.getUsername());
        bmQrBoxInfo.setCreateTime(DateUtils.getNowDate());
        int result = bmQrBoxMapper.insertBmQrcodeInfo(bmQrBoxInfo);
        return result > 0 ? AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg()) : AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 下载二维码标准箱
     * @param bmQrBoxInfo
     * @param response
     * @return
     */
    @Override
    public void download(BmQrBoxInfo bmQrBoxInfo, HttpServletResponse response) {
        try {
            List<BmQrBoxInfo> list = bmQrBoxMapper.find(bmQrBoxInfo);
            String code = "无编码";
            if (list.size() > 0) {
                code = list.get(0).getBoxCode();
            }
            // 新购管理-二维码打印-新增
            String url = BackstageApplication.getUrl() + "backstage/machine/qrCodePage?qrcode=" + code;
            // 二维码的图片格式
            String format = "jpg";
            //设置路径
            String mkdirsName = "images";
            // linux 系统路径
            String saveDirectory = "/data/imw/" + mkdirsName + "/";
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                //本地路径
                saveDirectory = "D://files/" + mkdirsName + "/";
            }
            // 生成二维码
            File files = new File(saveDirectory);
            if (!files.exists()) {
                files.mkdirs();
            }
            QrCodeUtils.generateQRImage(url, saveDirectory, code + ".jpg", format);
            String qrUrl = saveDirectory + code + ".jpg";
            String path = qrUrl.replace("filePath", "/data/imw");
            // 判断照片是否存在
            File imageFile = new File(path);
            if (!imageFile.exists()) {
                log.warn("图片不存在");
            }
            //设置MIME类型
            response.setContentType("application/octet-stream");
            response.addHeader("Content-disposition", "attachment;filename=" + new String(path.getBytes(), "ISO-8859-1"));
            InputStream inputStream = new FileInputStream(imageFile);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bs = new byte[1024];
            while ((inputStream.read(bs) > 0)) {
                outputStream.write(bs);
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 修改二维码标准箱管理
     * @param bmQrBoxInfo
     * @return
     */
    @Override
    public AjaxResult updateBmQrcodeInfo(BmQrBoxInfo bmQrBoxInfo) {
        bmQrBoxInfo.setUpdateBy(SecurityUtils.getUsername());
        bmQrBoxInfo.setUpdateTime(DateUtils.getNowDate());
        int result = bmQrBoxMapper.updateBmQrcodeInfo(bmQrBoxInfo);
        return result > 0 ? AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg()) : AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 删除二维码标准箱管理
     * @param bmQrBoxInfo
     * @return
     */
    @Override
    public AjaxResult deleteById(BmQrBoxInfo bmQrBoxInfo) {
        //根据id查看标准箱是否绑定，绑定不能删除
        if (bmQrBoxMapper.countBmQrcodeInfoByBoxId(bmQrBoxInfo.getBoxId()) > 0) {
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), "该标准箱还绑定设备，无法删除");
        }
        int result = bmQrBoxMapper.deleteById(bmQrBoxInfo);
        return result > 0 ? AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg()) : AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    /**
     * 查询二维码标准箱管理绑定详情列表
     * @param bmQrBoxInfo
     * @return
     */
    @Override
    public List<BmQrBoxInfo> getList(BmQrBoxInfo bmQrBoxInfo) {
        return bmQrBoxMapper.getList(bmQrBoxInfo);
    }
}
