import {downloadImage, toSend, writeProfileXml} from "@/backend/webserver/utils";

const compressing = require('compressing');
var uuid = require("uuid");
const path = require('path');
const fs = require('fs');
const os = require('os');
import axios from "axios";

var multiparty = require("multiparty");
let fn = new Object();

fn.getPodProductionInfo = async (req, res) => {
    const token = req.headers["jwt-token"]
    const company = req.headers["company"]
    const productionNo = req.body.productionNo
    try {
        let {data} = await axios.post(`https://${company}/api/podDesignCenter/getPodImageByProduction`, {productionNo}, {headers: {'jwt-token': token}})
        if (data.code === 200 && data.data && data.data.length > 0) {
            downloadImage(data.data, company, data => {
                res.json({code: 200, data})
            }, (err) => {
                res.json({code: 500, msg: '素材图下载失败'})
            })
        } else {
            res.json({code: 200, msg: '未找到素材图', data: []})
        }
    } catch (err) {
        console.log(err)
        res.json({code: 500, msg: '接口调用失败'})
    }

}
fn.findByPodProductionNo = async (req, res) => {
    const token = req.headers["jwt-token"]
    const company = req.headers["company"]
    const q = req.body
    try {
        let {data} = await axios.get(`https://${company}/api/pod/podProductionInfo/findByPodProductionNo`, {
            params: q,
            headers: {'jwt-token': token}
        })
        res.json(data)
    } catch (err) {
        res.json({code: 500, msg: err})
    }

}
fn.getCompanyList = async (req, res) => {
    try {
        let {data} = await axios.get('https://platform.jomalls.com/api/tools/getCompanyList')
        res.send(data)
    } catch (err) {
        console.log(err)
        res.json({code: 500, msg: err})
    }
}
fn.commitApply = async (req, res) => {
    const company = req.headers["company"]
    const q = req.body
    try {
        let {data} = await axios.post(`https://${company}/api/sysDeviceInfo/commitApply`, q)
        res.send(data)
    } catch (err) {
        console.log(err)
        res.json({code: 500, msg: err})
    }
}
fn.completeDelivery = async (req, res) => {
    const token = req.headers["jwt-token"]
    const company = req.headers["company"]
    const q = req.body
    try {
        let {data} = await axios.post(`https://${company}/api/pod/podProductionInfo/completeDelivery`, q, {
            headers: {'jwt-token': token}
        })
        res.json(data)
    } catch (err) {
        res.json({code: 500, msg: err})
    }

}
fn.downloadByDesignId = async (req, res) => {
    let q = req.body
    try {
        let dir = path.join(os.homedir(), '/Desktop/' + q.productionNo+'.zip')
        const zipStream = new compressing.zip.Stream();

        for(let k in q.imgList){
            const p = path.join(process.cwd(),'./print/Input/'+q.imgList[k].fileName)
            zipStream.addEntry(p);
        }

        const destStream = fs.createWriteStream(dir);
        zipStream.pipe(destStream)
            .on('finish', () => {
                console.log('success');
                res.json({code: 200, msg: q.productionNo+'.zip' + '已下载到桌面'})
            })
            .on('error', () => {
                res.json({code: 500, msg: '文件下载失败'})
            });
        // let ws=fs.createWriteStream(dir );
        // console.log(downloadByDesignId)
        //
        // ws.write(downloadByDesignId.data);
        // ws.on('drain',function () {
        //     console.log("内存干了");
        // });
        // ws.on('error',function (err) {
        //     res.json({code: 500, msg: '文件下载失败'})
        // });
        // ws.on('close',function (err) {
        //
        // });
        // ws.end()

    } catch (err) {
        console.log(err)
        res.json({code: 500, msg: err})
    }

}
fn.uploadImage = async (req, res) => {
    try {
        const p = path.join(process.cwd(), './print/Input/')
        let fileName = uuid.v4() + ".png";
        console.log(fileName)

        const form = new multiparty.Form({uploadDir: p});
        form.parse(req, function (err, fields, files) {
            console.log(fields, files, err)
            if (err) {
                res.send({code: 500, err})
            } else {
                fs.renameSync(files.file[0].path, path.join(p, fileName))
                res.json({code: 200, data: {fileName, url: path.join(process.cwd(), './print/Input/' + fileName)}})
            }
        });
    } catch (err) {
        console.log(err)
        res.json({code: 500, msg: err})
    }

}
fn.getPngImg = async (req, res) => {
    try {
        const filePath = path.join(process.cwd(), `./print/Input/${req.body.fileName}`);
        console.log(filePath)
        // 给客户端返回一个文件流 type类型
        res.set('content-type', {"png": "image/png", "jpg": "image/jpeg"});//设置返回类型
        let stream = fs.createReadStream(filePath);
        let responseData = [];//存储文件流
        if (stream) {//判断状态
            stream.on('data', function (chunk) {
                responseData.push(chunk);
            });
            stream.on('end', function () {
                const finalData = Buffer.concat(responseData);
                res.write(finalData);
                res.end();
            });
        }
    } catch (err) {
        res.send({code: 500, msg: err})
    }


}

fn.login = async (req, res) => {
    const {loginName, company, password, deviceId} = req.body
    try {
        let {data} = await axios.post(`https://${company}/api/sysLogin/login`, {loginName, password, deviceId})

        res.send(data)
    } catch (err) {
        console.log(err)
        res.json({code: 500, msg: err})
    }
}


fn.toPrint = (req, res) => {
    let body = req.body;
    writeProfileXml(body) // 写入xml文件
    // GTXproCMD.exe print -X "Profile\\CO12.xml" -I "Input\\sample.png" -A "Output\\pO12.arxp" -S 03000400 -L 02540254
    toSend(body).then(r => {
        res.send({code: 200, msg: '操作成功'})
    }).catch(err => {
        res.send({code: 500, msg: err})
    })
};

export {fn as default};
