var querystring = require('querystring');
var url = require('url');
const fs = require('fs')
var https = require('https');
var request = require('request');
var ejs = require('ejs');
function myPlugin(rawOptions) {
    const options = {
        isProduction: process.env.NODE_ENV === 'production',
        ...rawOptions,
        root: process.cwd(),
    };
    let postData; let config;
    return {
        name: 'vite-plugin-func', // 必须的，将会显示在 warning 和 error 中 
        configResolved(resolvedConfig) {
            // 存储最终解析的配置
            config = resolvedConfig
        },
        configureServer(server) {
            server.middlewares.use((req, res, next) => {
                //console.log(new Date(), 'req.url:', req.url)
                if (req.url.indexOf(".flow") != -1 || req.url.indexOf(".func") != -1) {
                    let url = req.url;
                    let post = '';
                    postData = '';
                    let path;
                    let fmodelpath = url.split("?")[0];
                    var post_data;
                    var param = req.url.split("?")[1];
                    var result = {};
                    if (param) {
                        let values = param.split("&");
                        for (let i = 0; i < values.length; i++) {
                            const element = values[i];
                            let _val = element.split("=");
                            result[_val[0]] = _val[1];
                        }
                    }
                    if (fmodelpath.endsWith(".flow")) {
                        var fversion = "";
                        var ftaskguid = "";
                        if (param) {
                            fversion = result["_version"];
                            ftaskguid = result["_ftaskguid"];
                        }
                        post_data = { fmodelpath: fmodelpath, fversion, ftaskguid }
                        path = process.env.VITE_APP_BASE_API + process.env.VITE_APP_SERVER + "/flow/open?pn=";
                    } else {
                        var viewItemId = ""
                        if (param) {
                            viewItemId = result["__viewItemId"] || result["viewItemId"] || "";
                        }
                        path = process.env.VITE_APP_BASE_API + process.env.VITE_APP_SERVER + fmodelpath + "?skip=false&viewItemId=" + viewItemId + "&pn="
                    }
                    // let pn = url.split("/")[1];
                    const TokenKey = 'EAP-Token';
                    req.on('data', (chunk) => {
                        post += chunk;
                        postData = querystring.parse(post);
                        // console.log(new Date(), 'PostData:', postData);
                    });
                    var Cookies = {};
                    if (req.headers.cookie != null) {
                        req.headers.cookie.split(';').forEach(l => {
                            var parts = l.split('=');
                            Cookies[parts[0].trim()] = (parts[1] || '').trim();
                        });
                    }
                    let token = Cookies[TokenKey];
                    let requestUrl = path + process.env.VITE_APP_PN;
                    console.log("----requestUrl:", requestUrl, "token:", token);
                    request({
                        url: requestUrl,
                        method: "POST",
                        json: true,
                        body: post_data,
                        headers: {
                            "token": token,
                            "Authorization": "Bearer " + token,
                            "Content-Type": "application/json;charset=UTF-8"
                        }
                    }, function (error, response, body) {
                        if (!error && response.statusCode == 200) {
                            let pcform;
                            let designPath;
                            let isGuest = false;
                            if (body) {
                                if (fmodelpath.endsWith(".flow") && body.outParameter) {
                                    pcform = body.outParameter.task.bizpcform;
                                } else if (fmodelpath.endsWith(".func") && body.dataPack) {
                                    pcform = body.dataPack.path;
                                    designPath = body.dataPack.designPath;
                                    isGuest = body.dataPack.isGuest;
                                }
                            }
                            if (!pcform) {
                                res.writeHead(500, {
                                    "Content-Type": "application/json;charset=UTF-8"
                                });
                                res.end(JSON.stringify(body));
                                return;
                            }
                            if (designPath && (designPath.endsWith(".vm") || designPath.endsWith(".dvm"))) {
                                res.writeHead(200, {
                                    'Content-Type': 'html'
                                });
                                let projectName = process.env.VITE_APP_PN.split("/")[0];
                                var pn = `pn=${process.env.VITE_APP_PN}`
                                if (req.url.indexOf("?") == -1) {
                                    pn = "?" + pn;
                                } else {
                                    pn = "&" + pn;
                                }
                                let accessToken = ""
                                if (token) {
                                    accessToken = `&access_token=${token}`;
                                }
                                let html = `
                            <script src="/assets_platform/eap/eap.umd.min.js"></script>
                            <script>
                                window._global ={
                                    env :"dev"
                                }
                            </script>
                            <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script>
                            <script>
                                window.location.href="${process.env.VITE_APP_BASE_API}${process.env.VITE_APP_SERVER}${req.url}${pn}${accessToken}";
                            </script>
                            `
                                res.end(html);
                                return;
                            }
                            // var fullPath = "eaptpl/12112/mokuai/shitumulu/biaodan/dtv/1.0.0/desktop/index.html";
                            let content;
                            try {
                                content = fs.readFileSync(pcform, { encoding: 'utf8' })
                            } catch (e) {
                                res.writeHead(404, {
                                    "Content-Type": "application/json;charset=UTF-8"
                                });
                                res.end("pcform:" + pcform + "文件异常!");
                                return;
                            }
                            const statusCode = 200;
                            if (!body)
                                throw new Error(`No body text found for the ${statusCode} status code`);

                            var html = ejs.render(content, rawOptions)

                            let postDataStr = JSON.stringify(postData || {});
                            let varName = options.varName || 'viteRequestData';
                            let varGlobal = JSON.stringify(options.global || {});
                            let funcName = new Date().valueOf();
                            let queryScript = `
            function _viteGetQuery${funcName}() {
                var url = window.location.search;
                var theRequest = new Object();
                if (url.indexOf("?") != -1) {
                  var str = url.substr(1);
                  strs = str.split("&");
                  for(var i = 0; i < strs.length; i ++) {
                    theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
                  }
                }
                return theRequest;
              }`
                            let titleStr = html.match(/<head(.*?)>/g)[0] || "";
                            html = html.replace(
                                /<head(.*?)>/g,
                                `${titleStr}<script>${queryScript};window.isGuest=${isGuest};window.${varName} = Object.assign(_viteGetQuery${funcName}(),${postDataStr}); window._global=${varGlobal}</script>`
                            )
                            res.writeHead(statusCode, {
                                // 'Content-Length': html.length,
                                'Content-Type': 'html'
                            });
                            res.write(html)

                            res.end();
                        } else {
                            if (response && response.statusCode == 401) {
                                res.writeHead(200, {
                                    'Content-Type': 'html'
                                });
                                let projectName = process.env.VITE_APP_PN.split("/")[0];
                                let html = `
                            <script src="/assets_platform/eap/eap.umd.min.js"></script>
                            <script>
                                window._global ={
                                    env :"dev"
                                }
                            </script>
                            <script src="/${projectName}/setting/desktop/development.js" type="text/javascript"></script>
                            <script>
                                window.location.href=window.HIVUI_SETTING.loginUrl;
                            </script>
                            `
                                res.end(html);
                            } else {
                                res.writeHead(500, {
                                    "Content-Type": "application/json;charset=UTF-8"
                                });
                                res.end(JSON.stringify(body));
                            }
                            // res.end(requestUrl + ":" + JSON.stringify(error) + JSON.stringify(body));
                        }
                    }, (msg) => {
                        res.writeHead(404, {
                            "Content-Type": "application/json;charset=UTF-8"
                        });
                        res.end(JSON.stringify(msg));
                        // console.log(msg)
                    });
                    return;
                } else {
                    next();
                }
            })
        },
    }
}
export default myPlugin;