
import moment from 'moment';
import React from 'react';
import { UploadData2, UploadData, UploadFormData, UpdateStoreStatus, bytesToSize, UpdateDistributorStatus, getAllFolderImages, getKPIFields } from '../controller/functions';
import { common_ImagePath, ImageFolderPath, visiCoolerImgPath, db, URL_IMAGE, IRSyncStatus } from './constants';
import { getMethodName, METHODS } from './methodNames';
import { AppTables } from './tableConstants';
import * as RNFS from 'react-native-fs';
import { Platform } from 'react-native';
import * as mime from 'mime';
import IRLogin from '../components/IRLogin';

export async function getUploadData(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    switch (ScreenName) {
        case 'STOCK': {
            let CHUNK_SIZE = await getChunk_dataStk();
            if (CHUNK_SIZE != null && CHUNK_SIZE > 0) {
                var postData = await getStockDataChunks(storeData, UserId, previousDayUpload, CHUNK_SIZE);
                return postData;
            } else {
                // Stocks2
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}'` : '') + ` `;
                        let allImages = [], allChilds = [];
                        let allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);

                                    if (data.IMAGE != null && data.IMAGE != '') {
                                        let imgsData = {};

                                        imgsData['MID'] = MID;
                                        imgsData['UserId'] = UserId;
                                        imgsData['SubCategoryId'] = data.SUB_CATEGORY_ID;
                                        imgsData['SubCategoryImg'] = data.IMAGE != null ? data.IMAGE : '';

                                        allImages.push(imgsData);

                                        let imgPath = common_ImagePath + data.IMAGE;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: data.IMAGE,
                                            filetype: 'image',
                                            folderName: 'StockSingleKPIImages',
                                        }
                                        allKPIfiles.push(file);
                                    }
                                }
                                async function getMFDStockData(skud) {
                                    let { SUB_CATEGORY_ID, BRAND_ID, PRODUCT_ID } = skud;
                                    return new Promise((resolve, reject) => {
                                        db.transaction(async function (txn) {
                                            let q = `select * from ${AppTables.STOCK2_MFD_DATA} where STOCK_UID='${skud.STOCK_UID}'`;
                                            await txn.executeSql(q, [], async function (txn2, txnres) {
                                                if (txnres.rows.length > 0) {
                                                    let arr1 = [];
                                                    for (var i = 0; i < txnres.rows.length; i++) {
                                                        let data = txnres.rows.item(i);
                                                        let { STOCK } = data;
                                                        let date = data.MFD != null && data.MFD != '' ? moment(data.MFD).format('MM/DD/YYYY') : '';
                                                        let obj1 = {};
                                                        obj1['MID'] = MID,
                                                            obj1['SubCategoryId'] = SUB_CATEGORY_ID;
                                                        obj1['BrandId'] = BRAND_ID;
                                                        obj1['ProductId'] = PRODUCT_ID;
                                                        obj1['Mfd'] = date,
                                                            obj1['LotNo'] = data.LOT_NO,
                                                            obj1['Stock'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;

                                                        arr1.push(obj1);
                                                        if (i == txnres.rows.length - 1) {
                                                            resolve(arr1)
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve([])
                                                }
                                            }, function (txnE, txnerr) { console.log(txnerr); resolve([]) },);
                                        });
                                    }).catch((err) => {
                                        console.log(err);
                                        return [];
                                    })
                                }

                                let join = `  inner join Mapping_ProductAssortmentStorewise m on p.PRODUCT_ID=m.ProductId and m.StoreId='${StoreId}'`;
                                let q = `SELECT Distinct p.*,m.MBQ FROM ${AppTables.STOCK2_DATA} p ${join} WHERE p.STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and p.VISIT_DATE='${d2}' ` : '') + ` `;
                                await txn.executeSql(q, [], async function (txn2, txnres3) {
                                    for (var i = 0; i < txnres3.rows.length; i++) {
                                        let data2 = txnres3.rows.item(i);
                                        let { ARTICLE_CODE, COMMON_ID, STORE_ID, VISIT_DATE, PriceYesNo, SUB_CATEGORY_ID, SUB_CATEGORY, BRAND_ID, BRAND, PRODUCT_ID, MSL, STOCK, PACKTYPE, BACKROOM_STOCK, DAMAGED_STOCK, LOST_STOCK, EXPIRY_STOCK, IS_SKU_STOCK_PRESENT, NREXPIRY1_STOCK, NREXPIRY2_STOCK, NREXPIRY3_STOCK, OUT_OF_STOCK, LESS_THAN_MBQ, ADDED_DATE, MBQ } = data2;
                                        let mfdStocks = await getMFDStockData(data2);
                                        let obj = {};
                                        obj['MID'] = MID;
                                        obj['UserId'] = UserId;
                                        obj['Msl'] = (MSL == 'true' || MSL == true) ? 1 : 0;
                                        obj['ArticleCode'] = ARTICLE_CODE || "";
                                        obj['SubCategoryId'] = SUB_CATEGORY_ID;
                                        obj['ProductId'] = PRODUCT_ID;
                                        obj['Stock'] = STOCK != null && STOCK != "" && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;
                                        obj['PackType'] = PACKTYPE != null && PACKTYPE != "" && PACKTYPE != "null" && PACKTYPE != "undefined" ? PACKTYPE : '';
                                        obj['BackRoomStock'] = BACKROOM_STOCK != null && BACKROOM_STOCK != "" && BACKROOM_STOCK != "null" && BACKROOM_STOCK != "undefined" ? BACKROOM_STOCK : 0;
                                        obj['DamagedStock'] = DAMAGED_STOCK != null && DAMAGED_STOCK != "" && DAMAGED_STOCK != "null" && DAMAGED_STOCK != "undefined" ? DAMAGED_STOCK : 0;
                                        obj['LostStock'] = LOST_STOCK != null && LOST_STOCK != "" && LOST_STOCK != "null" && LOST_STOCK != "undefined" ? LOST_STOCK : 0;
                                        obj['ExpiryStock'] = EXPIRY_STOCK != null && EXPIRY_STOCK != "" && EXPIRY_STOCK != "null" && EXPIRY_STOCK != "undefined" ? EXPIRY_STOCK : 0;
                                        obj['MFD_Stocks'] = mfdStocks || [];
                                        obj['IsSKUPresent'] = IS_SKU_STOCK_PRESENT;
                                        obj['NrExpiry1_Stock'] = NREXPIRY1_STOCK != null && NREXPIRY1_STOCK != "" && NREXPIRY1_STOCK != "null" && NREXPIRY1_STOCK != "undefined" ? NREXPIRY1_STOCK : 0;
                                        obj['NrExpiry2_Stock'] = NREXPIRY2_STOCK != null && NREXPIRY2_STOCK != "" && NREXPIRY2_STOCK != "null" && NREXPIRY2_STOCK != "undefined" ? NREXPIRY2_STOCK : 0;
                                        obj['NrExpiry3_Stock'] = NREXPIRY3_STOCK != null && NREXPIRY3_STOCK != "" && NREXPIRY3_STOCK != "null" && NREXPIRY3_STOCK != "undefined" ? NREXPIRY3_STOCK : 0;
                                        obj['OutOfStock'] = OUT_OF_STOCK != null && OUT_OF_STOCK != "" && OUT_OF_STOCK != "null" && OUT_OF_STOCK != "undefined" ? OUT_OF_STOCK : 0;
                                        obj['LessThanMBQ'] = LESS_THAN_MBQ != null && LESS_THAN_MBQ != "" && LESS_THAN_MBQ != "null" && LESS_THAN_MBQ != "undefined" ? LESS_THAN_MBQ : 0;
                                        obj['MBQ'] = MBQ;
                                        obj['PriceYesNo'] = PriceYesNo
                                        allChilds.push(obj);
                                    }

                                    let alljsonData = {};
                                    alljsonData['StockImgs'] = allImages;
                                    alljsonData['StockChilds'] = allChilds;
                                    postData['MID'] = MID;
                                    postData['Keys'] = 'StockSingleKPI';
                                    postData['JsonData'] = JSON.stringify(alljsonData);
                                    postData['UserId'] = UserId;
                                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                                    console.log('stock2 postData', postData);

                                }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);
                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                })
            }
        }

        case 'STOCKWITHPROMO':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.STOCKPOMO_HDR_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}'` : '') + ` `;
                        let allImages = [], allChilds = [];
                        let allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);

                                    if (data.IMAGE_JSON != null && data.IMAGE_JSON != '') {
                                        let imageJson = data?.IMAGE_JSON;
                                        let images = JSON.parse(imageJson);
                                        // let IMAGE = images;
                                        console.log("imgjsoon---", images)


                                        let IMAGE = images.map(image => {
                                            delete image.imgRequired;
                                            delete image.ImageName;
                                            delete image.ImagePath;
                                            return image;
                                        });

                                        console.log("finalimages---", IMAGE)

                                        let imgsData = {};

                                        imgsData['MID'] = MID;
                                        imgsData['UserId'] = UserId;
                                        imgsData['SubCategoryId'] = data.SUB_CATEGORY_ID;
                                        imgsData['HeaderImg'] = IMAGE != null ? IMAGE : '';

                                        allImages.push(imgsData);
                                        let imgPath = common_ImagePath + IMAGE;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: IMAGE,
                                            filetype: 'image',
                                            folderName: 'StockSingleKPIImages',
                                        }
                                        allKPIfiles.push(file);
                                    }



                                }

                                async function getMFDStockData(skud) {
                                    let { SUB_CATEGORY_ID, BRAND_ID, PRODUCT_ID } = skud;

                                    return new Promise((resolve, reject) => {
                                        db.transaction(async function (txn) {
                                            let q = `select * from ${AppTables.STOCK2_MFD_DATA} where STOCK_UID='${skud.STOCK_UID}'`;
                                            await txn.executeSql(q, [], async function (txn2, txnres) {
                                                if (txnres.rows.length > 0) {
                                                    let arr1 = [];
                                                    for (var i = 0; i < txnres.rows.length; i++) {
                                                        let data = txnres.rows.item(i);
                                                        let { STOCK } = data;
                                                        let date = data.MFD != null && data.MFD != '' ? moment(data.MFD).format('MM/DD/YYYY') : '';
                                                        let obj1 = {};
                                                        obj1['MID'] = MID,
                                                            obj1['SubCategoryId'] = SUB_CATEGORY_ID;
                                                        obj1['BrandId'] = BRAND_ID;
                                                        obj1['ProductId'] = PRODUCT_ID;
                                                        obj1['Mfd'] = date,
                                                            obj1['LotNo'] = data.LOT_NO,
                                                            obj1['Stock'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;

                                                        arr1.push(obj1);
                                                        if (i == txnres.rows.length - 1) {
                                                            resolve(arr1)
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve([])
                                                }
                                            }, function (txnE, txnerr) { console.log(txnerr); resolve([]) },);
                                        });
                                    }).catch((err) => {
                                        console.log(err);
                                        return [];
                                    })
                                }

                                let join = `  inner join Mapping_ProductAssortmentStorewise m on p.PRODUCT_ID=m.ProductId and m.StoreId='${StoreId}'`;
                                let q = `SELECT Distinct p.*,m.MBQ FROM ${AppTables.STOCKPROMO_DATA} p ${join} WHERE p.STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and p.VISIT_DATE='${d2}' ` : '') + ` `;

                                await txn.executeSql(q, [], async function (txn2, txnres3) {
                                    for (var i = 0; i < txnres3.rows.length; i++) {
                                        let data2 = txnres3.rows.item(i);

                                        let { COMMON_ID, STORE_ID, VISIT_DATE, SUB_CATEGORY_ID, SUB_CATEGORY, BRAND_ID, BRAND, PRODUCT_ID, PRODUCT, MSL, STOCK, BACKROOM_STOCK, DAMAGED_STOCK, MRP, SELLING_PRICE, REMARK, LOST_STOCK, EXPIRY_STOCK, IS_SKU_STOCK_PRESENT, NREXPIRY1_STOCK, NREXPIRY2_STOCK, NREXPIRY3_STOCK, OUT_OF_STOCK, LESS_THAN_MBQ, ADDED_DATE, MBQ, STOCK_AVL_STATUS, PROMO_TYPE, PROMO_RUNNING, FROM_DATE, TO_DATE, IMAGE_JSON } = data2;
                                        let mfdStocks = await getMFDStockData(data2);
                                        let childImageJson
                                        try {
                                            childImageJson = JSON.parse(IMAGE_JSON);
                                        } catch (error) {
                                            console.error("JSON Parse error for IMAGE_JSON:", IMAGE_JSON);
                                            continue; // Skip this iteration if JSON parsing fails
                                        }




                                        let IMAGE_CHILD = childImageJson.map(imagesC => {
                                            delete imagesC.imgRequired;
                                            delete imagesC.ImageName;
                                            delete imagesC.ImagePath;
                                            return imagesC;
                                        });

                                        console.log("finalimagechild---", IMAGE_CHILD)
                                        let obj = {};
                                        obj['MID'] = MID;
                                        obj['UserId'] = UserId;
                                        obj['Msl'] = (MSL == 'true' || MSL == true) ? 1 : 0;
                                        obj['SubCategoryId'] = SUB_CATEGORY_ID;
                                        obj['ProductId'] = PRODUCT_ID;
                                        obj['StockAvlStatus'] = STOCK_AVL_STATUS;
                                        obj['PromoType'] = PROMO_TYPE;
                                        obj['PromoRunning'] = PROMO_RUNNING;
                                        obj['FromDate'] = FROM_DATE;
                                        obj['ToDate'] = TO_DATE;
                                        obj['ChildImg'] = IMAGE_CHILD;
                                        obj['Stock'] = STOCK != null && STOCK != "" && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;
                                        obj['MRP'] = MRP != null && MRP != "" && MRP != "null" && MRP != "undefined" ? MRP : 0;
                                        obj['SellingPrice'] = SELLING_PRICE != null && SELLING_PRICE != "" && SELLING_PRICE != "null" && SELLING_PRICE != "undefined" ? SELLING_PRICE : 0;
                                        obj['Remark'] = REMARK != null && REMARK != "" && REMARK != "null" && REMARK != "undefined" ? REMARK : 0;

                                        obj['BackRoomStock'] = BACKROOM_STOCK != null && BACKROOM_STOCK != "" && BACKROOM_STOCK != "null" && BACKROOM_STOCK != "undefined" ? BACKROOM_STOCK : 0;
                                        obj['DamagedStock'] = DAMAGED_STOCK != null && DAMAGED_STOCK != "" && DAMAGED_STOCK != "null" && DAMAGED_STOCK != "undefined" ? DAMAGED_STOCK : 0;
                                        obj['LostStock'] = LOST_STOCK != null && LOST_STOCK != "" && LOST_STOCK != "null" && LOST_STOCK != "undefined" ? LOST_STOCK : 0;
                                        obj['ExpiryStock'] = EXPIRY_STOCK != null && EXPIRY_STOCK != "" && EXPIRY_STOCK != "null" && EXPIRY_STOCK != "undefined" ? EXPIRY_STOCK : 0;
                                        obj['MFD_Stocks'] = mfdStocks || [];
                                        obj['IsSKUPresent'] = IS_SKU_STOCK_PRESENT;
                                        obj['OutOfStock'] = OUT_OF_STOCK != null && OUT_OF_STOCK != "" && OUT_OF_STOCK != "null" && OUT_OF_STOCK != "undefined" ? OUT_OF_STOCK : 0;
                                        obj['LessThanMBQ'] = LESS_THAN_MBQ != null && LESS_THAN_MBQ != "" && LESS_THAN_MBQ != "null" && LESS_THAN_MBQ != "undefined" ? LESS_THAN_MBQ : 0;
                                        obj['MBQ'] = MBQ;
                                        allChilds.push(obj);
                                        // new child upload folder
                                        if (IMAGE_CHILD != '' && IMAGE_CHILD != null) {
                                            let imgPath = common_ImagePath + IMAGE_CHILD;
                                            let file = {
                                                uri: imgPath,
                                                type: 'image/jpeg',
                                                name: IMAGE_CHILD,
                                                filetype: 'image',
                                                folderName: 'StockSingleKPIImages',
                                            }
                                            allKPIfiles.push(file);
                                        }
                                    }

                                    let alljsonData = {};
                                    alljsonData['StockHeader'] = allImages;
                                    alljsonData['StockChilds'] = allChilds;
                                    postData['MID'] = MID;
                                    postData['Keys'] = 'StockWithPromo';
                                    postData['JsonData'] = JSON.stringify(alljsonData);
                                    postData['UserId'] = UserId;
                                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                                    console.log('stockpromo postData--', postData);
                                }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);
                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                })
            }

        case 'STOCKWITHCATEGORY':
            {
                // StockWithCat
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.STOCKWITHCAT_HDR_DATA} WHERE STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allImages = [], allChilds = [];
                        let allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let imgsData = {};
                                    imgsData['MID'] = MID;
                                    imgsData['UserId'] = UserId;
                                    imgsData['CategoryId'] = data.CATEGORY_ID;
                                    imgsData['CategoryImg'] = data.IMAGE;
                                    allImages.push(imgsData);
                                    if (data.IMAGE != '' && data.IMAGE != null) {
                                        let imgPath = common_ImagePath + data.IMAGE;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: data.IMAGE,
                                            filetype: 'image',
                                            folderName: 'StockWithCatImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                }

                                async function getMFDStockData(skud) {
                                    let { CATEGORY_ID, BRAND_ID, PRODUCT_ID } = skud;
                                    return new Promise((resolve, reject) => {
                                        db.transaction(async function (txn) {
                                            let q = `select * from ${AppTables.STOCKWITHCAT_MFD_DATA} where STOCK_UID='${skud.STOCK_UID}'`;
                                            await txn.executeSql(q, [], async function (txn2, txnres) {
                                                if (txnres.rows.length > 0) {
                                                    let arr1 = [];
                                                    for (var i = 0; i < txnres.rows.length; i++) {
                                                        let data = txnres.rows.item(i);
                                                        let { STOCK } = data;
                                                        let obj1 = {};
                                                        obj1['MID'] = MID,
                                                            obj1['CategoryId'] = CATEGORY_ID;
                                                        obj1['BrandId'] = BRAND_ID;
                                                        obj1['ProductId'] = PRODUCT_ID;
                                                        obj1['Mfd'] = data.MFD,
                                                            obj1['LotNo'] = data.LOT_NO,
                                                            obj1['Stock'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;

                                                        arr1.push(obj1);
                                                        if (i == txnres.rows.length - 1) {
                                                            resolve(arr1)
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve([])
                                                }
                                            }, function (txnE, txnerr) { console.log(txnerr); resolve([]) },);
                                        });
                                    }).catch((err) => {
                                        console.log(err);
                                        return [];
                                    })
                                }

                                let q = `SELECT * FROM ${AppTables.STOCKWITHCAT_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;

                                await txn.executeSql(q, [], async function (txn2, txnres3) {
                                    for (var i = 0; i < txnres3.rows.length; i++) {
                                        let data2 = txnres3.rows.item(i);
                                        let { COMMON_ID, STORE_ID, VISIT_DATE, CATEGORY_ID, CATEGORY, BRAND_ID, BRAND, PRODUCT_ID, PRODUCT, MSL, STOCK, BACKROOM_STOCK, DAMAGED_STOCK, LOST_STOCK, EXPIRY_STOCK, IS_SKU_STOCK_PRESENT, NREXPIRY1_STOCK, NREXPIRY2_STOCK, NREXPIRY3_STOCK, ADDED_DATE } = data2;
                                        let mfdStocks = await getMFDStockData(data2);

                                        let obj = {};
                                        obj['MID'] = MID;
                                        obj['UserId'] = UserId;
                                        obj['Msl'] = (MSL == 'true' || MSL == true) ? 1 : 0;
                                        obj['CategoryId'] = CATEGORY_ID;
                                        obj['ProductId'] = PRODUCT_ID;
                                        obj['Stock'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;
                                        obj['BackRoomStock'] = BACKROOM_STOCK != null && BACKROOM_STOCK != "" && BACKROOM_STOCK != "null" && BACKROOM_STOCK != "undefined" ? BACKROOM_STOCK : 0;
                                        obj['DamagedStock'] = DAMAGED_STOCK != null && DAMAGED_STOCK != "" && DAMAGED_STOCK != "null" && DAMAGED_STOCK != "undefined" ? DAMAGED_STOCK : 0;
                                        obj['LostStock'] = LOST_STOCK != null && LOST_STOCK != "" && LOST_STOCK != "null" && LOST_STOCK != "undefined" ? LOST_STOCK : 0;
                                        obj['ExpiryStock'] = EXPIRY_STOCK != null && EXPIRY_STOCK != "" && EXPIRY_STOCK != "null" && EXPIRY_STOCK != "undefined" ? EXPIRY_STOCK : 0;
                                        obj['MFD_Stocks'] = mfdStocks || [];
                                        obj['IsSKUPresent'] = IS_SKU_STOCK_PRESENT;
                                        obj['NrExpiry1_Stock'] = NREXPIRY1_STOCK != null && NREXPIRY1_STOCK != "" && NREXPIRY1_STOCK != "null" && NREXPIRY1_STOCK != "undefined" ? NREXPIRY1_STOCK : 0;
                                        obj['NrExpiry2_Stock'] = NREXPIRY2_STOCK != null && NREXPIRY2_STOCK != "" && NREXPIRY2_STOCK != "null" && NREXPIRY2_STOCK != "undefined" ? NREXPIRY2_STOCK : 0;
                                        obj['NrExpiry3_Stock'] = NREXPIRY3_STOCK != null && NREXPIRY3_STOCK != "" && NREXPIRY3_STOCK != "null" && NREXPIRY3_STOCK != "undefined" ? NREXPIRY3_STOCK : 0;
                                        allChilds.push(obj);
                                    }



                                    let alljsonData = {};
                                    alljsonData['StockImgs'] = allImages;
                                    alljsonData['StockChilds'] = allChilds;

                                    postData['MID'] = MID;
                                    postData['Keys'] = 'StockWithCat';
                                    postData['JsonData'] = JSON.stringify(alljsonData);
                                    postData['UserId'] = UserId;
                                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                                    console.log('stockwithcat postData', postData);

                                }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                })
            }
        case 'OPSTOCK':
            {
                // Stocks
                var postData = {};
                let KPIFields = await getKPIFields({ "ScreenName": "OPSTOCK" });
                let isExpStock1Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock1')
                let isExpStock1PIObj = isExpStock1Index >= 0 ? KPIFields[isExpStock1Index] : {};
                let isExpStock1Enable = isExpStock1Index >= 0 ? isExpStock1PIObj['KPIFieldEnable'] : false;
                let isExpStock2Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock2')
                let isExpStock2PIObj = isExpStock2Index >= 0 ? KPIFields[isExpStock2Index] : {};
                let isExpStock2Enable = isExpStock2Index >= 0 ? isExpStock2PIObj['KPIFieldEnable'] : false;
                let isExpStock3Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock3')
                let isExpStock3PIObj = isExpStock3Index >= 0 ? KPIFields[isExpStock3Index] : {};
                let isExpStock3Enable = isExpStock3Index >= 0 ? isExpStock3PIObj['KPIFieldEnable'] : false;
                let isExpStock4Index = KPIFields.findIndex(i => i.KPIFieldName == 'ExpiryStock4')
                let isExpStock4PIObj = isExpStock4Index >= 0 ? KPIFields[isExpStock4Index] : {};
                let isExpStock4Enable = isExpStock4Index >= 0 ? isExpStock4PIObj['KPIFieldEnable'] : false;
                let isStockCalculateIndex = KPIFields.findIndex(i => i.KPIFieldName == 'StockCalculate')
                let isStockCalculatePIObj = isStockCalculateIndex >= 0 ? KPIFields[isStockCalculateIndex] : {};
                let isStockCalculateEnable = isStockCalculateIndex >= 0 ? isStockCalculatePIObj['KPIFieldEnable'] : false;
                let expiryEnable = isStockCalculateEnable || isExpStock1Enable || isExpStock2Enable || isExpStock3Enable || isExpStock4Enable

                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.INSERT_OPENINGHEADER_DATA} WHERE STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + `  `;
                        let allImages = [], allChilds = [], allChildsExp = [];
                        let allKPIfiles = [];

                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                console.log("hdr count:", txnres2.rows.length);
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let imgsData = {};
                                    if (data && data.IMAGE != null && data.IMAGE != "null" && data.IMAGE != undefined && data.IMAGE != "undefined" && data.IMAGE != '') {
                                        imgsData['MID'] = MID;
                                        imgsData['UserId'] = UserId;
                                        imgsData['CategoryId'] = data.CATEGORY_ID;
                                        imgsData['CategoryImg'] = data.IMAGE;

                                        allImages.push(imgsData);
                                    }

                                    if (data.IMAGE != '' && data.IMAGE != null) {
                                        let imgPath = common_ImagePath + data.IMAGE;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: data.IMAGE,
                                            filetype: 'image',
                                            folderName: 'StockImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                }

                                async function getStocks(qry) {
                                    console.log("qry in OPS:", qry);
                                    let allprds = [];
                                    return new Promise((resolve, reject) => {
                                        db.transaction(async function (txn) {
                                            txn.executeSql(qry, [], async function (txn2, txnres4) {
                                                if (txnres4.rows.length > 0) {
                                                    for (var i = 0; i < txnres4.rows.length; i++) {
                                                        let data2 = txnres4.rows.item(i);
                                                        let { ARTICLE_CODE, COMMON_ID, STORE_ID, VISIT_DATE, CATEGORY_ID, CATEGORY, BRAND_ID, BRAND, PRODUCT_ID, PRODUCT, MSL, OPENING_STOCK, MIDDAY_STOCK, CLOSING_STOCK, EXPIRY_ISOPEN, EXPIRY_STK, ADDED_DATE } = data2;
                                                        let obj = {};
                                                        obj['MID'] = MID;
                                                        obj['UserId'] = UserId;
                                                        obj['Msl'] = (MSL == 'true' || MSL == true) ? 1 : 0;
                                                        obj['ArticleCode'] = ARTICLE_CODE || "";
                                                        obj['CategoryId'] = CATEGORY_ID;
                                                        obj['ProductId'] = PRODUCT_ID;
                                                        obj['OPS'] = OPENING_STOCK != null && OPENING_STOCK != "null" && OPENING_STOCK != 'undefined' && OPENING_STOCK != '' ? OPENING_STOCK : 0;
                                                        obj['MDS'] = MIDDAY_STOCK != null && MIDDAY_STOCK != "null" && MIDDAY_STOCK != 'undefined' && MIDDAY_STOCK != '' ? MIDDAY_STOCK : 0;
                                                        obj['CLS'] = CLOSING_STOCK != null && CLOSING_STOCK != "null" && CLOSING_STOCK != 'undefined' && CLOSING_STOCK != '' ? CLOSING_STOCK : 0;

                                                        obj['ExpirySTKOpen'] = EXPIRY_ISOPEN;
                                                        obj['ExpirySTK'] = EXPIRY_STK;

                                                        allprds.push(obj);
                                                        if (i == txnres4.rows.length - 1) {
                                                            resolve(allprds);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allprds);
                                                }
                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allprds); });
                                        });
                                    })
                                }

                                async function getStocksExp(qry) {
                                    console.log("qry in OPS:", qry);
                                    let allprds = [];
                                    return new Promise((resolve, reject) => {
                                        db.transaction(async function (txn) {
                                            txn.executeSql(qry, [], async function (txn2, txnres4) {
                                                if (txnres4.rows.length > 0) {
                                                    for (var i = 0; i < txnres4.rows.length; i++) {
                                                        let data2 = txnres4.rows.item(i);
                                                        let { COMMON_ID, STORE_ID, VISIT_DATE, CATEGORY_ID, CATEGORY, BRAND_ID, BRAND, PRODUCT_ID, PRODUCT, MSL, OPENING_STOCK, MIDDAY_STOCK, CLOSING_STOCK, EXPIRY_ISOPEN, EXPIRY_STK,
                                                            MIDDAY_EXPIRYSTOCK1, MIDDAY_EXPIRYSTOCK2, MIDDAY_EXPIRYSTOCK3, MIDDAY_EXPIRYSTOCK4,
                                                            EXPIRYSTOCK1, EXPIRYSTOCK2, EXPIRYSTOCK3, EXPIRYSTOCK4,
                                                            CLOSING_EXPIRYSTOCK1, CLOSING_EXPIRYSTOCK2, CLOSING_EXPIRYSTOCK3, CLOSING_EXPIRYSTOCK4,
                                                            ADDED_DATE } = data2;
                                                        let obj = {};

                                                        obj['MID'] = MID;
                                                        obj['UserId'] = UserId;
                                                        obj['Msl'] = (MSL == 'true' || MSL == true) ? 1 : 0;
                                                        obj['CategoryId'] = CATEGORY_ID;
                                                        obj['ProductId'] = PRODUCT_ID;
                                                        
                                                        obj['MDS_ExpiryStock1'] = MIDDAY_EXPIRYSTOCK1 != null && MIDDAY_EXPIRYSTOCK1 != "null" && MIDDAY_EXPIRYSTOCK1 != 'undefined' && MIDDAY_EXPIRYSTOCK1 != '' ? MIDDAY_EXPIRYSTOCK1 : 0;
                                                        obj['MDS_ExpiryStock2'] = MIDDAY_EXPIRYSTOCK2 != null && MIDDAY_EXPIRYSTOCK2 != "null" && MIDDAY_EXPIRYSTOCK2 != 'undefined' && MIDDAY_EXPIRYSTOCK2 != '' ? MIDDAY_EXPIRYSTOCK2 : 0;
                                                        obj['MDS_ExpiryStock3'] = MIDDAY_EXPIRYSTOCK3 != null && MIDDAY_EXPIRYSTOCK3 != "null" && MIDDAY_EXPIRYSTOCK3 != 'undefined' && MIDDAY_EXPIRYSTOCK3 != '' ? MIDDAY_EXPIRYSTOCK3 : 0;
                                                        obj['MDS_ExpiryStock4'] = MIDDAY_EXPIRYSTOCK4 != null && MIDDAY_EXPIRYSTOCK4 != "null" && MIDDAY_EXPIRYSTOCK4 != 'undefined' && MIDDAY_EXPIRYSTOCK4 != '' ? MIDDAY_EXPIRYSTOCK4 : 0;

                                                        obj['OPS_ExpiryStock1'] = EXPIRYSTOCK1 != null && EXPIRYSTOCK1 != "null" && EXPIRYSTOCK1 != 'undefined' && EXPIRYSTOCK1 != '' ? EXPIRYSTOCK1 : 0;
                                                        obj['OPS_ExpiryStock2'] = EXPIRYSTOCK2 != null && EXPIRYSTOCK2 != "null" && EXPIRYSTOCK2 != 'undefined' && EXPIRYSTOCK2 != '' ? EXPIRYSTOCK2 : 0;
                                                        obj['OPS_ExpiryStock3'] = EXPIRYSTOCK3 != null && EXPIRYSTOCK3 != "null" && EXPIRYSTOCK3 != 'undefined' && EXPIRYSTOCK3 != '' ? EXPIRYSTOCK3 : 0;
                                                        obj['OPS_ExpiryStock4'] = EXPIRYSTOCK4 != null && EXPIRYSTOCK4 != "null" && EXPIRYSTOCK4 != 'undefined' && EXPIRYSTOCK4 != '' ? EXPIRYSTOCK4 : 0;

                                                        obj['CLS_ExpiryStock1'] = CLOSING_EXPIRYSTOCK1 != null && CLOSING_EXPIRYSTOCK1 != "null" && CLOSING_EXPIRYSTOCK1 != 'undefined' && CLOSING_EXPIRYSTOCK1 != '' ? CLOSING_EXPIRYSTOCK1 : 0;
                                                        obj['CLS_ExpiryStock2'] = CLOSING_EXPIRYSTOCK2 != null && CLOSING_EXPIRYSTOCK2 != "null" && CLOSING_EXPIRYSTOCK2 != 'undefined' && CLOSING_EXPIRYSTOCK2 != '' ? CLOSING_EXPIRYSTOCK2 : 0;
                                                        obj['CLS_ExpiryStock3'] = CLOSING_EXPIRYSTOCK3 != null && CLOSING_EXPIRYSTOCK3 != "null" && CLOSING_EXPIRYSTOCK3 != 'undefined' && CLOSING_EXPIRYSTOCK3 != '' ? CLOSING_EXPIRYSTOCK3 : 0;
                                                        obj['CLS_ExpiryStock4'] = CLOSING_EXPIRYSTOCK4 != null && CLOSING_EXPIRYSTOCK4 != "null" && CLOSING_EXPIRYSTOCK4 != 'undefined' && CLOSING_EXPIRYSTOCK4 != '' ? CLOSING_EXPIRYSTOCK4 : 0;

                                                    
                                                        allprds.push(obj);
                                                        if (i == txnres4.rows.length - 1) {
                                                            resolve(allprds);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allprds);
                                                }
                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allprds); });
                                        });
                                    })
                                }

                                let checkq = ` SELECT * FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + `  `;
                                const MAXObjCount = 250;

                                await txn.executeSql(checkq, [], async function (txn2, txnres2) {
                                    //if product count is greater than 250 then upload part by part (in limit of 250)
                                    console.log("prd count:", txnres2.rows.length);
                                    if (txnres2.rows.length > MAXObjCount) {
                                        let partsCount = Math.ceil(txnres2.rows.length / MAXObjCount);
                                        let PrdsByParts = [];
                                        console.log("partsCount:", partsCount);
                                        for (let i = 0; i < partsCount; i++) {
                                            let Offset = (i * MAXObjCount);
                                            let q = `SELECT * FROM ${AppTables.STOCK_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` LIMIT ${MAXObjCount} OFFSET ${Offset} `;
                                            let allProducts = await getStocks(q);
                                            let obj1 = { "PartNo": i, "Products": allProducts };
                                            PrdsByParts.push(obj1);
                                            if (i == partsCount - 1) {
                                                postData['MID'] = MID;
                                                postData['Keys'] = 'Stocks';
                                                postData['UploadByPart'] = true;
                                                postData['PartsCount'] = partsCount;
                                                postData['PartsData'] = PrdsByParts;
                                                postData['AllImages'] = allImages;
                                                postData['UserId'] = UserId;
                                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                                            }
                                        }

                                    }
                                    else {
                                        allChilds = await getStocks(checkq);



                                        let alljsonData = {};
                                        alljsonData['StockImgs'] = allImages;
                                        alljsonData['StockChilds'] = allChilds;
                                        if (expiryEnable) {
                                            allChildsExp = await getStocksExp(checkq);
                                            alljsonData['StockExpiry'] = allChildsExp;
                                        } else {
                                            alljsonData['StockExpiry'] = [];
                                        }
                                        postData['MID'] = MID;
                                        postData['Keys'] = 'Stocks';
                                        postData['JsonData'] = JSON.stringify(alljsonData);
                                        postData['UserId'] = UserId;
                                        resolve({ 'Files': allKPIfiles, 'PostData': postData });
                                    }


                                }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                })
            }
        case 'BACKSTOCK':
            {
                // BRS
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q = `SELECT * FROM ${AppTables.CHILD_BACK_OF_STORE} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allChilds = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { ARTICLE_CODE, COMMON_ID, STORE_ID, VISIT_DATE, CATEGORY, CATEGORY_ID, PRODUCT, PRODUCT_ID, MSL, STOCK, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Msl'] = (MSL == 'true' || MSL == true) ? 1 : 0;
                                    obj['ArticleCode'] = ARTICLE_CODE || "";
                                    obj['CategoryId'] = CATEGORY_ID;
                                    obj['ProductId'] = PRODUCT_ID;
                                    obj['BCKStock'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;
                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'BCK';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                resolve({ 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }

                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'ONEAPPSTOCKQRSCAN':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q = `SELECT * FROM ${AppTables.QRCODE_SCANNER} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        console.log("checkQRquery", q)
                        let allChilds = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    console.log("checkQRquerydata", data)
                                    let { QRCODE_ID, STORE_ID, VISIT_DATE, UNIQUE_QRCODE, ADDED_DATE, PRODUCT_ID } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['UniqueQRcode'] = UNIQUE_QRCODE;
                                    obj['productId'] = PRODUCT_ID;
                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'STOCK_UNIQUEQRCODE';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                console.log('UNIQUEQRCODE data', postData)
                                resolve({ 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }

                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }

        case 'ONEAPPSALEQRSCAN':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q = `SELECT * FROM ${AppTables.QRCODE_SALE} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        console.log("checkQRquery", q)
                        let allChilds = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    console.log("checkQRSaleQueryData", data)
                                    let { QRCODE_ID, STORE_ID, VISIT_DATE, UNIQUE_QRCODE, ADDED_DATE, PRODUCT_ID } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['UniqueQRcode'] = UNIQUE_QRCODE;
                                    obj['productId'] = PRODUCT_ID;
                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'SALE_UNIQUEQRCODE';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                console.log('SALE_UNIQUEQRCODE data', postData)
                                resolve({ 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }

                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'KYCONEAPP':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q = `SELECT * FROM ${AppTables.STORE_KYC_INFO} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        console.log("checkQRquery", q)
                        let allChilds = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    console.log("checkSTORE_KYC_INFO", data)
                                    let { STORE_ID, KYC_DATA } = data;
                                    let obj = {};
                                    try {
                                        let kycData = JSON.parse(KYC_DATA);
                                        obj = { ...kycData };
                                    } catch (e) {
                                        console.error('Error parsing KYC_DATA:', e);
                                        obj = {}; // Fallback to empty object if parsing fails
                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'KYCONEAPP';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                console.log('KYCONEAPP data', postData)
                                resolve({ 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }

                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'SOS':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.SHARE_OF_SHELF_IMAGE} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allImages = [], allChilds = [];
                        let allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let imgsData = {};

                                    imgsData['MID'] = MID;
                                    imgsData['UserId'] = UserId;
                                    imgsData['CategoryId'] = data.CATEGORY_ID;
                                    imgsData['CategoryImg'] = data.IMAGE != null && data.IMAGE != 'undefined' ? data.IMAGE : '';
                                    allImages.push(imgsData);

                                    if (data.IMAGE != '' && data.IMAGE != null) {
                                        let imgPath = common_ImagePath + data.IMAGE;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: data.IMAGE,
                                            filetype: 'image',
                                            folderName: 'ShareOfShelfImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                }

                                let q = `SELECT * FROM ${AppTables.SHARE_OF_SHELF_FACING_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                                await txn.executeSql(q, [], async function (txn2, txnres3) {
                                    for (var i = 0; i < txnres3.rows.length; i++) {
                                        let data2 = txnres3.rows.item(i);
                                        let { COMMON_ID, STORE_ID, VISIT_DATE, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, SUB_CATEGORY_STOCK, STOCK, IMAGE1, ADDED_DATE } = data2;
                                        let obj = {};
                                        obj['MID'] = MID;
                                        obj['UserId'] = UserId;
                                        obj['CategoryId'] = CATEGORY_ID;
                                        obj['SubCategoryId'] = SUB_CATEGORY_ID;
                                        obj['TotalFacing'] = SUB_CATEGORY_STOCK != '' && SUB_CATEGORY_STOCK != null && SUB_CATEGORY_STOCK != "null" && SUB_CATEGORY_STOCK != "undefined" ? SUB_CATEGORY_STOCK : 0;
                                        obj['SelfFacing'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;
                                        obj['Image1'] = IMAGE1 != null ? IMAGE1 : '';
                                        allChilds.push(obj);

                                        if (IMAGE1 != '' && IMAGE1 != null) {
                                            let imgPath = common_ImagePath + IMAGE1;
                                            let file = {
                                                uri: imgPath,
                                                type: 'image/jpeg',
                                                name: IMAGE1,
                                                filetype: 'image',
                                                folderName: 'ShareOfShelfImages',
                                            }
                                            allKPIfiles.push(file);
                                        }

                                    }

                                    let alljsonData = {};
                                    alljsonData['SOSImg'] = allImages;
                                    alljsonData['ShareOfSelf'] = allChilds;

                                    postData['MID'] = MID;
                                    postData['Keys'] = 'SOS';
                                    postData['JsonData'] = JSON.stringify(alljsonData);
                                    postData['UserId'] = UserId;
                                    resolve({ 'Files': allKPIfiles, 'PostData': postData });

                                }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'PAIDVISI':
            {
                // PaidVis
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.PAID_VISIBILITY_CHILD_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allChilds = [];
                        let allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { COMMON_ID, STORE_ID, VISIT_DATE, SUB_CATEGORY, SUB_CATEGORY_ID, VISIBILITY_PRESENT, DISPLAY_ID, DISPLAY, IMAGE1, IMAGE2, REASON, REASON_ID, REASON_REMARK, ADDED_DATE } = data;
                                    let displayCheckList_obj = await getDisplayCheckList(DISPLAY_ID, SUB_CATEGORY_ID, storeData);
                                    let displayCheckList = displayCheckList_obj.Results || [];
                                    let obj = {};

                                    obj['MID'] = MID;
                                    obj['User_Id'] = UserId;
                                    obj['SubCategoryId'] = SUB_CATEGORY_ID;
                                    obj['DisplayId'] = DISPLAY_ID;
                                    obj['Present'] = VISIBILITY_PRESENT;
                                    obj['ImgOne'] = IMAGE1;
                                    obj['ImgTwo'] = IMAGE2;
                                    obj['ReasonId'] = REASON_ID;
                                    obj['ReasonRemark'] = REASON_REMARK;


                                    let imgPath = common_ImagePath + IMAGE1;
                                    let imgPath2 = common_ImagePath + IMAGE2;
                                    console.log('IMAGE2:', IMAGE2, ' , IMAGE1:', IMAGE1);

                                    if (IMAGE1 != '' && IMAGE1 != null) {
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: IMAGE1,
                                            filetype: 'image',
                                            folderName: 'VisibilityImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    if (IMAGE2 != '' && IMAGE2 != null) {
                                        let file2 = {
                                            uri: imgPath2,
                                            type: 'image/jpeg',
                                            name: IMAGE2,
                                            filetype: 'image',
                                            folderName: 'VisibilityImages',
                                        }
                                        allKPIfiles.push(file2);
                                    }



                                    if (displayCheckList.length > 0) {
                                        let checkl_data = [];
                                        for (var i = 0; i < displayCheckList.length; i++) {
                                            let data2 = displayCheckList[i];
                                            let { ChecklistId, ChecklistName, REASON, REASON_ID } = data2;
                                            let chlobj = {};
                                            chlobj['MID'] = MID;
                                            chlobj['User_Id'] = UserId;
                                            chlobj['SubCategoryId'] = SUB_CATEGORY_ID;
                                            chlobj['DisplayId'] = DISPLAY_ID;
                                            chlobj['ChecklistId'] = ChecklistId;
                                            chlobj['AnswerId'] = REASON_ID;

                                            checkl_data.push(chlobj);
                                        }
                                        obj['Checklists'] = checkl_data;
                                    }
                                    else {
                                        obj['Checklists'] = "";
                                    }
                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'PaidVisibility';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                // console.log('PaidVis',postData)
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'ADDITIONALVISI':
            {
                var postData = await getDataFor_ADVONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("ADDITIONALVISI postData:", postData)
                return postData;
            }

        case 'ADDITIONALVISI_IR':
            {
                var postData = await getDataFor_ADVONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("ADDITIONALVISI IR postData:", postData)
                return postData;
            }

        case 'RETURNSTOCKONEAPP':
            {
                var postData = await getDataFor_RETURN_STOCK(storeData, KpiData, UserId, previousDayUpload);
                console.log("RETURNSTOCKONEAPP postData:", postData)
                return postData;
            }

        case 'ORDERSIMPLIFYONEAPP':
            {
                var postData = await getDataFor_ORDER_SIMPLIFY(storeData, KpiData, UserId, previousDayUpload);
                console.log("ORDERSIMPLIFYONEAPP postData:", postData)
                return postData;
            }


        case 'COMPVISI':
            {
                var postData = await getDataFor_COMPVONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("COMPVISI postData:", postData)
                return postData;
            }
        case 'COMPVISI_IR':
            {
                var postData = await getDataFor_COMPVONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("COMPVISI IR postData:", postData)
                return postData;
            }

        case 'PROMOTION':
            {
                // Promotion
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.PROMOTION_DATA} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { COMMON_ID, STORE_ID, VISIT_DATE, SUB_CATEGORY, SUB_CATEGORY_ID, PROMOTION, PROMOTION_ID, STOCK_AVL, PROMOTALK_AVL, POS_AVL, IMAGE1, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['User_Id'] = UserId;
                                    obj['SubCategoryId'] = SUB_CATEGORY_ID;
                                    obj['PromotionId'] = PROMOTION_ID;
                                    obj['StockAvl'] = STOCK_AVL;
                                    obj['PromoTalkerAvl'] = PROMOTALK_AVL;
                                    obj['POSAvl'] = POS_AVL;
                                    if (STOCK_AVL == 1 || PROMOTALK_AVL == 1 || POS_AVL == 1) {
                                        obj['PromoImg'] = IMAGE1;
                                        if (IMAGE1 != '' && IMAGE1 != null) {
                                            let imgPath = common_ImagePath + IMAGE1;
                                            let file = {
                                                uri: imgPath,
                                                type: 'image/jpeg',
                                                name: IMAGE1,
                                                filetype: 'image',
                                                folderName: 'PromotionImages',
                                            }
                                            allKPIfiles.push(file);
                                        }
                                    }
                                    else {
                                        obj['PromoImg'] = "";
                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'Promotion';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'PROMOTION2':
            {
                // Promotion2
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT Distinct t1.*,m.Camera1Enable,m.Camera2Enable FROM ${AppTables.SIMPLE_PROMOTION_DATA} t1 Inner Join Mapping_Promotion m on m.PromoId=t1.PROMOTION_ID  WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { COMMON_ID, STORE_ID, VISIT_DATE, SUB_CATEGORY, SUB_CATEGORY_ID, PROMOTION, PROMOTION_ID, IS_PRESENT, REASON_ID, REASON, IMAGE1, ADDED_DATE, Camera1Enable } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['User_Id'] = UserId;
                                    obj['SubCategoryId'] = SUB_CATEGORY_ID;
                                    obj['PromotionId'] = PROMOTION_ID;
                                    obj['IsPresent'] = IS_PRESENT;
                                    obj['ReasonId'] = REASON_ID;
                                    obj['Image1'] = IMAGE1;


                                    let CE1 = (Camera1Enable == 1 || Camera1Enable == 'true') ? true : false;
                                    if (IS_PRESENT == 1 && CE1 == true && IMAGE1 != '') {

                                        let imgPath = common_ImagePath + IMAGE1;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: IMAGE1,
                                            filetype: 'image',
                                            folderName: 'Promotion2Images',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'Promotion2';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                // console.log('promotin2 postData',postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'COMPROMO':
            {
                // CompPromo
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.COMPETITION_PROMOTION} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { STORE_ID, VISIT_DATE, PRESENT, COMPANY, COMPANY_ID, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, PROMO_TYPE, PROMO_TYPE_ID, PRODUCT, PRODUCT_ID, PROMO_DETAILS, MRP, SELLING_PRICE, DISCOUNT_PERCENT, GRAMMAGE, IMAGE, IMAGE2, IMAGE3, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['User_Id'] = UserId;
                                    obj['Present'] = PRESENT;
                                    console.log('CompPromo,PRESENT:', PRESENT);
                                    if (PRESENT == 1) {
                                        obj['CompanyId'] = COMPANY_ID;
                                        obj['CategoryId'] = CATEGORY_ID;
                                        obj['SubCategoryId'] = SUB_CATEGORY_ID;
                                        obj['BrandId'] = BRAND_ID;
                                        obj['ProductId'] = PRODUCT_ID;
                                        obj['PromoTypeId'] = PROMO_TYPE_ID;
                                        obj['Promodetails'] = PROMO_DETAILS;
                                        obj['MRP'] = MRP != '' && MRP != null && MRP != "null" && MRP != "undefined" ? MRP : 0;;
                                        obj['SellingPrice'] = SELLING_PRICE != '' && SELLING_PRICE != null && SELLING_PRICE != "null" && SELLING_PRICE != "undefined" ? SELLING_PRICE : 0;;
                                        obj['DiscountPercent'] = DISCOUNT_PERCENT != '' && DISCOUNT_PERCENT != null && DISCOUNT_PERCENT != "null" && DISCOUNT_PERCENT != "undefined" ? DISCOUNT_PERCENT : 0;
                                        obj['Grammage'] = GRAMMAGE != '' && GRAMMAGE != null && GRAMMAGE != "null" && GRAMMAGE != "undefined" ? GRAMMAGE : 0;
                                        obj['CompPromoImg'] = IMAGE;
                                        obj['CompPromoImg2'] = IMAGE2 != null && IMAGE2 != 'undefined' ? IMAGE2 : '';
                                        obj['CompPromoImg3'] = IMAGE3 != null && IMAGE3 != 'undefined' ? IMAGE3 : '';



                                    }
                                    else {
                                        obj['CompanyId'] = 0;
                                        obj['CategoryId'] = 0;
                                        obj['SubCategoryId'] = 0;
                                        obj['BrandId'] = 0;
                                        obj['ProductId'] = 0;
                                        obj['PromoTypeId'] = 0;
                                        obj['Promodetails'] = "";
                                        obj['MRP'] = 0;
                                        obj['SellingPrice'] = 0;
                                        obj['DiscountPercent'] = 0;
                                        obj['Grammage'] = 0;
                                        obj['CompPromoImg'] = "";
                                        obj['CompPromoImg2'] = "";
                                        obj['CompPromoImg3'] = "";

                                    }


                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'CompPromotion';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'CONCOV':
            {
                // Contacts
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` AND SCREEN_TYPE='Contact' `;

                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                let data = txnres2.rows.item(0);
                                let { STORE_ID, VISIT_DATE, TOTAL_CONTACT, CST_CONTACT, ADDED_DATE } = data;
                                let obj = {};
                                obj['MID'] = MID;
                                obj['User_Id'] = UserId;
                                obj['TotalContact'] = TOTAL_CONTACT != '' && TOTAL_CONTACT != null && TOTAL_CONTACT != "null" && TOTAL_CONTACT != "undefined" ? TOTAL_CONTACT : 0;
                                obj['CSTConverted'] = CST_CONTACT != '' && CST_CONTACT != null && CST_CONTACT != "null" && CST_CONTACT != "undefined" ? CST_CONTACT : 0;


                                postData['MID'] = MID;
                                postData['Keys'] = 'ConversionTracking';
                                postData['JsonData'] = JSON.stringify(obj);
                                postData['UserId'] = UserId;
                                console.log("TotalContact-postData-", TOTAL_CONTACT, postData)
                                resolve({ 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'SALE':
            {
                // Sale
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.SALES} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` and STOCK is not NULL and STOCK!='' and STOCK>0`;
                        let allChilds = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { ARTICLE_CODE, STORE_ID, VISIT_DATE, CATEGORY, CATEGORY_ID, PRODUCT, PRODUCT_ID, MSL, STOCK, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Msl'] = (MSL == 'true' || MSL == true) ? 1 : 0;
                                    obj['ArticleCode'] = ARTICLE_CODE || "";
                                    obj['CategoryId'] = CATEGORY_ID;
                                    obj['ProductId'] = PRODUCT_ID;
                                    obj['Sales'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'Sales';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                // console.log("postdata sale:",postData);
                                resolve({ 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'ORDER':
            {
                // Order
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {

                        let q2 = ` SELECT * FROM ${AppTables.ORDER} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and STOCK >0 and VISIT_DATE='${d2}' ` : '') + ` `;

                        let allChilds = [], allData = {};
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { CATEGORY, CATEGORY_ID, PRODUCT, STOCKIST_ID, STOCKIST_NAME, REASON_ID, PRODUCT_ID, STOCK, REASON, IS_PRESENT, SYSTEM_PO, STORE_PO, PO_DATE, CONTACT_NAME, CONTACT_NO } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['CategoryId'] = CATEGORY_ID;
                                    obj['ProductId'] = PRODUCT_ID;
                                    obj['OrderQty'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;

                                    if (IS_PRESENT == 1) {
                                        allChilds.push(obj);
                                    }

                                    if (i == 0) {
                                        allData['MID'] = MID;
                                        allData['UserId'] = UserId;
                                        allData['IsPresent'] = IS_PRESENT;
                                        allData['Reason'] = REASON;
                                        allData['ReasonId'] = REASON_ID;
                                        allData['SystemPO'] = SYSTEM_PO;
                                        allData['StorePO'] = STORE_PO != null ? STORE_PO : '';
                                        allData['ContactName'] = CONTACT_NAME != null ? CONTACT_NAME : '';
                                        allData['ContactNo'] = CONTACT_NO != null ? CONTACT_NO : '';
                                        allData['StockistId'] = STOCKIST_ID != null ? STOCKIST_ID : '';
                                        allData['StockistName'] = STOCKIST_NAME != null ? STOCKIST_NAME : '';

                                    }
                                    if (i == txnres2.rows.length - 1) {
                                        allData['OrderSKUList'] = allChilds;
                                    }
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'Order';
                                postData['JsonData'] = JSON.stringify(allData);
                                postData['UserId'] = UserId;
                                console.log('Order postData:', postData);
                                resolve({ 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'ORDERSTATUS': {
            var postData = {};
            return new Promise((resolve, reject) => {
                db.transaction(async function (txn) {


                    let q2 = `Select * FROM ${AppTables.ORDERSTATUS} Where STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
                    console.log("orderstatusq--", q2)

                    let allChilds = [], allChilds2 = [], allKPIfiles = [];
                    await txn.executeSql(q2, [], async function (txn2, txnres2) {
                        if (txnres2.rows.length > 0) {
                            for (var i = 0; i < txnres2.rows.length; i++) {
                                let data = txnres2.rows.item(i);
                                let { STORE_ID, VISIT_DATE, IMAGES, ORDER_ID, ORDER_QTY, PRODUCT_ID, ISPRESENT, ADDED_DATE, INVOICE_TYPE } = data;
                                let obj = {}, objImg = {};

                                obj['MID'] = MID;
                                obj['UserId'] = UserId;
                                obj['StoreId'] = STORE_ID;
                                obj['OrderId'] = ORDER_ID;
                                obj['ProductId'] = PRODUCT_ID;
                                obj['IsPresent'] = ISPRESENT;
                                // obj['OrderQty']=ORDER_QTY!=null && ORDER_QTY!='undefined' && ORDER_QTY!=''?ORDER_QTY:'0'; 
                                obj['OrderQty'] = ISPRESENT == 0 ? '0' : (ORDER_QTY != null && ORDER_QTY != 'undefined' && ORDER_QTY != '' ? ORDER_QTY : '0');
                                obj['InVoiceType'] = INVOICE_TYPE;


                                let imagObj = IMAGES && JSON.parse(IMAGES?.replace(/\n/g, ''));
                                objImg = {
                                    MID: MID,
                                    UserId: UserId,
                                    OrderId: ORDER_ID,
                                    StoreId: STORE_ID,
                                    InVoiceType: INVOICE_TYPE,
                                    Image1: imagObj?.Image1 || "",
                                    Image2: imagObj?.Image2 || ""
                                };
                                allChilds.push(obj);

                                if (!allChilds2.some(img => img.OrderId === objImg.OrderId)) {
                                    allChilds2.push(objImg);
                                }
                                // allChilds2.push(objImg)
                            }

                            let result = {
                                OrderImage: allChilds2,
                                data: allChilds
                            };

                            postData['MID'] = MID;
                            postData['Keys'] = 'OrderStatus';
                            postData['JsonData'] = JSON.stringify(result);
                            postData['UserId'] = UserId;

                            console.log('Order Status data:', postData);
                            resolve({ 'Files': allKPIfiles, 'PostData': postData });

                        }
                        else {
                            resolve({ 'PostData': postData });
                        }
                    }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                });
            }).then((val) => {
                return val;
            }).catch((err) => {
                console.log(err);
                return postData;
            });
        }

        case 'SURVEY':
            {
                // Survey
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {

                        let selectlist = ` DISTINCT T.SurveyId as SurveyId,T.CategoryId as CategoryId,T.Category as Category,T.MaxLength as MaxLength,T.MinLength as MinLength,T.QuestionImageAllow as QuestionImageAllow,T.DateRange as DateRange,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,ifnull(T1.IMAGE1,'')  as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,ifnull(T1.IMAGE2,'') as Image2,T1.MULTI_OPTIONS_IDS as MultiOptionsIds,T1.IS_DISABLED as isDisabled`;
                        let join = ` INNER JOIN Mapping_Survey M on T.SurveyId=M.SurveyId`;
                        let join2 = ` INNER JOIN ${AppTables.SURVEY} T1 on T.SurveyId=T1.SURVEY_ID and T.CategoryId=T1.CATEGORY_ID And T.QuestionId=T1.QUESTION_ID`;
                        let q2 = `Select ${selectlist} FROM Master_SurveyQuestion T ${join} ${join2} WHERE T1.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` AND T1.VISIT_DATE= '${d2}' ` : '') + ` and T1.MENU_ID='${MenuId}' ORDER BY T.CategorySequence `;

                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { SurveyId, CategoryId, Category, SubCategoryId, SubCategory, MaxLength, MinLength, QuestionImageAllow, DateRange, Question, QuestionId, QuestionType, OTP, Answer, AnswerId, ImageAllow1, Image1, ImageAllow2, Image2, MultiOptionsIds, isDisabled } = data;
                                    let obj = {};

                                    let isQtnDisabled = isDisabled == 1 || isDisabled == '1' ? true : false;
                                    if (!isQtnDisabled) {
                                        obj['MID'] = MID;
                                        obj['UserId'] = UserId;
                                        obj['Store_Id'] = StoreId;
                                        obj['MenuId'] = MenuId;
                                        obj['SurveyId'] = SurveyId;
                                        obj['CategoryId'] = CategoryId;
                                        obj['SubCategoryId'] = SubCategoryId;
                                        obj['QuestionId'] = QuestionId;
                                        obj['QuestionType'] = QuestionType;
                                        obj['Answer'] = Answer;
                                        obj['AnswerId'] = AnswerId;
                                        obj['MultiAnswerId'] = MultiOptionsIds != null && MultiOptionsIds != 'undefined' ? MultiOptionsIds : '';
                                        obj['AnswerImage1'] = Image1;
                                        obj['AnswerImage2'] = Image2;

                                        if (((QuestionImageAllow == 1 || QuestionImageAllow == 'true') || (ImageAllow1 == 1 | ImageAllow1 == 'true')) && Image1 != '') {
                                            let imgPath = common_ImagePath + Image1;
                                            let file = {
                                                uri: imgPath,
                                                type: 'image/jpeg',
                                                name: Image1,
                                                filetype: 'image',
                                                folderName: 'SurveyImages',
                                            }
                                            allKPIfiles.push(file);
                                        }

                                        if ((ImageAllow2 == 1 || ImageAllow2 == 'true') && Image2 != '') {
                                            let imgPath = common_ImagePath + Image2;
                                            let file = {
                                                uri: imgPath,
                                                type: 'image/jpeg',
                                                name: Image2,
                                                filetype: 'image',
                                                folderName: 'SurveyImages',
                                            }
                                            allKPIfiles.push(file);
                                        }


                                        if (QuestionType == 'Audio' && Answer != '') {
                                            let filePath = common_ImagePath + 'Recordings/' + Answer;
                                            let file = {
                                                uri: filePath,
                                                type: (Platform.OS == 'ios' ? 'audio/m4a' : 'audio/mp3'),
                                                name: Answer,
                                                filetype: 'audio',
                                                folderName: 'SurveyVoicefiles',
                                            }
                                            allKPIfiles.push(file);
                                        }

                                        allChilds.push(obj);
                                    }
                                }
                                let upkName = UploadKeyName != null && UploadKeyName != 'undefined' && UploadKeyName != '' ? UploadKeyName : 'StoreSurveys';

                                postData['MID'] = MID;
                                postData['Keys'] = upkName;
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                // console.log('survey data:',postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }
        case 'FEEDBACK':
            {
                // Feedback
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {

                        let selectlist = ` DISTINCT T.FeedbackCategoryId as CategoryId,T.FeedbackCategory as Category,T.FeedbackQuestionId as QuestionId,T.FeedbackQuestionCode as QuestionCode,T.FeedbackQuestionName as Question,T.QuestionType,T.FQShowCamera,T.FQCameraMandatory,T.FQLengthValidationRequired,T.FQMinimumChar,T.FQMaximumChar,T.FQDecimalPoint,T.FQDateRangeMin,T.FQDateRangeMax,T.FQVoiceLengthInMinutes,T.FQDefaultQuestionEnable,T.FeedbackQuestionSequence,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled `;
                        let join = ` INNER JOIN ${AppTables.FEEDBACK_DATA} T1 on T.FeedbackQuestionId=T1.QUESTION_ID and T.FeedbackCategoryId=T1.CATEGORY_ID`;
                        let q2 = `Select ${selectlist} FROM Master_FeedbackQuestion T ${join} WHERE T1.STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` AND T1.VISIT_DATE= '${d2}' ` : '') + `  ORDER BY T.FeedbackQuestionSequence  `;

                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { CategoryId, Category, MaxLength, MinLength, FQShowCamera, DateRange, Question, QuestionId, QuestionCode, QuestionType, Answer, AnswerId, ImageAllow1, Image1 } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Store_Id'] = StoreId;
                                    obj['CategoryId'] = CategoryId;
                                    obj['QuestionId'] = QuestionId;
                                    obj['Answer'] = Answer;
                                    obj['AnswerId'] = AnswerId;
                                    obj['AnswerImage1'] = Image1;

                                    if ((FQShowCamera == 1 || FQShowCamera == 'true') || (ImageAllow1 == 1 | ImageAllow1 == 'true')) {
                                        if (Image1 != '' && Image1 != null) {
                                            let imgPath = common_ImagePath + Image1;
                                            let file = {
                                                uri: imgPath,
                                                type: 'image/jpeg',
                                                name: Image1,
                                                filetype: 'image',
                                                folderName: 'FeedbackImages',
                                            }
                                            allKPIfiles.push(file);
                                        }
                                    }

                                    if (QuestionType == 'Audio' && Answer != '') {
                                        let filePath = common_ImagePath + 'Recordings/' + Answer;
                                        let file = {
                                            uri: filePath,
                                            type: (Platform.OS == 'ios' ? 'audio/m4a' : 'audio/mp3'),
                                            name: Answer,
                                            filetype: 'audio',
                                            folderName: 'FeedbackVoicefiles',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'Feedback';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }
        case 'WINDOW':
            {
                var postData = await getDataFor_WINDOW(storeData, KpiData, UserId, previousDayUpload);
                console.log("WINDOW postData:", postData)
                return postData;
            }
        case 'WINDOW_IR':
            {
                var postData = await getDataFor_WINDOW(storeData, KpiData, UserId, previousDayUpload);
                console.log("WINDOW IR postData:", postData)
                return postData;
            }

        case 'POSSALEONEAPP': {
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let join = ' cross Join Master_PosSaleDefinition '
                        let q1 = ` Select * from ${AppTables.HEADER_POSSALE_DATA} h ${join} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? `  and VISIT_DATE='${d2}' ` : '') + `  `
                        let allChilds = [], allDataUp = {}, allKPIfiles = [];
                        await txn.executeSql(q1, [], async function (txn3, txnres3) {
                            if (txnres3.rows.length > 0) {
                                let data = txnres3.rows.item(0);
                                let { MONTH, IMAGE1, IMAGE2, TOTAL_POS_VALUE, HeaderImageRequired, PosDefinitionId, HeaderImageCount } = data;
                                let dateParts = MONTH.split(" ");
                                let month = dateParts.length > 0 ? dateParts[0] : '';
                                let yr = dateParts.length > 1 ? dateParts[1] : '';

                                allDataUp['MID'] = MID;
                                allDataUp['UserId'] = UserId;
                                allDataUp['StoreId'] = StoreId;
                                allDataUp['Month'] = month;
                                allDataUp['Year'] = yr;
                                allDataUp['TotalPOSValue'] = TOTAL_POS_VALUE != '' && TOTAL_POS_VALUE != null && TOTAL_POS_VALUE != "undefined" ? TOTAL_POS_VALUE : 0;
                                allDataUp['Image1'] = IMAGE1 || '';
                                allDataUp['Image2'] = IMAGE2 || '';

                                let join1 = `inner join Master_PosSaleDefinition m on p.POSDEFINITIONID=m.PosDefinitionId `
                                let q = ` Select Distinct p.*,m.PosTable, m.PosField from ${AppTables.POSSALE_DATA} p ${join1} WHERE p.STORE_ID='${StoreId}' ` + (!previousDayUpload ? `  and p.VISIT_DATE='${d2}' ` : '') + `  `;



                                async function getPosSaleImages() {
                                    let q2 = `select * from ${AppTables.POSSALE_IMAGES} where POSDEFINITIONID='${PosDefinitionId}' and  STORE_ID='${StoreId}' and IMAGE1!='' and IMAGE1!='undefined' and IMAGE1 is not null `;

                                    let allWindowSplitImages = [];
                                    return new Promise((resolve, reject) => {
                                        db.transaction(async function (txn) {
                                            txn.executeSql(q2, [], async function (txn2, txnres3) {

                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let splitItem = txnres3.rows.item(j);
                                                        let { IMAGE1, IMAGE2 } = splitItem
                                                        let obj1 = { 'Image1': (IMAGE1 != null ? IMAGE1 : '') };
                                                        obj1['PosDefinitionId'] = PosDefinitionId
                                                        obj1['MID'] = MID;
                                                        obj1['UserId'] = UserId;
                                                        obj1['Store_Id'] = StoreId;

                                                        allWindowSplitImages.push(obj1);

                                                        if (j == txnres3.rows.length - 1) {
                                                            console.log('all images added')
                                                            resolve(allWindowSplitImages);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allWindowSplitImages);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                        });
                                    });
                                }




                                await txn.executeSql(q, [], async function (txn2, txnres2) {
                                    if (txnres2.rows.length > 0) {
                                        for (var i = 0; i < txnres2.rows.length; i++) {
                                            let data = txnres2.rows.item(i);
                                            let { WINDOW_ID, WINDOW_NAME, POSDEFINITIONID, POS_VALUE, POS_VOLUME, ISPRESENT, REASONID, REASON, PosTable, PosField } = data;
                                            let obj = {};

                                            obj['MID'] = MID;
                                            obj['UserId'] = UserId;
                                            obj['Store_Id'] = StoreId;
                                            obj['ChildId'] = WINDOW_ID;
                                            obj['ChildName'] = WINDOW_NAME;
                                            obj['PosTable'] = PosTable;
                                            obj['PosField'] = PosField;
                                            obj['POSDefinitionId'] = POSDEFINITIONID;
                                            obj['POSValue'] = POS_VALUE == null || POS_VALUE == '' ? '0' : POS_VALUE;
                                            obj['POSVolume'] = POS_VOLUME == null || POS_VOLUME == '' ? '0' : POS_VOLUME;
                                            obj['IsPresent'] = ISPRESENT;
                                            obj['ReasonId'] = REASONID == null || REASONID == '' ? '0' : REASONID;
                                            obj['Reason'] = REASON;


                                            allChilds.push(obj);

                                            if (i == txnres2.rows.length - 1) {
                                                allDataUp["POSChilds"] = allChilds;
                                                if (HeaderImageRequired && HeaderImageCount > 0) {
                                                    let posSaleImages = await getPosSaleImages();
                                                    allDataUp['PosSaleImages'] = posSaleImages
                                                }
                                                else {
                                                    allDataUp['PosSaleImages'] = []
                                                }
                                            }
                                        }

                                        postData['MID'] = MID;
                                        postData['Keys'] = 'POSSale';
                                        postData['JsonData'] = JSON.stringify(allDataUp);
                                        postData['UserId'] = UserId;
                                        console.log('postData POSSALE', postData)
                                        resolve({ 'Files': allKPIfiles, 'PostData': postData });
                                    }
                                    else {
                                        allDataUp["POSChilds"] = [];
                                        if (HeaderImageRequired && HeaderImageCount > 0) {
                                            let posSaleImages = await getPosSaleImages();
                                            allDataUp['PosSaleImages'] = posSaleImages
                                        }
                                        else {
                                            allDataUp['PosSaleImages'] = []
                                        }
                                        postData['MID'] = MID;
                                        postData['Keys'] = 'POSSale';
                                        postData['JsonData'] = JSON.stringify(allDataUp);
                                        postData['UserId'] = UserId;
                                        console.log('postData POSSALE', postData)
                                        resolve({ 'PostData': postData });
                                    }
                                },
                                    function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);


                            }
                            else {
                                resolve({ 'PostData': postData });
                            }

                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);
                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }
        }

        case 'POSM':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {

                        let selectlist = ` Distinct w.STORE_ID as StoreId,w.POSM_HEADER_ID as posmHeaderId,wd.POSMDefinitionId,wd.PosmId,wd.POSMName,wd.PosmTypeId,wd.POSMTypeName,wd.POSMTable,wd.POSMField,wd.POSMValue,wd.ChildName,wd.POSMRefImage,w.IS_PRESENT as IsPresent,wd.POSMNotExistCamera,w.POSM_NA_IMAGE as POSMNAImage,w.POSM_IMAGE1 as Image1,w.POSM_IMAGE2 as Image2,wd.POSMExistReasonEnable,wd.POSMNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,wd.POSMImage1,wd.POSMImage2,w.REASON_REMARK`;
                        let join = ` inner join Master_POSMDefinition wd on w.POSM_DEFINITION_ID=wd.POSMDefinitionId `;
                        let q = ` Select ${selectlist} from ${AppTables.POSM_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  `;

                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { posmHeaderId, POSMDefinitionId, PosmId, POSMName, PosmTypeId, POSMTypeName, POSMTable, POSMField, POSMValue, ChildName, IsPresent, POSMNotExistCamera, POSMNAImage, Image1, Image2, POSMExistReasonEnable, POSMNotExistReasonEnable, ReasonId, Reason, POSMImage1, POSMImage2, REASON_REMARK } = data;
                                    let obj = {};

                                    let isNaCamAvl = (POSMNotExistCamera == 'true' || POSMNotExistCamera == 1) ? 1 : 0;
                                    let isReasonEnable = (POSMExistReasonEnable == 'true' || POSMExistReasonEnable == 1) ? 1 : 0;
                                    let isNAReasonEnable = (POSMNotExistReasonEnable == 'true' || POSMNotExistReasonEnable == 1) ? 1 : 0;
                                    let isImage1 = (POSMImage1 == 'true' || POSMImage1 == 1) ? 1 : 0;
                                    let isImage2 = (POSMImage2 == 'true' || POSMImage2 == 1) ? 1 : 0;


                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Store_Id'] = StoreId;
                                    obj['POSMDefinitionId'] = POSMDefinitionId;
                                    obj['POSMId'] = PosmId;
                                    obj['POSMTable'] = POSMTable;
                                    obj['POSMField'] = POSMField;
                                    obj['POSMValue'] = POSMValue;
                                    obj['ChildName'] = ChildName;
                                    obj['IsPresent'] = IsPresent;
                                    obj['POSMNotExistImage'] = isNaCamAvl == 1 ? POSMNAImage : '';
                                    obj['Image1'] = isImage1 == 1 && IsPresent == 1 ? Image1 : '';
                                    obj['Image2'] = isImage2 == 1 && IsPresent == 1 ? Image2 : '';
                                    obj['ReasonId'] = IsPresent == 1 ? 0 : ReasonId;
                                    obj['ReasonRemark'] = REASON_REMARK;

                                    if (isNaCamAvl == 1 && POSMNAImage != '') {
                                        let imgPath = common_ImagePath + POSMNAImage;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: WindowNAImage,
                                            filetype: 'image',
                                            folderName: 'POSMImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    if (isImage1 == 1 && Image1 != '') {
                                        let imgPath = common_ImagePath + Image1;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: Image1,
                                            filetype: 'image',
                                            folderName: 'POSMImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    if (isImage2 == 1 && Image2 != '') {
                                        let imgPath = common_ImagePath + Image2;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: Image2,
                                            filetype: 'image',
                                            folderName: 'POSMImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    if (IsPresent == 1) {
                                        async function getPOSMQA() {

                                            let selectlist_q = ` DISTINCT  q.QUESTION_ID as POSMQuestionId,q.QUESTION_CODE as POSMQuestionCode,wq.POSMQuestionName,wq.QuestionType,wq.PQShowCamera,wq.PQCameraMandatory,wq.PQLengthValidationRequired,wq.PQMinimumChar,wq.PQMaximumChar,wq.PQDecimalPoint,wq.PQDateRangeMin,wq.PQDateRangeMax,wq.PQVoiceLengthInMinutes,wq.PQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as PAShowCamera,q.IMAGE1 as Image1  `;
                                            let join2_q = ` inner join Mapping_POSMQuestion mq on mq.POSMQuestionId=wq.POSMQuestionId `;
                                            let join_q = ` inner join Master_POSMQuestion wq on wq.POSMQuestionId=q.QUESTION_ID `;
                                            let q2 = `select ${selectlist_q} from ${AppTables.POSM_CHILD_DATA} q ${join_q} ${join2_q} where q.STORE_ID='${StoreId}' and q.POSM_DEFINITION_ID='${POSMDefinitionId}' and q.POSM_ID='${PosmId}' order by wq.POSMQuestionSequence  `;

                                            let allQAs = [];
                                            return new Promise((resolve, reject) => {
                                                db.transaction(async function (txn) {
                                                    txn.executeSql(q2, [], async function (txn2, txnres3) {

                                                        if (txnres3.rows.length > 0) {
                                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                                let QAData = txnres3.rows.item(j);
                                                                let { POSMQuestionId, AnswerId, Answer, PAShowCamera, Image1 } = QAData
                                                                let showImage1 = (PAShowCamera == 'true' || PAShowCamera == 1) ? 1 : 0;
                                                                let obj1 = {};
                                                                obj1['MID'] = MID;
                                                                obj1['POSMDefinitionId'] = POSMDefinitionId
                                                                obj1['POSMId'] = PosmId
                                                                obj1['POSMQuestionId'] = POSMQuestionId
                                                                obj1['AnswerId'] = AnswerId
                                                                obj1['Answer'] = Answer
                                                                obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                                allQAs.push(obj1);

                                                                if (showImage1 == 1 && Image1 != null && Image1 != '') {
                                                                    let imgPath = common_ImagePath + Image1;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: Image1,
                                                                        filetype: 'image',
                                                                        folderName: 'POSMImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }
                                                                if (j == txnres3.rows.length - 1) {
                                                                    resolve(allQAs);
                                                                }
                                                            }
                                                        }
                                                        else {
                                                            resolve(allQAs);
                                                        }

                                                    }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                                });
                                            });
                                        }
                                        obj['QuestionAnswers'] = await getPOSMQA();
                                        console.log(obj);

                                    }
                                    else {
                                        obj['QuestionAnswers'] = []
                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'POSM';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                //   console.log('POSM',postData)
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }
        case 'STOREIMG':
            {
                // StoreImages
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.STORE_IMAGES} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? `  and VISIT_DATE='${d2}' ` : '') + ` `;
                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { STORE_ID, VISIT_DATE, IMAGE_TYPE_ID, IMAGE_TYPE, IMAGE, LAT, LNG, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['User_Id'] = UserId;
                                    obj['ImageTypeId'] = IMAGE_TYPE_ID;
                                    obj['Image'] = IMAGE;
                                    obj['Latitude'] = LAT || 0;
                                    obj['Longitude'] = LNG || 0;

                                    if (IMAGE != null && IMAGE != '') {
                                        let imgPath = common_ImagePath + IMAGE;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: IMAGE,
                                            filetype: 'image',
                                            folderName: 'StoreImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'StoreImages';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                // console.log('StoreImages postData',postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }
        case 'SHELFTALKER':
            {

                // ShelfTalker
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let txn1 = txn;
                        let selectlist = ` Distinct w.STORE_ID as StoreId,w.ST_HEADER_ID as stHeaderId,wd.StDefinitionId,wd.ShelfTalkerId,wd.StName,wd.StTable,wd.StField,wd.StValue,wd.ChildName,wd.StRefImage,wd.StElementCheckAssortment,wd.StElementStockRequired,w.IS_PRESENT as IsPresent,wd.StNotExistCamera,w.ST_NA_IMAGE as StNAImage,wd.StExistReasonEnable,wd.StNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.StImage1,wd.StImage2,wd.StImage1Lable,wd.StImage2Lable,wd.StImage1CameraGrid,wd.StImage2CameraGrid`;
                        let join = ` inner join Master_ShelfTalkerDefinition wd on w.ST_DEFINITION_ID=wd.StDefinitionId `;
                        let q = ` Select ${selectlist} from ${AppTables.ST_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  `;

                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { stHeaderId, StDefinitionId, ShelfTalkerId, StName, StTable, StField, StValue, ChildName, StElementStockRequired, StElementCheckAssortment, NoOfSplit, IsPresent, StNotExistCamera, StNAImage, StExistReasonEnable, StNotExistReasonEnable, ReasonId, Reason, StImage1, StImage2, Remark } = data;
                                    let obj = {};

                                    let isStockReq = (StElementStockRequired == 'true' || StElementStockRequired == 1) ? 1 : 0;
                                    let isCheckAssrt = (StElementCheckAssortment == 'true' || StElementCheckAssortment == 1) ? 1 : 0;
                                    let isNaCamAvl = (StNotExistCamera == 'true' || StNotExistCamera == 1) ? 1 : 0;
                                    let isReasonEnable = (StExistReasonEnable == 'true' || StExistReasonEnable == 1) ? 1 : 0;
                                    let isNAReasonEnable = (StNotExistReasonEnable == 'true' || StNotExistReasonEnable == 1) ? 1 : 0;
                                    let isImage1 = (StImage1 == 'true' || StImage1 == 1) ? 1 : 0;
                                    let isImage2 = (StImage2 == 'true' || StImage2 == 1) ? 1 : 0;


                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Store_Id'] = StoreId;
                                    obj['StDefinitionId'] = StDefinitionId;
                                    obj['ShelfTalkerId'] = ShelfTalkerId;
                                    obj['StTable'] = StTable;
                                    obj['StField'] = StField;
                                    obj['StValue'] = StValue;
                                    obj['ChildName'] = ChildName;
                                    obj['IsPresent'] = IsPresent;
                                    obj['StNotExistImage'] = isNaCamAvl == 1 ? StNAImage : '';
                                    obj['ReasonId'] = ReasonId;
                                    obj['Reason'] = Reason;
                                    obj['Remark'] = Remark != null ? Remark : '';



                                    if (isNaCamAvl == 1 && StNAImage != '') {
                                        let imgPath = common_ImagePath + StNAImage;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: StNAImage,
                                            filetype: 'image',
                                            folderName: 'ShelfTalkerImages',
                                        }
                                        allKPIfiles.push(file);
                                    }


                                    if (IsPresent == 1 && parseInt(NoOfSplit) > 0) {
                                        console.log('add split windows')


                                        async function getWindowSplits() {
                                            let q2 = `select * from ${AppTables.ST_IMAGES} where ST_HEADER_ID='${stHeaderId}' and  STORE_ID='${StoreId}' `;

                                            let allWindowSplitImages = [];
                                            return new Promise((resolve, reject) => {
                                                db.transaction(async function (txn) {

                                                    txn.executeSql(q2, [], async function (txn2, txnres3) {

                                                        if (txnres3.rows.length > 0) {
                                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                                let splitItem = txnres3.rows.item(j);
                                                                let { IMAGE1, IMAGE2 } = splitItem
                                                                let obj1 = { 'Image1': (isImage1 == 1 && IMAGE1 != null ? IMAGE1 : ''), 'Image2': (isImage2 == 1 && IMAGE2 != null ? IMAGE2 : '') };
                                                                obj1['StDefinitionId'] = StDefinitionId
                                                                obj1['ShelfTalkerId'] = ShelfTalkerId
                                                                obj1['MID'] = MID;

                                                                allWindowSplitImages.push(obj1);
                                                                if (isImage1 == 1 && IMAGE1 != null && IMAGE1 != '') {
                                                                    let imgPath = common_ImagePath + IMAGE1;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: IMAGE1,
                                                                        filetype: 'image',
                                                                        folderName: 'ShelfTalkerImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }
                                                                if (isImage2 == 1 && IMAGE2 != null && IMAGE2 != '') {
                                                                    let imgPath = common_ImagePath + IMAGE2;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: IMAGE2,
                                                                        filetype: 'image',
                                                                        folderName: 'ShelfTalkerImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }

                                                                if (j == txnres3.rows.length - 1) {
                                                                    console.log('all images added')
                                                                    resolve(allWindowSplitImages);

                                                                }
                                                            }
                                                        }
                                                        else {
                                                            resolve(allWindowSplitImages);
                                                        }

                                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                                });
                                            });
                                        }

                                        obj['StSplitImages'] = await getWindowSplits();
                                    }

                                    if (IsPresent == 1) {

                                        async function getWindowQA() {

                                            let selectlist_q1 = `DISTINCT  q.QUESTION_ID as StQuestionId,q.QUESTION_CODE as StQuestionCode,wq.StQuestionName,wq.QuestionType,wq.StqShowCamera,wq.StqCameraMandatory,wq.StqLengthValidationRequired,wq.StqMinimumChar,wq.StqMaximumChar,wq.StqDecimalPoint,wq.StqDateRangeMin,wq.StqDateRangeMax,wq.StqVoiceLengthInMinutes,wq.StqDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as StaShowCamera,q.IMAGE1 as Image1   `;
                                            let join_q2 = ` inner join Mapping_ShelfTalkerQuestion mq on mq.StQuestionId=wq.StQuestionId `;
                                            let join_q1 = ` inner join Master_ShelfTalkerQuestion wq on wq.StQuestionId=q.QUESTION_ID `;
                                            let q3 = `select ${selectlist_q1} from ${AppTables.ST_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.ST_DEFINITION_ID='${StDefinitionId}' and q.SHELFTALKER_ID='${ShelfTalkerId}' order by wq.StQuestionSequence  `;

                                            let allQAs = [];
                                            return new Promise((resolve, reject) => {
                                                db.transaction(async function (txn) {
                                                    txn.executeSql(q3, [], async function (txn2, txnres3) {

                                                        if (txnres3.rows.length > 0) {
                                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                                let QAData = txnres3.rows.item(j);
                                                                let { StQuestionId, AnswerId, Answer, StaShowCamera, Image1 } = QAData
                                                                let showImage1 = (StaShowCamera == 'true' || StaShowCamera == 1) ? 1 : 0;
                                                                let obj1 = {};
                                                                obj1['MID'] = MID;
                                                                obj1['StDefinitionId'] = StDefinitionId
                                                                obj1['ShelfTalkerId'] = ShelfTalkerId
                                                                obj1['StQuestionId'] = StQuestionId
                                                                obj1['AnswerId'] = AnswerId
                                                                obj1['Answer'] = Answer
                                                                obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                                allQAs.push(obj1);

                                                                if (showImage1 == 1 && Image1 != null && Image1 != '') {
                                                                    let imgPath = common_ImagePath + Image1;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: Image1,
                                                                        filetype: 'image',
                                                                        folderName: 'ShelfTalkerImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }
                                                                if (j == txnres3.rows.length - 1) {
                                                                    resolve(allQAs);
                                                                }
                                                            }
                                                        }
                                                        else {
                                                            resolve(allQAs);
                                                        }

                                                    }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                                });
                                            });
                                        }

                                        obj['QuestionAnswers'] = await getWindowQA();

                                        if (isStockReq == 1) {
                                            async function getWindowStock() {
                                                return new Promise((resolve, reject) => {
                                                    let allStock = [];
                                                    let join_s1 = ''
                                                    if (isCheckAssrt == 1) {
                                                        join_s1 = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.ST_STOCK_VALUE`;
                                                    }
                                                    let selectlist_s1 = ` Distinct s.ST_STOCK_DEFINITION_ID as StStockDefinitionId, s.ST_DEFINITION_ID as StDefinitionId,s.ST_STOCK_TABLE as StStockTable,s.ST_STOCK_FIELD as StStockField,s.ST_STOCK_VALUE as StStockValue,s.ST_STOCK_MBQ as StStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock,s.IS_PROMO_PRESENT as isPromoPresent`;
                                                    let q4 = `select ${selectlist_s1} from  ${AppTables.ST_STOCK_DATA} s ${join_s1} where s.ST_DEFINITION_ID='${StDefinitionId}' and s.STORE_ID='${StoreId}'  `;
                                                    if (isCheckAssrt) {
                                                        q4 += ` and a.StoreId='${StoreId}' `;
                                                    }
                                                    q4 += ` order by s.PRODUCT_NAME `;


                                                    db.transaction(async function (txn) {

                                                        txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                            if (txnres3.rows.length > 0) {
                                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                                    let SData = txnres3.rows.item(j);
                                                                    let { StStockDefinitionId, StStockValue, Stock, isPromoPresent } = SData

                                                                    let obj1 = {};
                                                                    obj1['MID'] = MID;
                                                                    obj1['StDefinitionId'] = StDefinitionId
                                                                    obj1['ShelfTalkerId'] = ShelfTalkerId
                                                                    obj1['StStockDefinitionId'] = StStockDefinitionId
                                                                    obj1['StStockValue'] = StStockValue
                                                                    obj1['Stock'] = Stock != '' && Stock != null && Stock != "null" && Stock != "undefined" ? Stock : 0;
                                                                    obj1['isPromoPresent'] = isPromoPresent

                                                                    allStock.push(obj1);
                                                                    if (j == txnres3.rows.length - 1) {
                                                                        resolve(allStock);
                                                                    }
                                                                }
                                                            }
                                                            else {
                                                                resolve(allStock);
                                                            }

                                                        }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                                    });
                                                });
                                            }
                                            obj['StockData'] = await getWindowStock();
                                        }
                                        else {
                                            obj['StockData'] = [];
                                        }
                                    }
                                    else {
                                        obj['StSplitImages'] = [];
                                        obj['QuestionAnswers'] = []
                                        obj['StockData'] = [];

                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'ShelfTalker';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;



                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }
        case 'PROMOTIONONEAPP':
            {
                // PromotionOneApp
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let txn1 = txn;
                        let selectlist = ` Distinct w.STORE_ID as StoreId,w.PROMO_HEADER_ID as PromoHeaderId,wd.PromoDefinitionId,wd.PromoId,wd.PromoName,wd.PromoTable,wd.PromoField,wd.PromoValue,wd.ChildName,wd.PromoRefImage,wd.PromoElementCheckAssortment,wd.PromoElementStockRequired,w.IS_PRESENT as IsPresent,wd.PromoNotExistCamera,w.PROMO_NA_IMAGE as PromoNAImage,wd.PromoExistReasonEnable,wd.PromoNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.PromoImage1,wd.PromoImage2,wd.PromoImage1Lable,wd.PromoImage2Lable,wd.PromoImage1CameraGrid,wd.PromoImage2CameraGrid,wd.StockQtyRequired,w.REASON_REMARK`;
                        let join = ` inner join Master_PromotionDefinition wd on w.PROMO_DEFINITION_ID=wd.PromoDefinitionId `;
                        let q = ` Select ${selectlist} from ${AppTables.PROMO_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  `;

                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { PromoHeaderId, PromoDefinitionId, PromoId, PromoName, PromoTable, PromoField, PromoValue, ChildName, PromoElementStockRequired, PromoElementCheckAssortment, NoOfSplit, IsPresent, PromoNotExistCamera, PromoNAImage, PromoExistReasonEnable, PromoNotExistReasonEnable, ReasonId, Reason, PromoImage1, PromoImage2, Remark, PromoImage1Lable, PromoImage2Lable, REASON_REMARK } = data;
                                    let obj = {};

                                    let isStockReq = (PromoElementStockRequired == 'true' || PromoElementStockRequired == 1) ? 1 : 0;
                                    let isCheckAssrt = (PromoElementCheckAssortment == 'true' || PromoElementCheckAssortment == 1) ? 1 : 0;
                                    let isNaCamAvl = (PromoNotExistCamera == 'true' || PromoNotExistCamera == 1) ? 1 : 0;
                                    let isReasonEnable = (PromoExistReasonEnable == 'true' || PromoExistReasonEnable == 1) ? 1 : 0;
                                    let isNAReasonEnable = (PromoNotExistReasonEnable == 'true' || PromoNotExistReasonEnable == 1) ? 1 : 0;
                                    let isImage1 = (PromoImage1 == 'true' || PromoImage1 == 1) ? 1 : 0;
                                    let isImage2 = (PromoImage2 == 'true' || PromoImage2 == 1) ? 1 : 0;


                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Store_Id'] = StoreId;
                                    obj['PromoDefinitionId'] = PromoDefinitionId;
                                    obj['PromoId'] = PromoId;
                                    obj['PromoTable'] = PromoTable;
                                    obj['PromoField'] = PromoField;
                                    obj['PromoValue'] = PromoValue;
                                    obj['ChildName'] = ChildName;
                                    obj['IsPresent'] = IsPresent;
                                    obj['PromoNotExistImage'] = isNaCamAvl == 1 ? PromoNAImage : '';
                                    obj['ReasonId'] = ReasonId;
                                    obj['Reason'] = Reason;
                                    obj['Remark'] = Remark != null ? Remark : '';
                                    obj['ReasonRemark'] = REASON_REMARK;

                                    if (isNaCamAvl == 1 && PromoNAImage != '') {
                                        let imgPath = common_ImagePath + PromoNAImage;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: PromoNAImage,
                                            filetype: 'image',
                                            folderName: 'PromotionImages',
                                        }
                                        allKPIfiles.push(file);
                                    }


                                    if (IsPresent == 1 && parseInt(NoOfSplit) > 0) {
                                        console.log('add split windows')


                                        async function getWindowSplits() {
                                            let q2 = `select * from ${AppTables.PROMO_IMAGES} where PROMO_HEADER_ID='${PromoHeaderId}' and  STORE_ID='${StoreId}' `;

                                            let allWindowSplitImages = [];
                                            return new Promise((resolve, reject) => {
                                                db.transaction(async function (txn) {

                                                    txn.executeSql(q2, [], async function (txn2, txnres3) {

                                                        if (txnres3.rows.length > 0) {
                                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                                let splitItem = txnres3.rows.item(j);
                                                                let { IMAGE1, IMAGE2 } = splitItem
                                                                let obj1 = { 'Image1': (isImage1 == 1 && IMAGE1 != null && IMAGE1 != '' && IMAGE1 != 'undefined' ? IMAGE1 : ''), 'Image2': (isImage2 == 1 && IMAGE2 != null && IMAGE2 != '' && IMAGE2 != 'undefined' ? IMAGE2 : '') };
                                                                obj1['PromoDefinitionId'] = PromoDefinitionId
                                                                obj1['PromoId'] = PromoId
                                                                obj1['MID'] = MID;
                                                                // obj1['PromoImage1Lable']=PromoImage1Lable;
                                                                // obj1['PromoImage2Lable']=PromoImage2Lable;


                                                                allWindowSplitImages.push(obj1);
                                                                if (isImage1 == 1 && IMAGE1 != null && IMAGE1 != '' && IMAGE1 != 'undefined') {
                                                                    let imgPath = common_ImagePath + IMAGE1;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: IMAGE1,
                                                                        filetype: 'image',
                                                                        folderName: 'PromotionImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }
                                                                if (isImage2 == 1 && IMAGE2 != null && IMAGE2 != '' && IMAGE2 != 'undefined') {
                                                                    let imgPath = common_ImagePath + IMAGE2;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: IMAGE2,
                                                                        filetype: 'image',
                                                                        folderName: 'PromotionImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }

                                                                if (j == txnres3.rows.length - 1) {
                                                                    console.log('all images added')
                                                                    resolve(allWindowSplitImages);

                                                                }
                                                            }
                                                        }
                                                        else {
                                                            resolve(allWindowSplitImages);
                                                        }

                                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                                });
                                            });
                                        }

                                        obj['PromoSplitImages'] = await getWindowSplits();
                                    }

                                    if (IsPresent == 1) {

                                        async function getWindowQA() {

                                            let selectlist_q1 = ` DISTINCT  q.QUESTION_ID as PromoQuestionId,q.IS_DISABLED,q.QUESTION_CODE as PromoQuestionCode,wq.PromoQuestionName,wq.QuestionType,wq.PromoqShowCamera,wq.PromoqCameraMandatory,wq.PromoqLengthValidationRequired,wq.PromoqMinimumChar,wq.PromoqMaximumChar,wq.PromoqDecimalPoint,wq.PromoqDateRangeMin,wq.PromoqDateRangeMax,wq.PromoqVoiceLengthInMinutes,wq.PromoqDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as PromoaShowCamera,q.IMAGE1 as Image1  `;
                                            let join_q2 = ` inner join Mapping_PromotionQuestion mq on mq.PromoQuestionId=wq.PromoQuestionId `;
                                            let join_q1 = ` inner join Master_PromotionQuestion wq on wq.PromoQuestionId=q.QUESTION_ID `;
                                            let q3 = `select ${selectlist_q1} from ${AppTables.PROMO_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.PROMO_DEFINITION_ID='${PromoDefinitionId}' and q.PROMO_ID='${PromoId}' order by wq.PromoQuestionSequence  `;

                                            let allQAs = [];
                                            return new Promise((resolve, reject) => {
                                                db.transaction(async function (txn) {
                                                    txn.executeSql(q3, [], async function (txn2, txnres3) {
                                                        console.log('getWindowQA PROMOoneapp:', txnres3.rows.length);
                                                        if (txnres3.rows.length > 0) {
                                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                                let QAData = txnres3.rows.item(j);
                                                                let { PromoQuestionId, IS_DISABLED, AnswerId, Answer, PromoaShowCamera, Image1 } = QAData
                                                                let showImage1 = (PromoaShowCamera == 'true' || PromoaShowCamera == 1) ? 1 : 0;
                                                                let obj1 = {};
                                                                obj1['MID'] = MID;
                                                                obj1['PromoDefinitionId'] = PromoDefinitionId;
                                                                obj1['PromoId'] = PromoId;
                                                                obj1['PromoQuestionId'] = PromoQuestionId
                                                                obj1['AnswerId'] = AnswerId
                                                                obj1['Answer'] = Answer
                                                                obj1['Image1'] = (showImage1 == 1 && Image1 != null && Image1 != '' && Image1 != 'undefined' ? Image1 : '')

                                                                console.log("IS_DISABLED-----", IS_DISABLED, IS_DISABLED == "0")
                                                                if (IS_DISABLED == "0") {
                                                                    allQAs.push(obj1);
                                                                }
                                                                if (showImage1 == 1 && Image1 != null && Image1 != '' && Image1 != 'undefined') {
                                                                    let imgPath = common_ImagePath + Image1;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: Image1,
                                                                        filetype: 'image',
                                                                        folderName: 'PromotionImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }
                                                                if (j == txnres3.rows.length - 1) {
                                                                    resolve(allQAs);
                                                                }
                                                            }
                                                        }
                                                        else {
                                                            resolve(allQAs);
                                                        }

                                                    }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                                });
                                            });
                                        }

                                        obj['QuestionAnswers'] = await getWindowQA();

                                        if (isStockReq == 1) {
                                            async function getWindowStock() {
                                                return new Promise((resolve, reject) => {
                                                    let allStock = [];
                                                    let join_s1 = ''
                                                    if (isCheckAssrt == 1) {
                                                        join_s1 = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.PROMO_STOCK_VALUE`;
                                                    }
                                                    let selectlist_s1 = ` Distinct s.PROMO_STOCK_DEFINITION_ID as PromoStockDefinitionId, s.PROMO_DEFINITION_ID as PromoDefinitionId,s.PROMO_STOCK_TABLE as PromoStockTable,s.PROMO_STOCK_FIELD as PromoStockField,s.PROMO_STOCK_VALUE as PromoStockValue,s.PROMO_STOCK_MBQ as PromoStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock,s.IS_PROMO_PRESENT as isPromoPresent `;
                                                    let q4 = `select ${selectlist_s1} from  ${AppTables.PROMO_STOCK_DATA} s ${join_s1} where s.PROMO_DEFINITION_ID='${PromoDefinitionId}' and s.STORE_ID='${StoreId}'  `;
                                                    if (isCheckAssrt) {
                                                        q4 += ` and a.StoreId='${StoreId}' `;
                                                    }
                                                    q4 += ` order by s.PRODUCT_NAME `;


                                                    db.transaction(async function (txn) {

                                                        txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                            if (txnres3.rows.length > 0) {
                                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                                    let SData = txnres3.rows.item(j);
                                                                    let { PromoStockDefinitionId, PromoStockTable, PromoStockField, PromoStockValue, PromoStockMBQ, ProductName, Stock, isPromoPresent } = SData

                                                                    let obj1 = {};
                                                                    obj1['MID'] = MID;
                                                                    obj1['PromoDefinitionId'] = PromoDefinitionId;
                                                                    obj1['PromoId'] = PromoId;
                                                                    obj1['PromoStockDefinitionId'] = PromoStockDefinitionId
                                                                    obj1['PromoStockTable'] = PromoStockTable
                                                                    obj1['PromoStockField'] = PromoStockField
                                                                    obj1['PromoStockValue'] = PromoStockValue
                                                                    obj1['PromoStockMBQ'] = PromoStockMBQ
                                                                    obj1['ProductName'] = ProductName
                                                                    obj1['Stock'] = Stock != '' && Stock != null && Stock != "null" && Stock != "undefined" ? Stock : 0;
                                                                    obj1['isPromoPresent'] = isPromoPresent

                                                                    allStock.push(obj1);
                                                                    if (j == txnres3.rows.length - 1) {
                                                                        resolve(allStock);
                                                                    }
                                                                }
                                                            }
                                                            else {
                                                                resolve(allStock);
                                                            }

                                                        }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                                    });
                                                });
                                            }
                                            obj['StockData'] = await getWindowStock();
                                        }
                                        else {
                                            obj['StockData'] = [];
                                        }
                                    }
                                    else {
                                        obj['PromoSplitImages'] = [];
                                        obj['QuestionAnswers'] = []
                                        obj['StockData'] = [];

                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'PromotionOneApp';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;


                                // console.log('PromotionOneApp:',postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }
        case 'PAIDVISIONEAPP':
            {
                var postData = await getDataFor_PVONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("PAIDVISIONEAPP postData:", postData)
                return postData;
            }
        case 'WAREHOUSEDEPLOY':
            {
                var postData = await getDataForWareHouseDeploy(storeData, KpiData, UserId, previousDayUpload);
                console.log("WAREHOUSEDEPLOY postData:", postData)
                return postData;
            }
        case 'WAREHOUSECAMPAIGN':
            {
                var postData = await getWAREHOUSECAMPAIGN(storeData, KpiData, UserId, previousDayUpload);
                console.log("WAREHOUSEDEPLOYCamp postData:", postData)
                return postData;
            }
        case 'TGBASEDONEAPP':
            {
                var postData = await getDataFor_VISICOLONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("TGBASEDONEAPP postData:", postData)
                return postData;
            }

        case 'PAIDVISIONEAPP_IR':
            {
                var postData = await getDataFor_PVONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("PAIDVISIONEAPP postData:", postData)
                return postData;
            }
        case 'PROGRAMONEAPP':
            {
                var postData = await getDataFor_PROG_ONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("PAIDVISIONEAPP postData:", postData)
                return postData;
            }
        case 'SOSONEAPP':
            {
                // SOSOneApp
                var postData = await getDataFor_SOSONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("SOSOneApp postData:", postData)
                return postData;
            }

        case 'SOSEYELEVELONEAPP':
            {
                // SOSOneApp
                var postData = await getDataFor_SOSEyeLevelONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("SOSOneApp postData:", postData)
                return postData;
            }
        case 'SOSONEAPP_IR':
            {
                // SOSOneApp
                var postData = await getDataFor_SOSONEAPP(storeData, KpiData, UserId, previousDayUpload);
                console.log("SOSOneApp IR postData:", postData)
                return postData;
            }
        case 'CATEXEONEAPP':
            {
                // CatExeOneApp
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let txn1 = txn;

                        let selectlist = ` Distinct w.STORE_ID as StoreId,w.CAT_HEADER_ID as CatHeaderId,wd.CategoryDefinitionId,wd.CategoryId,wd.CategoryName,wd.CategoryRefImage,wd.CategoryElementCheckAssortment,wd.CategoryElementStockRequired,w.IS_PRESENT as IsPresent,wd.CategoryNotExistCamera,w.CATE_NA_IMAGE as CatNAImage,wd.CategoryExistReasonEnable,wd.CategoryNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.CategoryImage1,wd.CategoryImage2,wd.CategoryImage1Lable,wd.CategoryImage2Lable,wd.CategoryImage1CameraGrid,wd.CategoryImage2CameraGrid,wd.StockQtyRequired`;
                        let join = ` inner join Master_CategoryDefinition wd on w.CAT_DEFINITION_ID=wd.CategoryDefinitionId `;
                        let q = ` Select ${selectlist} from ${AppTables.CATEXE_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}'  `;


                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { CatHeaderId, CategoryDefinitionId, CategoryId, CategoryName, CategoryElementStockRequired, CategoryElementCheckAssortment, NoOfSplit, IsPresent, CategoryNotExistCamera, CatNAImage, CategoryExistReasonEnable, CategoryNotExistReasonEnable, ReasonId, Reason, CategoryImage1, CategoryImage2, Remark } = data;
                                    let obj = {};

                                    let isStockReq = (CategoryElementStockRequired == 'true' || CategoryElementStockRequired == 1) ? 1 : 0;
                                    let isCheckAssrt = (CategoryElementCheckAssortment == 'true' || CategoryElementCheckAssortment == 1) ? 1 : 0;
                                    let isNaCamAvl = (CategoryNotExistCamera == 'true' || CategoryNotExistCamera == 1) ? 1 : 0;
                                    let isReasonEnable = (CategoryExistReasonEnable == 'true' || CategoryExistReasonEnable == 1) ? 1 : 0;
                                    let isNAReasonEnable = (CategoryNotExistReasonEnable == 'true' || CategoryNotExistReasonEnable == 1) ? 1 : 0;
                                    let isImage1 = (CategoryImage1 == 'true' || CategoryImage1 == 1) ? 1 : 0;
                                    let isImage2 = (CategoryImage2 == 'true' || CategoryImage2 == 1) ? 1 : 0;


                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Store_Id'] = StoreId;
                                    obj['CategoryDefinitionId'] = CategoryDefinitionId;
                                    obj['CategoryId'] = CategoryId;
                                    obj['IsPresent'] = IsPresent;
                                    obj['CategoryNotExistImage'] = isNaCamAvl == 1 ? CatNAImage : '';
                                    obj['ReasonId'] = ReasonId;
                                    obj['Reason'] = Reason;
                                    obj['Remark'] = Remark != null ? Remark : '';




                                    if (isNaCamAvl == 1 && CatNAImage != '') {
                                        let imgPath = common_ImagePath + CatNAImage;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: CatNAImage,
                                            filetype: 'image',
                                            folderName: 'CategoryExecutionImages',
                                        }
                                        allKPIfiles.push(file);
                                    }


                                    if (IsPresent == 1 && parseInt(NoOfSplit) > 0) {
                                        console.log('add cat exec')


                                        async function getWindowSplits() {
                                            let q2 = `select * from ${AppTables.CATEXE_IMAGES} where CAT_HEADER_ID='${CatHeaderId}' and  STORE_ID='${StoreId}' `;

                                            let allWindowSplitImages = [];
                                            return new Promise((resolve, reject) => {
                                                db.transaction(async function (txn) {

                                                    txn.executeSql(q2, [], async function (txn2, txnres3) {

                                                        if (txnres3.rows.length > 0) {
                                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                                let splitItem = txnres3.rows.item(j);
                                                                let { IMAGE1, IMAGE2 } = splitItem
                                                                let obj1 = { 'Image1': (isImage1 == 1 && IMAGE1 != null ? IMAGE1 : ''), 'Image2': (isImage2 == 1 && IMAGE2 != null ? IMAGE2 : '') };
                                                                obj1['CategoryDefinitionId'] = CategoryDefinitionId
                                                                obj1['CategoryId'] = CategoryId
                                                                obj1['MID'] = MID;

                                                                allWindowSplitImages.push(obj1);
                                                                if (isImage1 == 1 && IMAGE1 != null && IMAGE1 != '') {
                                                                    let imgPath = common_ImagePath + IMAGE1;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: IMAGE1,
                                                                        filetype: 'image',
                                                                        folderName: 'CategoryExecutionImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }
                                                                if (isImage2 == 1 && IMAGE2 != null && IMAGE2 != '') {
                                                                    let imgPath = common_ImagePath + IMAGE2;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: IMAGE2,
                                                                        filetype: 'image',
                                                                        folderName: 'CategoryExecutionImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }

                                                                if (j == txnres3.rows.length - 1) {
                                                                    console.log('all images added')
                                                                    resolve(allWindowSplitImages);
                                                                }
                                                            }
                                                        }
                                                        else {
                                                            resolve(allWindowSplitImages);
                                                        }

                                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                                });
                                            });
                                        }

                                        obj['CatExecSplitImages'] = await getWindowSplits();
                                    }

                                    if (IsPresent == 1) {

                                        async function getWindowQA() {


                                            let selectlist_q1 = ` DISTINCT  q.QUESTION_ID as CategoryQuestionId,q.QUESTION_CODE as CategoryQuestionCode,wq.CategoryQuestionName,wq.QuestionType,wq.CQShowCamera,wq.CQCameraMandatory,wq.CQLengthValidationRequired,wq.CQMinimumChar,wq.CQMaximumChar,wq.CQDecimalPoint,wq.CQDateRangeMin,wq.CQDateRangeMax,wq.CQVoiceLengthInMinutes,wq.CQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as CAShowCamera,q.IMAGE1 as Image1  `;
                                            let join_q2 = ` inner join Mapping_CategoryQuestion mq on mq.CategoryQuestionId=wq.CategoryQuestionId `;
                                            let join_q1 = ` inner join Master_CategoryQuestion wq on wq.CategoryQuestionId=q.QUESTION_ID `;
                                            let q3 = `select ${selectlist_q1} from ${AppTables.CATEXE_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.CAT_DEFINITION_ID='${CategoryDefinitionId}' and q.CAT_ID='${CategoryId}' order by wq.CategoryQuestionSequence  `;
                                            let allQAs = [];
                                            return new Promise((resolve, reject) => {
                                                db.transaction(async function (txn) {
                                                    txn.executeSql(q3, [], async function (txn2, txnres3) {
                                                        console.log('getWindowQA Catexec:', txnres3.rows.length);
                                                        if (txnres3.rows.length > 0) {
                                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                                let QAData = txnres3.rows.item(j);
                                                                let { CategoryQuestionId, AnswerId, Answer, CAShowCamera, Image1 } = QAData
                                                                let showImage1 = (CAShowCamera == 'true' || CAShowCamera == 1) ? 1 : 0;
                                                                let obj1 = {};
                                                                obj1['MID'] = MID;
                                                                obj1['CategoryDefinitionId'] = CategoryDefinitionId
                                                                obj1['CategoryId'] = CategoryId
                                                                obj1['CategoryQuestionId'] = CategoryQuestionId
                                                                obj1['AnswerId'] = AnswerId
                                                                obj1['Answer'] = Answer
                                                                obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                                allQAs.push(obj1);

                                                                if (showImage1 == 1 && Image1 != null && Image1 != '') {
                                                                    let imgPath = common_ImagePath + Image1;
                                                                    let file = {
                                                                        uri: imgPath,
                                                                        type: 'image/jpeg',
                                                                        name: Image1,
                                                                        filetype: 'image',
                                                                        folderName: 'CategoryExecutionImages',
                                                                    }
                                                                    allKPIfiles.push(file);
                                                                }
                                                                if (j == txnres3.rows.length - 1) {
                                                                    resolve(allQAs);
                                                                }
                                                            }
                                                        }
                                                        else {
                                                            resolve(allQAs);
                                                        }

                                                    }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                                });
                                            });
                                        }

                                        obj['QuestionAnswers'] = await getWindowQA();

                                        if (isStockReq == 1) {
                                            async function getWindowStock() {
                                                return new Promise((resolve, reject) => {
                                                    let allStock = [];

                                                    let join_s1 = '';
                                                    if (isCheckAssrt) {
                                                        join_s1 = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.CAT_STOCK_VALUE and a.StoreId='${StoreId}'`;
                                                    }
                                                    let selectlist_s1 = ` Distinct s.CAT_STOCK_DEFINITION_ID as CategoryStockDefinitionId, s.CAT_DEFINITION_ID as CategoryDefinitionId,s.CAT_STOCK_TABLE as CategoryStockTable,s.CAT_STOCK_FIELD as CategoryStockField,s.CAT_STOCK_VALUE as CategoryStockValue,s.CAT_STOCK_MBQ as CategoryStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock,s.IS_CAT_PRESENT as isCatPresent `;
                                                    let q4 = `select ${selectlist_s1} from  ${AppTables.CATEXE_STOCK_DATA} s ${join_s1} where s.CAT_DEFINITION_ID='${CategoryDefinitionId}' and s.STORE_ID='${StoreId}'  `;
                                                    q4 += ` order by s.PRODUCT_NAME `;


                                                    db.transaction(async function (txn) {

                                                        txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                            if (txnres3.rows.length > 0) {
                                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                                    let SData = txnres3.rows.item(j);
                                                                    let { CategoryStockDefinitionId, CategoryStockTable, CategoryStockField, CategoryStockValue, CategoryStockMBQ, ProductName, Stock, isCatPresent } = SData

                                                                    let obj1 = {};
                                                                    obj1['MID'] = MID;
                                                                    obj1['CategoryDefinitionId'] = CategoryDefinitionId
                                                                    obj1['CategoryId'] = CategoryId
                                                                    obj1['CategoryStockDefinitionId'] = CategoryStockDefinitionId
                                                                    obj1['CategoryStockTable'] = CategoryStockTable
                                                                    obj1['CategoryStockField'] = CategoryStockField
                                                                    obj1['CategoryStockValue'] = CategoryStockValue
                                                                    obj1['CategoryStockMBQ'] = CategoryStockMBQ
                                                                    obj1['ProductName'] = ProductName
                                                                    obj1['Stock'] = Stock != '' && Stock != null && Stock != "null" && Stock != "undefined" ? Stock : 0;
                                                                    obj1['isCatPresent'] = isCatPresent;

                                                                    allStock.push(obj1);
                                                                    if (j == txnres3.rows.length - 1) {
                                                                        resolve(allStock);
                                                                    }
                                                                }
                                                            }
                                                            else {
                                                                resolve(allStock);
                                                            }

                                                        }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                                    });
                                                });
                                            }
                                            obj['StockData'] = await getWindowStock();
                                        }
                                        else {
                                            obj['StockData'] = [];
                                        }


                                    }
                                    else {
                                        obj['CatExecSplitImages'] = [];
                                        obj['QuestionAnswers'] = [];
                                        obj['StockData'] = [];
                                    }

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'CatExecutionOneApp';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;


                                // console.log('CatExecOneApp:',postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }
        case 'StoreChecklist': {
            var postData = {};
            return new Promise((resolve, reject) => {
                db.transaction(async function (txn) {

                    let selectlist = ` DISTINCT T.MaxLength as MaxLength,T.MinLength as MinLength,T.CategoryId,T.Category,T.LengthValidation as LengthValidation,T.QuestionImageAllow as QuestionImageAllow,T.DateRange as DateRange,T.Question as Question,T.QuestionId as QuestionId,T.QuestionType as QuestionType,T.OTP as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled,T1.STORE_CHECKLIST_ONCE As StoreChecklistOnce`;
                    let join = ` INNER JOIN ${AppTables.STORE_CHECKLIST} T1 on T.QuestionId=T1.QUESTION_ID`;
                    let q2 = `Select ${selectlist} FROM Master_StoreChecklist T ${join} WHERE T1.STORE_ID='${StoreId}'  ` + (!previousDayUpload ? `  AND T1.VISIT_DATE= '${d2}' ` : '') + ` ORDER BY T.QuestionSequence `;

                    // console.log("checklistdataaa:",q2)

                    let allChilds = [], allKPIfiles = [];
                    await txn.executeSql(q2, [], async function (txn2, txnres2) {
                        if (txnres2.rows.length > 0) {

                            //console.log("checklistdataaa2:",txnres2.rows.length)

                            for (var i = 0; i < txnres2.rows.length; i++) {
                                let data = txnres2.rows.item(i);
                                let { CategoryId, Category, MaxLength, MinLength, QuestionImageAllow, DateRange, Question, QuestionId, QuestionType, OTP, Answer, AnswerId, ImageAllow1, Image1, ImageAllow2, Image2, MultiOptionsIds, isDisabled, StoreChecklistOnce } = data;
                                let obj = {};

                                let isQtnDisabled = isDisabled == 1 || isDisabled == '1' ? true : false;
                                if (!isQtnDisabled) {
                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['Store_Id'] = StoreId;
                                    obj['CategoryId'] = CategoryId;
                                    obj['QuestionId'] = QuestionId;
                                    obj['QuestionType'] = QuestionType;
                                    obj['Answer'] = Answer;
                                    obj['AnswerId'] = AnswerId != null && AnswerId != "null" && AnswerId != 'undefined' && AnswerId != '' ? AnswerId : 0;
                                    obj['MultiAnswerId'] = MultiOptionsIds != null && MultiOptionsIds != 'undefined' ? MultiOptionsIds : '';
                                    obj['AnswerImage1'] = Image1;
                                    obj['AnswerImage2'] = Image2;
                                    obj['StoreChecklistOnce'] = StoreChecklistOnce;

                                    if (((QuestionImageAllow == 1 || QuestionImageAllow == 'true') || (ImageAllow1 == 1 | ImageAllow1 == 'true')) && Image1 != '') {
                                        let imgPath = common_ImagePath + Image1;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: Image1,
                                            filetype: 'image',
                                            folderName: 'StoreChecklistImages',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    if ((ImageAllow2 == 1 || ImageAllow2 == 'true') && Image2 != '') {
                                        let imgPath = common_ImagePath + Image2;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: Image2,
                                            filetype: 'image',
                                            folderName: 'StoreChecklistImages',
                                        }
                                        allKPIfiles.push(file);
                                    }


                                    if (QuestionType == 'Audio' && Answer != '') {
                                        let filePath = common_ImagePath + 'Recordings/' + Answer;
                                        let file = {
                                            uri: filePath,
                                            type: (Platform.OS == 'ios' ? 'audio/m4a' : 'audio/mp3'),
                                            name: Answer,
                                            filetype: 'audio',
                                            folderName: 'StoreChecklistVoiceFiles',
                                        }
                                        allKPIfiles.push(file);
                                    }

                                    allChilds.push(obj);
                                }
                            }
                            postData['MID'] = MID;
                            postData['Keys'] = 'StoreChecklist';
                            postData['JsonData'] = JSON.stringify(allChilds);
                            postData['UserId'] = UserId;

                            console.log('Store Checklist data:', postData);
                            resolve({ 'Files': allKPIfiles, 'PostData': postData });
                        }
                        else {
                            resolve({ 'PostData': postData });
                        }
                    }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                });
            }).then((val) => {
                return val;
            }).catch((err) => {
                console.log(err);
                return postData;
            });
        }
        case 'StoreProfile': {
            var postData = {};
            return new Promise((resolve, reject) => {
                db.transaction(async function (txn) {

                    let q2 = `Select * FROM ${AppTables.STORE_PROFILE} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;

                    let allChilds = [], allKPIfiles = [];
                    await txn.executeSql(q2, [], async function (txn2, txnres2) {
                        if (txnres2.rows.length > 0) {

                            let data = txnres2.rows.item(0);
                            let { STORE_ID, STORE_NAME, ADDRESS, GSTNO, CONTACT_PERSON, PHONE, MOBILE, LOCATION, PINCODE, EMAIL, VISIT_DATE, ADDED_DATE } = data;
                            let obj = {};

                            obj['MID'] = MID;
                            obj['UserId'] = UserId;
                            obj['Store_Id'] = STORE_ID;
                            obj['StoreName'] = STORE_NAME;
                            obj['Address'] = ADDRESS;
                            obj['Location'] = LOCATION;
                            obj['Pincode'] = PINCODE;
                            obj['Email'] = EMAIL;
                            obj['GSTNo'] = GSTNO;
                            obj['ContactPerson'] = CONTACT_PERSON;
                            obj['Phone'] = PHONE;
                            obj['Mobile'] = MOBILE;

                            allChilds.push(obj);

                            postData['MID'] = MID;
                            postData['Keys'] = 'StoreProfile';
                            postData['JsonData'] = JSON.stringify(allChilds);
                            postData['UserId'] = UserId;

                            // console.log('Store Profile data:',postData);
                            resolve({ 'Files': allKPIfiles, 'PostData': postData });
                        }
                        else {
                            resolve({ 'PostData': postData });
                        }
                    }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                });
            }).then((val) => {
                return val;
            }).catch((err) => {
                console.log(err);
                return postData;
            });
        }

        //arman
        case 'StoreProfileKyc': {
            var postData = {};
            return new Promise((resolve, reject) => {
                db.transaction(async function (txn) {

                    let q2 = `Select * FROM ${AppTables.STORE_PROFILE_KYC} where STORE_ID='${StoreId}' and VISIT_DATE='${d2}'`;
                    console.log("checpq-->", q2)

                    let allChilds = [], allKPIfiles = [];
                    await txn.executeSql(q2, [], async function (txn2, txnres2) {
                        if (txnres2.rows.length > 0) {

                            let data = txnres2.rows.item(0);
                            let { STORE_ID, STORE_NAME, ADDRESS, GSTNO, IMAGE, CONTACT_PERSON, PHONE, MOBILE, LOCATION, PINCODE, EMAIL, VISIT_DATE, ADDED_DATE } = data;
                            let obj = {};

                            obj['MID'] = MID;
                            obj['UserId'] = UserId;
                            obj['Store_Id'] = STORE_ID;
                            obj['StoreName'] = STORE_NAME;
                            obj['GSTNo'] = GSTNO;
                            obj['GSTimage'] = IMAGE;


                            allChilds.push(obj);

                            postData['MID'] = MID;
                            postData['Keys'] = 'ShowCompactStoreProfile';
                            postData['JsonData'] = JSON.stringify(allChilds);
                            postData['UserId'] = UserId;

                            console.log('Store Profile kyc data:', postData);
                            resolve({ 'Files': allKPIfiles, 'PostData': postData });
                        }
                        else {
                            resolve({ 'PostData': postData });
                        }
                    }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                });
            }).then((val) => {
                return val;
            }).catch((err) => {
                console.log(err);
                return postData;
            });
        }

        case 'SAMPLINGONEAPP': {
            var postData = {};
            return new Promise((resolve, reject) => {
                db.transaction(async function (txn) {

                    let join = `INNER Join ${AppTables.SAMPLING_LIST} l on l.SAMPLING_DEFINITION_ID=T.SamplingDefinitionId and l.STORE_ID='${StoreId}' ` + (!previousDayUpload ? `  and l.VISIT_DATE='${d2}' ` : '') + ` `;
                    let q2 = `SELECT Distinct T.*,l.* FROM Master_SamplingDefinition T INNER JOIN Mapping_StoreSampling M ON T.SamplingDefinitionId=M.SamplingDefinitionId ${join} WHERE M.StoreId='${StoreId}'`;

                    let allChilds = [], allKPIfiles = [];
                    await txn.executeSql(q2, [], async function (txn2, txnres2) {
                        if (txnres2.rows.length > 0) {
                            let datagetCount = 0;
                            for (var i = 0; i < txnres2.rows.length; i++) {
                                let getinventoryDone = false, getStockDone = false, getSaleDone = false, getCCDone = false, getCustTrackDone = false;
                                let data = txnres2.rows.item(i);

                                let { STORE_ID, START_LUNCH, SAMPLING_PRESENT, KIOSKSETUP, END_LUNCH, START_IMAGE1, START_IMAGE2, END_IMAGE1, END_IMAGE2, START_IMG_TIME, END_IMG_TIME, SamplingDefinitionId, VISIT_DATE, ADDED_DATE, REASONID, REASON, CustomerTrackingQuestionCategoryId, InventoryQuestionCategoryId } = data;
                                let obj = {};

                                obj['MID'] = MID;
                                obj['UserId'] = UserId;
                                obj['Store_Id'] = STORE_ID;
                                obj['SamplingPresent'] = SAMPLING_PRESENT == 1 ? 1 : 0;
                                obj['SamplingDefinitionId'] = SamplingDefinitionId;
                                obj['KioskSetup'] = KIOSKSETUP == 1 ? 1 : 0;
                                obj['StartTimeImage1'] = START_IMAGE1 != '' && START_IMAGE1 != null && START_IMAGE1 != "null" && START_IMAGE1 != "undefined" && START_IMAGE1 != undefined ? START_IMAGE1 : '';
                                obj['StartTimeImage2'] = START_IMAGE2 != '' && START_IMAGE2 != null && START_IMAGE2 != 'null' && START_IMAGE2 != "undefined" && START_IMAGE2 != undefined ? START_IMAGE2 : '';
                                obj['StartTime'] = START_IMG_TIME;
                                obj['EndTime'] = END_IMG_TIME;
                                obj['EndTimeImage1'] = END_IMAGE1 != '' && END_IMAGE1 != undefined && END_IMAGE1 != "undefined" ? END_IMAGE1 : '';
                                obj['EndTimeImage2'] = END_IMAGE2 != '' && END_IMAGE2 != undefined && END_IMAGE2 != "undefined" ? END_IMAGE2 : '';
                                obj['StartLunchTime'] = START_LUNCH;
                                obj['EndLunchTime'] = END_LUNCH;
                                obj['ReasonId'] = REASONID;
                                obj['Reason'] = REASON;

                                async function getInventory() {
                                    let allStock = [];
                                    return new Promise((resolve, reject) => {

                                        let selectlist = ` DISTINCT T.SQMaximumChar as MaxLength,T.SQMinimumChar as MinLength,T.QuestionCategoryId as CategoryId,T.SQLengthValidationRequired as LengthValidation,T.SAShowCamera as QuestionImageAllow,"" as DateRange,T.SQDefaultQuestionEnable as QEnable,T.SamplingQuestionName as Question,T.SamplingQuestionId as QuestionId,T.QuestionType as QuestionType,"" as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.IMAGE_ALLOW1 as ImageAllow1,T1.IMAGE1 as Image1,T1.IMAGE_ALLOW2 as ImageAllow2,T1.IMAGE2 as Image2,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled `;
                                        let join2 = ` INNER JOIN ${AppTables.SAMPLING_INVENTORY} T1 on T.QuestionCategoryId=T1.CATEGORY_ID And T.SamplingQuestionId=T1.QUESTION_ID`;
                                        let join3 = ` INNER JOIN Mapping_SamplingQuestion T2 on T.SamplingQuestionId=T2.SamplingQuestionId And T2.SamplingDefinitionId='${SamplingDefinitionId}' `
                                        let q4 = `Select ${selectlist} FROM Master_SamplingQuestion T ${join2} ${join3} WHERE T1.STORE_ID='${StoreId}' ` + (!previousDayUpload ? `  AND T1.VISIT_DATE= '${d2}' ` : '') + ` AND T1.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' AND  T.QuestionCategoryId='${InventoryQuestionCategoryId}' `;
                                        q4 += ` ORDER BY T.SamplingQuestionSequence `;

                                        db.transaction(async function (txn) {

                                            txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);
                                                        let { CategoryId, QuestionId, AnswerId, Answer, } = SData;

                                                        let obj1 = {};
                                                        obj1['MID'] = MID;
                                                        obj1['UserId'] = UserId;
                                                        obj1['QuestionCategoryId'] = CategoryId
                                                        obj1['SamplingQuestionId'] = QuestionId
                                                        obj1['SamplingDefinitionId'] = SamplingDefinitionId;
                                                        obj1['AnswerId'] = AnswerId
                                                        obj1['Answer'] = Answer

                                                        allStock.push(obj1);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    }).then((val) => {
                                        getinventoryDone = true;
                                        return val;
                                    });
                                }

                                obj['Inventory'] = await getInventory();

                                async function getCust_Tracking() {
                                    let allStock = [];
                                    return new Promise((resolve, reject) => {
                                        // T.SAShowCamera as QuestionImageAllow
                                        // STORE_ID,VISIT_DATE,SAMPLING_DEFINITION_ID,CATEGORY_ID,QUESTION,QUESTION_ID,QUESTION_TYPE,ANSWER,ANSWER_ID,MULTI_OPTIONS_IDS,IS_DISABLED,CUSTID,ADDED_DATE)
                                        let selectlist = ` DISTINCT T.SQMaximumChar as MaxLength,T1.IMAGE1,T.SQMinimumChar as MinLength,T.QuestionCategoryId as CategoryId,T.SQLengthValidationRequired as LengthValidation,"" as DateRange,T.SQDefaultQuestionEnable as QEnable,T.SamplingQuestionName as Question,T.SamplingQuestionId as QuestionId,T.QuestionType as QuestionType,"" as OTP,T1.ANSWER As Answer, T1.ANSWER_ID as AnswerId,T1.MULTI_OPTIONS_IDS as multi_op_ids,T1.IS_DISABLED as isDisabled,T1.CUSTID `;
                                        let join2 = ` INNER JOIN ${AppTables.SAMPLING_CUST_TRACK} T1 on T.QuestionCategoryId=T1.CATEGORY_ID And T.SamplingQuestionId=T1.QUESTION_ID`;
                                        let join3 = ` INNER JOIN Mapping_SamplingQuestion T2 on T.SamplingQuestionId=T2.SamplingQuestionId And T2.SamplingDefinitionId='${SamplingDefinitionId}' `
                                        let q4 = `Select ${selectlist} FROM Master_SamplingQuestion T ${join2} ${join3} WHERE T1.STORE_ID='${StoreId}'  ` + (!previousDayUpload ? `  AND T1.VISIT_DATE= '${d2}' ` : '') + ` AND T1.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}'  AND  T.QuestionCategoryId='${CustomerTrackingQuestionCategoryId}' `;
                                        q4 += ` ORDER BY T.SamplingQuestionSequence `;

                                        console.log("q4 getCust_Tracking--", q4)

                                        db.transaction(async function (txn) {

                                            txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);
                                                        console.log("q4 getCust_Tracking--2", txnres3.rows.length)
                                                        let { CategoryId, QuestionId, AnswerId, Answer, CUSTID, IMAGE1 } = SData;

                                                        let obj1 = {};
                                                        obj1['MID'] = MID;
                                                        obj1['UserId'] = UserId;
                                                        obj1['QuestionCategoryId'] = CategoryId
                                                        obj1['SamplingQuestionId'] = QuestionId
                                                        obj1['SamplingDefinitionId'] = SamplingDefinitionId;
                                                        obj1['AnswerId'] = AnswerId
                                                        obj1['Answer'] = Answer
                                                        obj1['CustId'] = MID + "_" + CUSTID
                                                        obj1["IMAGE1"] = IMAGE1

                                                        // let bIndex=allStock.findIndex(i=>i.CUSTID==CUSTID);
                                                        // if(bIndex>=0){
                                                        //     let obj=allStock[bIndex] || {};
                                                        //     let QD1=obj.QuestionsData || [];
                                                        //     QD1.push(obj1);
                                                        //     obj['QuestionsData']= QD1;
                                                        //     allStock[bIndex]=obj;
                                                        // }
                                                        // else{
                                                        //     let obj={'CUSTID':CUSTID,'QuestionsData':[obj1]};
                                                        //     allStock.push(obj);
                                                        // }
                                                        allStock.push(obj1);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    }).then((val) => {
                                        getCustTrackDone = true;
                                        return val;
                                    });
                                }

                                obj['CustomerTracking'] = await getCust_Tracking();

                                async function getCustomerConversion() {
                                    let allStock = [];
                                    return new Promise((resolve, reject) => {

                                        let q2 = ` SELECT * FROM ${AppTables.CONTACT_CONVERSION} WHERE STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` and SAMPLING_DEFINITION_ID='${SamplingDefinitionId}'  and SCREEN_TYPE='SamplingContactConversion' `;

                                        db.transaction(async function (txn) {

                                            txn.executeSql(q2, [], async function (txn2, txnres3) {
                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);

                                                        let { STORE_ID, VISIT_DATE, TOTAL_CONTACT, CST_CONTACT, TOTAL_SAMPLED, ADDED_DATE } = SData;

                                                        let obj = {};
                                                        obj['MID'] = MID;
                                                        obj['User_Id'] = UserId;
                                                        obj['TotalContact'] = TOTAL_CONTACT != '' && TOTAL_CONTACT != null && TOTAL_CONTACT != "null" && TOTAL_CONTACT != "undefined" ? TOTAL_CONTACT : 0;
                                                        obj['CSTConverted'] = CST_CONTACT != '' && CST_CONTACT != null && CST_CONTACT != "null" && CST_CONTACT != "undefined" ? CST_CONTACT : 0;
                                                        obj['TotalSampled'] = TOTAL_SAMPLED != '' && TOTAL_SAMPLED != null && TOTAL_SAMPLED != "null" && TOTAL_SAMPLED != "undefined" ? TOTAL_SAMPLED : 0;
                                                        obj['SamplingDefinitionId'] = SamplingDefinitionId;

                                                        allStock.push(obj);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    }).then((val) => {
                                        getCCDone = true;
                                        return val;
                                    });
                                }

                                obj['CustomerConversion'] = await getCustomerConversion();

                                async function getSamplingStock() {
                                    let allStock = [];
                                    return new Promise((resolve, reject) => {

                                        let q2 = `SELECT Distinct c.SAMPLING_STOCK_VALUE as SamplingStockId, c.PRODUCT_NAME as ProductName,'' as MSL, c.SAMPLING_STOCK_DEFINITION_ID as SamplingStockDefinitionId, c.SAMPLING_DEFINITION_ID as SamplingDefinitionId, c.SAMPLING_STOCK_TABLE as SamplingStockTable, c.SAMPLING_STOCK_FIELD as SamplingStockField, c.SAMPLING_STOCK_MBQ as SamplingStockMBQ , STOCK from ${AppTables.SAMPLING_STOCK_DATA} c where c.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' AND c.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` AND c.VISIT_DATE='${d2}' ` : '') + ` `;

                                        db.transaction(async function (txn) {

                                            txn.executeSql(q2, [], async function (txn2, txnres3) {
                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);
                                                        let { SamplingStockDefinitionId, SamplingDefinitionId, SamplingStockTable, STOCK, SamplingStockField, ProductName } = SData

                                                        let obj1 = {};
                                                        obj1['MID'] = MID;
                                                        obj1['UserId'] = UserId;
                                                        obj1['SamplingDefinitionId'] = SamplingDefinitionId
                                                        obj1['SamplingStockDefinitionId'] = SamplingStockDefinitionId
                                                        obj1['SamplingStockTable'] = SamplingStockTable
                                                        obj1['SamplingStockField'] = SamplingStockField
                                                        obj1['ProductName'] = ProductName
                                                        obj1['Stock'] = STOCK != '' && STOCK != null && STOCK != "null" && STOCK != "undefined" ? STOCK : 0;

                                                        allStock.push(obj1);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    }).then((val) => {
                                        getStockDone = true;
                                        return val;
                                    });
                                }
                                obj['StockData'] = await getSamplingStock();

                                async function getSamplingSale() {
                                    return new Promise((resolve, reject) => {
                                        let allStock = [];
                                        // let q2=`SELECT c.SAMPLING_STOCK_VALUE as SamplingStockId, c.PRODUCT_NAME as ProductName,'' as MSL, c.SAMPLING_STOCK_DEFINITION_ID as SamplingStockDefinitionId, c.SAMPLING_DEFINITION_ID as SamplingDefinitionId, c.SAMPLING_STOCK_TABLE as SamplingStockTable, c.SAMPLING_STOCK_FIELD as SamplingStockField, c.SAMPLING_STOCK_MBQ as SamplingStockMBQ , STOCK, SALE from ${AppTables.SAMPLING_STOCK_DATA} c where c.SAMPLING_DEFINITION_ID='${SamplingData.SamplingDefinitionId}' AND c.STORE_ID='${StoreId}' AND c.VISIT_DATE='${d2}' } `;
                                        let q2 = `SELECT Distinct c.SAMPLING_STOCK_VALUE as SamplingStockId, c.PRODUCT_NAME as ProductName,'' as MSL, c.SAMPLING_STOCK_DEFINITION_ID as SamplingStockDefinitionId, c.SAMPLING_DEFINITION_ID as SamplingDefinitionId, c.SAMPLING_STOCK_TABLE as SamplingStockTable, c.SAMPLING_STOCK_FIELD as SamplingStockField, c.SAMPLING_STOCK_MBQ as SamplingStockMBQ , SALE from ${AppTables.SAMPLING_SALE_DATA} c where c.SAMPLING_DEFINITION_ID='${SamplingDefinitionId}' AND c.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` AND c.VISIT_DATE='${d2}' ` : '') + ` And c.SALE is not null and  c.SALE!="" and c.SALE>0 `;

                                        db.transaction(async function (txn) {

                                            txn.executeSql(q2, [], async function (txn2, txnres3) {

                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);
                                                        let { SamplingStockDefinitionId, SamplingDefinitionId, SamplingStockTable, SALE, SamplingStockField, ProductName } = SData

                                                        let obj1 = {};
                                                        obj1['MID'] = MID;
                                                        obj1['UserId'] = UserId;
                                                        obj1['SamplingDefinitionId'] = SamplingDefinitionId
                                                        obj1['SamplingStockDefinitionId'] = SamplingStockDefinitionId
                                                        obj1['SamplingStockTable'] = SamplingStockTable
                                                        obj1['SamplingStockField'] = SamplingStockField
                                                        obj1['ProductsName'] = ProductName
                                                        obj1['Sale'] = SALE != '' && SALE != null && SALE != "null" && SALE != "undefined" ? SALE : 0;


                                                        allStock.push(obj1);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    }).then((val) => {

                                        getSaleDone = true;
                                        return val;
                                    });
                                }
                                obj['SaleData'] = await getSamplingSale();



                                function addDataIfAllGet() {
                                    //Add data to arr When All data get completed for one sampling definition
                                    if (getinventoryDone && getCustTrackDone && getCCDone && getStockDone && getSaleDone) {
                                        allChilds.push(obj);
                                        datagetCount++;
                                        //check if this is done for all the samplings
                                        DoWhenAllDone();
                                    }
                                }

                                addDataIfAllGet();

                                function DoWhenAllDone() {
                                    //When All data get completed for all samplinig definitions
                                    if (datagetCount == txnres2.rows.length) {
                                        postData['MID'] = MID;
                                        postData['Keys'] = 'OneAppSampling';
                                        postData['JsonData'] = JSON.stringify(allChilds);
                                        postData['UserId'] = UserId;
                                        console.log("sampling postdata:", postData)
                                        resolve({ 'Files': allKPIfiles, 'PostData': postData });
                                    }
                                }

                            }


                        }
                        else {
                            resolve({ 'PostData': postData });
                        }
                    }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                });
            }).then((val) => {
                return val;
            }).catch((err) => {
                console.log(err);
                return postData;
            });
        }

        case 'ONEAPPMISSEDCALL':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.MISSED_CALL} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { STORE_ID, PRESENT, VISIT_DATE, UNIQUE_CODE, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['Store_Id'] = STORE_ID;
                                    obj['User_Id'] = UserId;
                                    obj['Unique_Code'] = UNIQUE_CODE;
                                    obj['Present'] = PRESENT;
                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'OneAppMissedCall';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                console.log('OneAppMissedCall postData', postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        case 'BREAKTIME':
            {
                // StoreImages
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.BREAKTIME} WHERE STORE_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    // BreakId,Break_Name,Minimum,Maximum
                                    let { STORE_ID, VISIT_DATE, BREAKNAME, BREAKID, STARTTIME, UNIQUEBREAKID, ENDTIME, MAXNUMBER, MINNUMBER, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['User_Id'] = UserId;
                                    obj['Store_Id'] = STORE_ID;
                                    obj['BreakId'] = BREAKID;
                                    // obj['Break_Name']=BREAKNAME;
                                    obj['StartTime'] = STARTTIME;
                                    obj['EndTime'] = ENDTIME;

                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'BreakData';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                // console.log('StoreImages postData',postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

        default: return false;
    }

}

export async function getStockDataChunks(storeData, UserId, previousDayUpload = false, CHUNK_SIZE) {
    try {
        // Helper: Execute SQL in promise form
        function executeSqlAsync(txn, query, params = []) {
            return new Promise((resolve, reject) => {
                txn.executeSql(
                    query,
                    params,
                    (tx, res) => resolve(res),
                    (tx, err) => {
                        console.error("❌ SQL Error:", err, "Query:", query);
                        reject(err);
                    }
                );
            });
        }

        let d1 = new Date();
        let d2 = moment(d1).format("MM/DD/YYYY");
        let { StoreId, MID } = storeData;
        let allImages = [], allChilds = [], allKPIfiles = [];
        // -------- Fetch STOCK2HDR_DATA --------
        const txnres2 = await new Promise((resolve, reject) => {
            db.transaction(async (txn) => {
                try {
                    let q2 = `SELECT * FROM ${AppTables.STOCK2HDR_DATA} WHERE STORE_ID='${StoreId}'` +
                        (!previousDayUpload ? ` AND VISIT_DATE='${d2}'` : "");
                    const res = await executeSqlAsync(txn, q2);
                    resolve(res);
                } catch (err) {
                    reject(err);
                }
            });
        });

        for (let i = 0; i < txnres2.rows.length; i++) {
            let data = txnres2.rows.item(i);
            if (data.IMAGE) {
                allImages.push({
                    MID,
                    UserId,
                    SubCategoryId: data.SUB_CATEGORY_ID,
                    SubCategoryImg: data.IMAGE != null && data.IMAGE !== "" ? data.IMAGE : "",
                });

                allKPIfiles.push({
                    uri: common_ImagePath + data.IMAGE,
                    type: "image/jpeg",
                    name: data.IMAGE != null && data.IMAGE !== "" ? data.IMAGE : "",
                    filetype: "image",
                    folderName: "StockSingleKPIImages",
                });
            }
        }

        // -------- Fetch STOCK2_DATA --------
        const txnres3 = await new Promise((resolve, reject) => {
            db.transaction(async (txn) => {
                try {
                    let join = `INNER JOIN Mapping_ProductAssortmentStorewise m 
                        ON p.PRODUCT_ID = m.ProductId AND m.StoreId='${StoreId}'`;
                    let q3 = `SELECT DISTINCT p.*, m.MBQ 
                        FROM ${AppTables.STOCK2_DATA} p ${join} 
                        WHERE p.STORE_ID='${StoreId}'` +
                        (!previousDayUpload ? ` AND p.VISIT_DATE='${d2}'` : "");
                    const res = await executeSqlAsync(txn, q3);
                    resolve(res);
                } catch (err) {
                    reject(err);
                }
            });
        });

        // Helper to fetch MFD stocks
        async function getMFDStockData(STOCK_UID, SubCategoryId, BrandId, ProductId) {
            return new Promise((resolve) => {
                db.transaction(async (txn) => {
                    let q = `SELECT * FROM ${AppTables.STOCK2_MFD_DATA} WHERE STOCK_UID='${STOCK_UID}'`;
                    let resMFD = await executeSqlAsync(txn, q);
                    let arr = [];
                    for (let i = 0; i < resMFD.rows.length; i++) {
                        let data = resMFD.rows.item(i);
                        arr.push({
                            MID,
                            SubCategoryId,
                            BrandId,
                            ProductId,
                            Mfd: data.MFD ? moment(data.MFD).format("MM/DD/YYYY") : "",
                            LotNo: data.LOT_NO,
                            Stock: data.STOCK != null && data.STOCK !== "" ? data.STOCK : 0,
                        });
                    }
                    resolve(arr);
                });
            });
        }

        for (let i = 0; i < txnres3.rows.length; i++) {
            let data2 = txnres3.rows.item(i);
            let mfdStocks = await getMFDStockData(
                data2.STOCK_UID,
                data2.SUB_CATEGORY_ID,
                data2.BRAND_ID,
                data2.PRODUCT_ID
            );

            allChilds.push({
                MID,
                UserId,
                Msl: data2.MSL == "true" || data2.MSL === true || data2.MSL === 1 ? 1 : 0,
                ArticleCode: data2.ARTICLE_CODE || "",
                SubCategoryId: data2.SUB_CATEGORY_ID,
                ProductId: data2.PRODUCT_ID,
                Stock: data2.STOCK != null && data2.STOCK !== "" ? data2.STOCK : 0,
                PackType: data2.PACKTYPE != null && data2.PACKTYPE != "" && data2.PACKTYPE != "null" && data2.PACKTYPE != "undefined" ? data2.PACKTYPE : '',
                BackRoomStock: data2.BACKROOM_STOCK != null && data2.BACKROOM_STOCK !== "" ? data2.BACKROOM_STOCK : 0,
                DamagedStock: data2.DAMAGED_STOCK != null && data2.DAMAGED_STOCK !== "" ? data2.DAMAGED_STOCK : 0,
                LostStock: data2.LOST_STOCK != null && data2.LOST_STOCK !== "" ? data2.LOST_STOCK : 0,
                ExpiryStock: data2.EXPIRY_STOCK != null && data2.EXPIRY_STOCK !== "" ? data2.EXPIRY_STOCK : 0,
                MFD_Stocks: mfdStocks,
                IsSKUPresent: data2.IS_SKU_STOCK_PRESENT,
                NrExpiry1_Stock: data2.NREXPIRY1_STOCK != null && data2.NREXPIRY1_STOCK !== "" ? data2.NREXPIRY1_STOCK : 0,
                NrExpiry2_Stock: data2.NREXPIRY2_STOCK != null && data2.NREXPIRY2_STOCK !== "" ? data2.NREXPIRY2_STOCK : 0,
                NrExpiry3_Stock: data2.NREXPIRY3_STOCK != null && data2.NREXPIRY3_STOCK !== "" ? data2.NREXPIRY3_STOCK : 0,
                OutOfStock: data2.OUT_OF_STOCK != null && data2.OUT_OF_STOCK !== "" ? data2.OUT_OF_STOCK : 0,
                LessThanMBQ: data2.LESS_THAN_MBQ != null && data2.LESS_THAN_MBQ !== "" ? data2.LESS_THAN_MBQ : 0,
                MBQ: data2.MBQ,
                PriceYesNo: data2.PriceYesNo,
            });
        }

        // -------- Chunk the results --------
        function chunkArray(arr, size) {
            let results = [];
            for (let i = 0; i < arr.length; i += size) {
                results.push(arr.slice(i, i + size));
            }
            return results;
        }

        let local_CHUNK_SIZE = CHUNK_SIZE;
        let allChildChunks = chunkArray(allChilds, local_CHUNK_SIZE);
        let chunkedPosts = allChildChunks.map((childGroup, index) => ({
            Files: index === 0 ? allKPIfiles : [],
            PostData: {
                MID,
                Keys: "StockSingleKPI",
                JsonData: JSON.stringify({
                    StockImgs: index === 0 ? allImages : [],
                    StockChilds: childGroup,
                }),
                UserId,
            },
        }));

        console.log("✅ Chunking complete. Total chunks:", chunkedPosts.length);
        return chunkedPosts;

    } catch (err) {
        console.error("🔥 Error in getStockDataChunks:", err);
        return [{ PostData: {} }];
    }
}




// helper: promisify executeSql
export function getDataFor_SOSONEAPP(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;
            let selectlist = ` DISTINCT p.SOS_HEADER_ID as SOSHeaderId,m.SOSHeaderTable,m.SOSHeaderField,p.SOS_HDR_VALUE as SOSHeaderValue,p.HEADER_NAME as HeaderName,m.SOSHeaderFacing,m.SOSHeaderFacingLable,m.SOSHeaderImage,m.SOSHeaderImageGrid,p.SOS_HDR_FACING as SOSHdrFacing `;
            let join = ` INNER JOIN Master_ShareOfShelfDefinition m on (p.SOS_HDR_VALUE=m.SOSHeaderValue and p.SOS_HDR_TABLE = m.SOSHeaderTable and p.SOS_HDR_FIELD=m.SOSHeaderField) `;
            let q = ` SELECT ${selectlist} FROM ${AppTables.SOS_HDR_DATA} p ${join} WHERE p.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and p.VISIT_DATE='${d2}' ` : '') + ` order by p.HEADER_NAME  `;

            console.log("sos_oneappQ", q)
            let allData = [], allKPIfiles = [];
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                if (txnres2.rows.length > 0) {
                    console.log("sos_oneapp_count",txnres2.rows.length)
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { SOSHeaderId, SOSHeaderTable, SOSHeaderField, SOSHeaderValue, HeaderName, SOSHeaderFacing, SOSHeaderFacingLable, SOSHeaderImage, SOSHeaderImageGrid, SOSHdrFacing } = data;
                        let obj = {};

                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['SOSHeaderTable'] = SOSHeaderTable;
                        obj['SOSHeaderField'] = SOSHeaderField;
                        obj['SOSHeaderValue'] = SOSHeaderValue;
                        obj['HeaderName'] = HeaderName;
                        obj['SOSHdrFacing'] = SOSHdrFacing != null && SOSHdrFacing != '' ? SOSHdrFacing : '0';

                        async function getWindowSplits() {
                            let q2 = ` SELECT IMAGE1,TYPE as Type,SOS_HDR_VALUE,SOS_CHILD_VALUE FROM ${AppTables.SOS_IMAGES} where SOS_HEADER_ID='${SOSHeaderId}' and STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;

                            let allWindowSplitImages = [];
                            return new Promise((resolve, reject) => {
                                db.transaction(async function (txn) {

                                    txn.executeSql(q2, [], async function (txn2, txnres3) {

                                        if (txnres3.rows.length > 0) {
                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                let splitItem = txnres3.rows.item(j);
                                                let { IMAGE1, Type, SOS_HDR_VALUE, SOS_CHILD_VALUE } = splitItem
                                                let obj1 = {};

                                                obj1['MID'] = MID;
                                                obj1['SOS_HDR_VALUE'] = SOS_HDR_VALUE
                                                obj1['SOS_CHILD_VALUE'] = SOS_CHILD_VALUE
                                                obj1['Type'] = Type
                                                obj1['Image1'] = (IMAGE1 != null && IMAGE1 != '' && IMAGE1 != 'undefined' && IMAGE1 != 'NA' ? IMAGE1 : '')

                                                allWindowSplitImages.push(obj1);
                                                if (IMAGE1 != null && IMAGE1 != '' && IMAGE1 != 'undefined' && IMAGE1 != 'NA') {
                                                    let imgPath = common_ImagePath + IMAGE1;
                                                    let file = {
                                                        uri: imgPath,
                                                        type: 'image/jpeg',
                                                        name: IMAGE1,
                                                        filetype: 'image',
                                                        folderName: 'SOSImages',
                                                    }
                                                    allKPIfiles.push(file);
                                                }

                                                if (j == txnres3.rows.length - 1) {
                                                    console.log('all images added')
                                                    resolve(allWindowSplitImages);
                                                }
                                            }
                                        }
                                        else {
                                            resolve(allWindowSplitImages);
                                        }

                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                });
                            });
                        }

                        obj['SOSImages'] = await getWindowSplits();


                        async function getChilds() {
                            return new Promise((resolve, reject) => {
                                let allStock = [];

                                let selectlist_c = ` Distinct m.SOSDefinitionId,m.SOSChildTable,m.SOSChildField,p.SOS_CHILD_VALUE as SOSChildValue,p.CHILD_NAME as ChildName,m.SOSChildTotalFacing,m.SOSChildSelfFacing,m.SOSChildTotalFacingLable,m.SOSChildSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,p.TOTAL_FACING as TotalFacing,p.SELF_FACING as SelfFacing`;
                                let join_s = ` INNER JOIN Master_ShareOfShelfDefinition m on (p.SOS_DEFINITION_ID=m.SOSDefinitionId and m.SOSChildTable=p.SOS_CHILD_TABLE and p.SOS_CHILD_FIELD=m.SOSChildField)  `;
                                let q4 = ` SELECT ${selectlist_c} FROM ${AppTables.SOS_CHILD_DATA} p ${join_s}  WHERE p.SOS_HDR_VALUE='${SOSHeaderValue}' and p.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and p.VISIT_DATE='${d2}' ` : '') + ` order by p.CHILD_NAME  `;

                                console.log("sos_oneappQ", q4)
                                db.transaction(async function (txn) {

                                    txn.executeSql(q4, [], async function (txn2, txnres3) {
                                        if (txnres3.rows.length > 0) {
                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                let SData = txnres3.rows.item(j);
                                                let { SOSDefinitionId, SOSChildTable, SOSChildField, SOSChildValue, ChildName, SOSChildTotalFacing, SOSChildSelfFacing, SOSChildTotalFacingLable, SOSChildSelfFacingLable, SOSChildImage, SOSChildImageCount, SOSChildImageGrid, TotalFacing, SelfFacing } = SData;

                                                let obj1 = {};
                                                obj1['MID'] = MID;
                                                obj1['SOSDefinitionId'] = SOSDefinitionId
                                                obj1['SOSHeaderValue'] = SOSHeaderValue
                                                obj1['SOSChildTable'] = SOSChildTable
                                                obj1['SOSChildField'] = SOSChildField
                                                obj1['SOSChildValue'] = SOSChildValue
                                                obj1['ChildName'] = ChildName
                                                obj1['TotalFacing'] = TotalFacing != null && TotalFacing != '' && TotalFacing != "null" && TotalFacing != "undefined" ? TotalFacing : '0';
                                                obj1['SelfFacing'] = SelfFacing != null && SelfFacing != '' && SelfFacing != "null" && SelfFacing != "undefined" ? SelfFacing : '0';

                                                allStock.push(obj1);
                                                if (j == txnres3.rows.length - 1) {
                                                    resolve(allStock);
                                                }
                                            }
                                        }
                                        else {
                                            resolve(allStock);
                                        }

                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                });
                            });
                        }
                        obj['SOSChilds'] = await getChilds();

                        //    allData.push(obj);

                        // sos question with stock

                        async function getChildsWindQS() {
                            return new Promise((resolve, reject) => {
                                let allStock = [];

                                let selectlist_c = ` Distinct m.SOSDefinitionId,m.SOSChildTable,p.SOS_CHILD_VALUE,m.SOSChildField,m.SOSChildTotalFacing,m.SOSChildSelfFacing,m.SOSChildTotalFacingLable,m.SOSChildSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,p.QUESTION_ID as questionId,p.IMAGE1 as Image1,p.QUESTION_CODE as questionCode,p.QUESTION_TYPE as questionType,p.ANSWER as answer,p.ANSWER_ID as answerId`;
                                let join_s = ` INNER JOIN Master_ShareOfShelfDefinition m on p.SOS_DEFINITION_ID=m.SOSDefinitionId `;
                                let q4 = ` SELECT ${selectlist_c} FROM ${AppTables.SOS_CHILD_QUES_DATA} p ${join_s}  WHERE p.SOS_HDR_VALUE='${SOSHeaderValue}' and p.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and p.VISIT_DATE='${d2}' ` : '') + ` order by p.QUESTION_ID  `;

                                db.transaction(async function (txn) {

                                    txn.executeSql(q4, [], async function (txn2, txnres3) {
                                        if (txnres3.rows.length > 0) {
                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                let SData = txnres3.rows.item(j);
                                                let { SOSDefinitionId, SOS_CHILD_VALUE, SOSChildTable, SOSChildField, SOSChildValue, SOSChildTotalFacing, SOSChildSelfFacing, SOSChildTotalFacingLable, SOSChildSelfFacingLable, SOSChildImage, SOSChildImageCount, SOSChildImageGrid, Image1, questionId, questionCode, questionType, answer, answerId } = SData;

                                                let obj1 = {};
                                                obj1['MID'] = MID;
                                                obj1['SOSDefinitionId'] = SOSDefinitionId
                                                obj1['SOSHeaderValue'] = SOSHeaderValue
                                                obj1['SOSQuestionId'] = questionId
                                                obj1['Answer'] = answer
                                                obj1['AnswerId'] = answerId
                                                obj1['Image1'] = Image1 != null && Image1 != '' && Image1 != 'undefined' && Image1 != 'NA' ? Image1 : ''
                                                obj1['SOSChildValue'] = SOS_CHILD_VALUE



                                                if (Image1 != null && Image1 != '' && Image1 != 'undefined' && Image1 != 'NA') {
                                                    let imgPath = common_ImagePath + Image1;
                                                    let file = {
                                                        uri: imgPath,
                                                        type: 'image/jpeg',
                                                        name: Image1,
                                                        filetype: 'image',
                                                        folderName: 'SOSImages',
                                                    }
                                                    allKPIfiles.push(file);
                                                }
                                                allStock.push(obj1);
                                                if (j == txnres3.rows.length - 1) {
                                                    resolve(allStock);
                                                }
                                            }
                                        }
                                        else {
                                            resolve(allStock);
                                        }

                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                });
                            });
                        }
                        obj['QuestionAnswers'] = await getChildsWindQS();

                        allData.push(obj);

                    }
                    postData['MID'] = MID;
                    postData['Keys'] = 'SOSOneApp';
                    postData['JsonData'] = JSON.stringify(allData);
                    postData['UserId'] = UserId;


                    // console.log('SOSOneApp:',postData);
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_SOSEyeLevelONEAPP(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;
            let selectlist = ` DISTINCT p.SOS_HEADER_ID as SOSHeaderId,m.SOSHeaderTable,m.SOSHeaderField,p.SOS_HDR_VALUE as SOSHeaderValue,p.HEADER_NAME as HeaderName,m.SOSHeaderEyeLevelFacing,m.SOSHeaderEyeLevelFacingLable, m.SOSHeaderNonEyeLevelFacing,m.SOSHeaderNonEyeLevelFacingLable,m.SOSHeaderImage,m.SOSHeaderImageCount,m.SOSHeaderImageGrid, p.EYE_LEVEL_HDR_FACING , p.EYE_LEVEL_HDR_FACING as SOSHdrEyeFacing, p.NONEYE_LEVEL_HDR_FACING as SOSHdrNonEyeFacing`;
            let join = ` INNER JOIN Master_ShareOfShelfEyeLevelDefinition m on p.SOS_HDR_VALUE=m.SOSHeaderValue `;
            let q = ` SELECT ${selectlist} FROM ${AppTables.EYE_LEVEL_HDR_DATA} p ${join} WHERE p.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and p.VISIT_DATE='${d2}' ` : '') + ` order by p.HEADER_NAME  `;

            let allData = [], allKPIfiles = [];
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { SOSHeaderId, SOSHeaderTable, SOSHdrEyeFacing, SOSHdrNonEyeFacing, SOSHeaderField, SOSHeaderValue, HeaderName, SOSHeaderFacing, SOSHeaderFacingLable, SOSHeaderImage, SOSHeaderImageCount, SOSHeaderImageGrid, SOSHdrFacing } = data;
                        let obj = {};

                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['SOSHeaderTable'] = SOSHeaderTable;
                        obj['SOSHeaderField'] = SOSHeaderField;
                        obj['SOSHeaderValue'] = SOSHeaderValue;
                        obj['HeaderName'] = HeaderName;
                        obj['SOSHdrEyeFacing'] = SOSHdrEyeFacing != null && SOSHdrEyeFacing != '' ? SOSHdrEyeFacing : '0';
                        obj['SOSHdrNonEyeFacing'] = SOSHdrNonEyeFacing != null && SOSHdrNonEyeFacing != '' ? SOSHdrNonEyeFacing : '0';

                        async function getWindowSplits() {
                            let q2 = ` SELECT Distinct IMAGE1,TYPE as Type,SOS_HDR_VALUE,SOS_CHILD_VALUE FROM ${AppTables.EYE_LEVEL_IMAGES} where SOS_HEADER_ID='${SOSHeaderId}' and STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;

                            let allWindowSplitImages = [];
                            return new Promise((resolve, reject) => {
                                db.transaction(async function (txn) {

                                    txn.executeSql(q2, [], async function (txn2, txnres3) {

                                        if (txnres3.rows.length > 0) {
                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                let splitItem = txnres3.rows.item(j);
                                                let { IMAGE1, Type, SOS_HDR_VALUE, SOS_CHILD_VALUE } = splitItem
                                                let obj1 = {};

                                                obj1['MID'] = MID;
                                                obj1['SOS_HDR_VALUE'] = SOS_HDR_VALUE
                                                obj1['SOS_CHILD_VALUE'] = SOS_CHILD_VALUE
                                                obj1['Type'] = Type
                                                obj1['Image1'] = (IMAGE1 != null ? IMAGE1 : '')

                                                allWindowSplitImages.push(obj1);
                                                if (IMAGE1 != null && IMAGE1 != '') {
                                                    let imgPath = common_ImagePath + IMAGE1;
                                                    let file = {
                                                        uri: imgPath,
                                                        type: 'image/jpeg',
                                                        name: IMAGE1,
                                                        filetype: 'image',
                                                        folderName: 'SOSImages',
                                                    }
                                                    allKPIfiles.push(file);
                                                }

                                                if (j == txnres3.rows.length - 1) {
                                                    console.log('all images added')
                                                    resolve(allWindowSplitImages);
                                                }
                                            }
                                        }
                                        else {
                                            resolve(allWindowSplitImages);
                                        }

                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                });
                            });
                        }

                        obj['SOSImages'] = await getWindowSplits();


                        async function getChilds() {
                            return new Promise((resolve, reject) => {
                                let allStock = [];
                                let selectlist_c = ` Distinct m.SOSDefinitionId,m.SOSChildTable,m.SOSChildField,m.SOSChildValue,m.ChildName,m.SOSChildEyeLevelTotalFacing,m.SOSChildNonEyeLevelTotalFacing,m.SOSChildNonEyeLevelSelfFacing,m.SOSChildEyeLevelSelfFacing,m.SOSHeaderNonEyeLevelFacingLable,m.SOSChildEyeLevelTotalFacingLable,m.SOSChildEyeLevelSelfFacingLable,m.SOSChildNonEyeLevelSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,p.TOTAL_EYE_FACING as TotalEyeLevelFacing, p.TOTAL_NONEYE_FACING as TotalNonEyeFacing ,p.SELF_EYE_FACING as SelfEyeFacing ,p.SELF_NONEYE_FACING as SelfNonEyeFacing`
                                //    let selectlist_c=` m.SOSDefinitionId,m.SOSChildTable,m.SOSChildField,m.SOS_CHILD_VALUE as SOSChildValue,m.CHILD_NAME as ChildName,m.SOSChildEyeLevelTotalFacing,m.SOSChildNonEyeLevelTotalFacing,m.SOSChildEyeLevelSelfFacing,m.SOSChildNonEyeLevelSelfFacing,m.SOSChildEyeLevelTotalFacingLable,m.SOSChildNonEyeLevelTotalFacingLable,m.SOSChildEyeLevelSelfFacingLable,m.SOSChildNonEyeLevelSelfFacingLable,m.SOSChildImage,m.SOSChildImageCount,m.SOSChildImageGrid,m.TOTAL_FACING as TotalFacing,m.SELF_FACING as SelfFacing`;
                                let join_s = ` INNER JOIN Master_ShareOfShelfEyeLevelDefinition m on p.SOS_DEFINITION_ID=m.SOSDefinitionId `;
                                let q4 = ` SELECT ${selectlist_c} FROM ${AppTables.EYE_LEVEL_CHILD_DATA} p ${join_s}  WHERE p.SOS_HDR_VALUE='${SOSHeaderValue}' and p.STORE_ID='${StoreId}' ` + (!previousDayUpload ? ` and p.VISIT_DATE='${d2}' ` : '') + ` order by p.CHILD_NAME  `;

                                db.transaction(async function (txn) {

                                    txn.executeSql(q4, [], async function (txn2, txnres3) {
                                        if (txnres3.rows.length > 0) {
                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                let SData = txnres3.rows.item(j);
                                                let { SOSDefinitionId, SOSChildTable, SelfNonEyeFacing, TotalNonEyeFacing, SOSChildField, SOSChildValue, ChildName, SelfEyeFacing, TotalEyeLevelFacing, SOSChildTotalFacing, SOSChildSelfFacing, SOSChildTotalFacingLable, SOSChildSelfFacingLable, SOSChildImage, SOSChildImageCount, SOSChildImageGrid, TotalFacing, SelfFacing } = SData;

                                                let obj1 = {};
                                                obj1['MID'] = MID;
                                                obj1['SOSDefinitionId'] = SOSDefinitionId
                                                obj1['SOSHeaderValue'] = SOSHeaderValue
                                                obj1['SOSChildTable'] = SOSChildTable
                                                obj1['SOSChildField'] = SOSChildField
                                                obj1['SOSChildValue'] = SOSChildValue
                                                obj1['ChildName'] = ChildName
                                                //    obj1['TotalFacing']=TotalFacing!=null && TotalFacing!='' && TotalFacing!="null" && TotalFacing!="undefined"?TotalFacing:'0';
                                                //    obj1['SelfFacing']=SelfFacing!=null && SelfFacing!='' && SelfFacing!="null" && SelfFacing!="undefined"?SelfFacing:'0';

                                                obj1['TotalNonEyeFacing'] = TotalNonEyeFacing != null && TotalNonEyeFacing != '' && TotalNonEyeFacing != "null" && TotalNonEyeFacing != "undefined" ? TotalNonEyeFacing : '0';
                                                obj1['SelfNonEyeFacing'] = SelfNonEyeFacing != null && SelfNonEyeFacing != '' && SelfNonEyeFacing != "null" && SelfNonEyeFacing != "undefined" ? SelfNonEyeFacing : '0';
                                                obj1['TotalEyeLevelFacing'] = TotalEyeLevelFacing != null && TotalEyeLevelFacing != '' && TotalEyeLevelFacing != "null" && TotalEyeLevelFacing != "undefined" ? TotalEyeLevelFacing : '0';
                                                obj1['SelfEyeFacing'] = SelfEyeFacing != null && SelfEyeFacing != '' && SelfEyeFacing != "null" && SelfEyeFacing != "undefined" ? SelfEyeFacing : '0';

                                                allStock.push(obj1);
                                                if (j == txnres3.rows.length - 1) {
                                                    resolve(allStock);
                                                }
                                            }
                                        }
                                        else {
                                            resolve(allStock);
                                        }

                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                });
                            });
                        }
                        obj['SOSChilds'] = await getChilds();

                        allData.push(obj);
                    }
                    postData['MID'] = MID;
                    postData['Keys'] = 'SosEyeLevelOneApp';
                    postData['JsonData'] = JSON.stringify(allData);
                    postData['UserId'] = UserId;


                    console.log('SosEyeLevelOneApp:', postData);
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_PVONEAPP(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;

            let selectlist = ` Distinct w.STORE_ID as StoreId,w.PVIS_HEADER_ID as PVisHeaderId,wd.VisibilityDefinitionId,wd.VisibilityId,wd.VisibilityName,wd.VisibilityTable,wd.VisibilityField,wd.VisibilityValue,wd.ChildName,wd.VisibilityRefImage,wd.VisibilityElementCheckAssortment,wd.VisibilityElementStockRequired,w.IS_PRESENT as IsPresent,wd.VisibilityNotExistCamera,w.PVIS_NA_IMAGE as PVisNAImage,wd.VisibilityExistReasonEnable,wd.VisibilityNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.VisibilityImage1,wd.VisibilityImage2,wd.VisibilityImage1Lable,wd.VisibilityImage2Lable,wd.VisibilityImage1CameraGrid,wd.VisibilityImage2CameraGrid,w.IS_STORE_SPECIFIC as isStoreSpecific,w.REASON_REMARK`;
            let join = ` inner join Master_VisibilityDefinition wd on w.PVIS_DEFINITION_ID=wd.VisibilityDefinitionId `;
            let q = ` Select ${selectlist} from ${AppTables.PAIDVIS_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}' and MENU_ID='${MenuId}' `;


            let allChilds = [], allKPIfiles = [], isSpecificKPI = false;
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                console.log('pv count:', MenuId, txnres2.rows.length)
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { PVisHeaderId, VisibilityDefinitionId, VisibilityId, VisibilityName, VisibilityTable, VisibilityField, VisibilityValue, ChildName, VisibilityElementStockRequired, VisibilityElementCheckAssortment, NoOfSplit, IsPresent, VisibilityNotExistCamera, PVisNAImage, VisibilityExistReasonEnable, VisibilityNotExistReasonEnable, ReasonId, Reason, VisibilityImage1, VisibilityImage2, Remark, VisibilityImage1Lable, VisibilityImage2Lable, isStoreSpecific, REASON_REMARK } = data;
                        let obj = {};

                        if (i == 0) {
                            isSpecificKPI = isStoreSpecific;
                        }
                        let isStockReq = (VisibilityElementStockRequired == 'true' || VisibilityElementStockRequired == 1) ? 1 : 0;
                        let isCheckAssrt = (VisibilityElementCheckAssortment == 'true' || VisibilityElementCheckAssortment == 1) ? 1 : 0;
                        let isNaCamAvl = (VisibilityNotExistCamera == 'true' || VisibilityNotExistCamera == 1) ? 1 : 0;
                        let isReasonEnable = (VisibilityExistReasonEnable == 'true' || VisibilityExistReasonEnable == 1) ? 1 : 0;
                        let isNAReasonEnable = (VisibilityNotExistReasonEnable == 'true' || VisibilityNotExistReasonEnable == 1) ? 1 : 0;
                        let isImage1 = (VisibilityImage1 == 'true' || VisibilityImage1 == 1) ? 1 : 0;
                        let isImage2 = (VisibilityImage2 == 'true' || VisibilityImage2 == 1) ? 1 : 0;


                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['MenuId'] = MenuId;
                        obj['VisibilityDefinitionId'] = VisibilityDefinitionId;
                        obj['VisibilityId'] = VisibilityId;
                        obj['VisibilityTable'] = VisibilityTable;
                        obj['VisibilityField'] = VisibilityField;
                        obj['VisibilityValue'] = VisibilityValue;
                        obj['ChildName'] = ChildName;
                        obj['IsPresent'] = IsPresent;
                        obj['VisibilityNotExistImage'] = isNaCamAvl == 1 ? PVisNAImage : '';
                        obj['ReasonId'] = ReasonId;
                        obj['Reason'] = Reason;
                        obj['Remark'] = Remark != null ? Remark : '';
                        obj['ReasonRemark'] = REASON_REMARK;

                        if (isNaCamAvl == 1 && PVisNAImage != '') {
                            let imgPath = common_ImagePath + PVisNAImage;
                            let file = {
                                uri: imgPath,
                                type: 'image/jpeg',
                                name: PVisNAImage,
                                filetype: 'image',
                                folderName: 'PaidVisibilityImages',
                            }
                            allKPIfiles.push(file);
                        }


                        if (IsPresent == 1 && parseInt(NoOfSplit) > 0) {
                            console.log('add paid vis ')


                            async function getWindowSplits() {
                                let q2 = `select * from ${AppTables.PAIDVIS_IMAGES} where PVIS_HEADER_ID='${PVisHeaderId}' and  STORE_ID='${StoreId}' `;

                                let allWindowSplitImages = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {

                                        txn.executeSql(q2, [], async function (txn2, txnres3) {

                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let splitItem = txnres3.rows.item(j);
                                                    let { IMAGE1, IMAGE2 } = splitItem
                                                    let obj1 = { 'Image1': (isImage1 == 1 && IMAGE1 != null ? IMAGE1 : ''), 'Image2': (isImage2 == 1 && IMAGE2 != null ? IMAGE2 : '') };
                                                    obj1['VisibilityDefinitionId'] = VisibilityDefinitionId
                                                    obj1['VisibilityId'] = VisibilityId
                                                    obj1['MID'] = MID;
                                                    // obj1['VisibilityImage1Lable']=VisibilityImage1Lable;
                                                    // obj1['VisibilityImage2Lable']=VisibilityImage2Lable;

                                                    allWindowSplitImages.push(obj1);
                                                    if (isImage1 == 1 && IMAGE1 != null && IMAGE1 != '') {
                                                        let imgPath = common_ImagePath + IMAGE1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: IMAGE1,
                                                            filetype: 'image',
                                                            folderName: 'PaidVisibilityImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }
                                                    if (isImage2 == 1 && IMAGE2 != null && IMAGE2 != '') {
                                                        let imgPath = common_ImagePath + IMAGE2;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: IMAGE2,
                                                            filetype: 'image',
                                                            folderName: 'PaidVisibilityImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }

                                                    if (j == txnres3.rows.length - 1) {
                                                        console.log('all images added')
                                                        resolve(allWindowSplitImages);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allWindowSplitImages);
                                            }

                                        }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                    });
                                });
                            }

                            obj['PaidVisSplitImages'] = await getWindowSplits();
                        }

                        if (IsPresent == 1) {

                            async function getWindowQA() {


                                let selectlist_q1 = ` DISTINCT  q.QUESTION_ID as VisibilityQuestionId,q.QUESTION_CODE as VisibilityQuestionCode,wq.VisibilityQuestionName,wq.QuestionType,wq.VQShowCamera,wq.VQCameraMandatory,wq.VQLengthValidationRequired,wq.VQMinimumChar,wq.VQMaximumChar,wq.VQDecimalPoint,wq.VQDateRangeMin,wq.VQDateRangeMax,wq.VQVoiceLengthInMinutes,wq.VQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as VAShowCamera,q.IMAGE1 as Image1  `;
                                let join_q2 = ` inner join Mapping_VisibilityQuestion mq on mq.VisibilityQuestionId=wq.VisibilityQuestionId and q.PVIS_DEFINITION_ID=mq.VisibilityDefinitionId`;
                                let join_q1 = ` inner join Master_VisibilityQuestion wq on wq.VisibilityQuestionId=q.QUESTION_ID `;
                                let q3 = `select ${selectlist_q1} from ${AppTables.PAIDVIS_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.PVIS_HEADER_ID='${PVisHeaderId}' order by wq.VisibilityQuestionSequence  `;

                                let allQAs = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {
                                        txn.executeSql(q3, [], async function (txn2, txnres3) {
                                            console.log('getWindowQA PaidvisOne App:', txnres3.rows.length);
                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let QAData = txnres3.rows.item(j);
                                                    let { VisibilityQuestionId, AnswerId, Answer, VAShowCamera, Image1 } = QAData
                                                    let showImage1 = (VAShowCamera == 'true' || VAShowCamera == 1) ? 1 : 0;
                                                    let obj1 = {};
                                                    obj1['MID'] = MID;
                                                    obj1['VisibilityDefinitionId'] = VisibilityDefinitionId
                                                    obj1['VisibilityId'] = VisibilityId
                                                    obj1['VisibilityQuestionId'] = VisibilityQuestionId
                                                    obj1['AnswerId'] = AnswerId
                                                    obj1['Answer'] = Answer
                                                    obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                    allQAs.push(obj1);

                                                    if (showImage1 == 1 && Image1 != null && Image1 != '') {
                                                        let imgPath = common_ImagePath + Image1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: Image1,
                                                            filetype: 'image',
                                                            folderName: 'PaidVisibilityImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }
                                                    if (j == txnres3.rows.length - 1) {
                                                        resolve(allQAs);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allQAs);
                                            }

                                        }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                    });
                                });
                            }

                            obj['QuestionAnswers'] = await getWindowQA();

                            if (isStockReq == 1) {
                                async function getWindowStock() {
                                    return new Promise((resolve, reject) => {
                                        let allStock = [];

                                        let join_s1 = '';
                                        if (isCheckAssrt) {
                                            join_s1 = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.PVIS_STOCK_VALUE`;
                                        }
                                        let selectlist_s1 = ` Distinct s.PVIS_STOCK_DEFINITION_ID as VisibilityStockDefinitionId, s.PVIS_DEFINITION_ID as VisibilityDefinitionId,s.PVIS_STOCK_TABLE as VisibilityStockTable,s.PVIS_STOCK_FIELD as VisibilityStockField,s.PVIS_STOCK_VALUE as VisibilityStockValue,s.PVIS_STOCK_MBQ as VisibilityStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock,s.IS_PVIS_PRESENT as isPVisPresent `;
                                        let q4 = `select ${selectlist_s1} from  ${AppTables.PAIDVIS_STOCK_DATA} s ${join_s1} where  s.STORE_ID='${StoreId}' and s.PVIS_HEADER_ID='${PVisHeaderId}'   `;
                                        if (isCheckAssrt) {
                                            q4 += ` and a.StoreId='${StoreId}' `;
                                        }
                                        q4 += ` order by s.PRODUCT_NAME `;


                                        db.transaction(async function (txn) {

                                            txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);
                                                        let { VisibilityStockDefinitionId, VisibilityStockTable, VisibilityStockField, VisibilityStockValue, VisibilityStockMBQ, ProductName, Stock, isPVisPresent } = SData

                                                        let obj1 = {};
                                                        obj1['MID'] = MID;
                                                        obj1['VisibilityDefinitionId'] = VisibilityDefinitionId
                                                        obj1['VisibilityId'] = VisibilityId
                                                        obj1['VisibilityStockDefinitionId'] = VisibilityStockDefinitionId
                                                        obj1['VisibilityStockTable'] = VisibilityStockTable
                                                        obj1['VisibilityStockField'] = VisibilityStockField
                                                        obj1['VisibilityStockValue'] = VisibilityStockValue
                                                        obj1['VisibilityStockMBQ'] = VisibilityStockMBQ
                                                        obj1['ProductName'] = ProductName
                                                        obj1['Stock'] = Stock != '' && Stock != null && Stock != "null" && Stock != "undefined" ? Stock : 0;
                                                        obj1['isPVisPresent'] = isPVisPresent;
                                                        obj1['Specific'] = isSpecificKPI;

                                                        allStock.push(obj1);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    });
                                }
                                obj['StockData'] = await getWindowStock();
                            }
                            else {
                                obj['StockData'] = [];
                            }
                        }
                        else {
                            obj['PaidVisSplitImages'] = [];
                            obj['QuestionAnswers'] = []
                            obj['StockData'] = [];

                        }

                        allChilds.push(obj);
                    }

                    let upkName = UploadKeyName != null && UploadKeyName != 'undefined' && UploadKeyName != '' ? UploadKeyName : 'PaidVisOneApp';
                    postData['MID'] = MID;
                    postData['Keys'] = upkName;
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;


                    console.log('PaidVisOneApp postdata:', upkName, postData);
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}
export function getWAREHOUSECAMPAIGN(storeData, KpiData, UserId, previousDayUpload = false) {

    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;

            let selectlist = ` Distinct w.STORE_ID as StoreId,w.WAREHS_HEADER_ID as WAREHSHeaderId,w.CAMPAIGN_ID,wd.ItemId,wd.ItemCode,wd.ItemName,wd.ItemCategory,wd.ItemCategoryId,w.IS_PRESENT as IsPresent,w.ITEM_QTY as itemQty,w.KPITYPE as KpiType`;
            let join = ` inner join Master_WarehouseItem wd on w.ITEM_ID=wd.ItemId `;
            let q = ` Select ${selectlist} from ${AppTables.WAREHOUSE_CAMPAIGN_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}' and MENU_ID='${MenuId}' `;


            let allChilds = [], allKPIfiles = [], isSpecificKPI = false;
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                console.log('wh count:', MenuId, txnres2.rows.length)
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        // KpiTypId,
                        let { WAREHSHeaderId, CameraSplitNo, ItemId, ItemCode, ItemName, ItemCategory, ItemCategoryId, itemQty, KpiType, IsPresent, CAMPAIGN_ID } = data;
                        let obj = {};

                        // let isImage1=(VisibilityImage1=='true' || VisibilityImage1==1)?1:0;
                        // let isImage2=(VisibilityImage2=='true' || VisibilityImage2==1)?1:0;

                        // let {WHRESHeaderId,ItemId,ItemCode,ItemName,ItemCategory,ItemCategoryId,itemQty,KpiTypId,KpiTyp,IsPresent}=data;
                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['MenuId'] = MenuId;
                        obj['ItemId'] = ItemId;
                        obj['CampaignId'] = CAMPAIGN_ID;
                        // obj['ItemCode']=ItemCode;
                        // obj['ItemName']=ItemName;   
                        // obj['ItemCategory']=ItemCategory;
                        obj['ItemCategoryId'] = ItemCategoryId;
                        obj['itemQty'] = itemQty || 0;
                        // obj['KpiTypId']=KpiTypId;
                        obj['DeploymentType'] = KpiType;
                        obj['IsPresent'] = IsPresent;



                        if (IsPresent == 1) {
                            console.log('add warehouse vis ')


                            async function getWindowSplits() {
                                let q2 = `select * from ${AppTables.WAREHOUSE_CAMPAIGN_IMAGES} where WAREHS_HEADER_ID='${WAREHSHeaderId}' and  STORE_ID='${StoreId}' `;

                                let allWindowSplitImages = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {

                                        txn.executeSql(q2, [], async function (txn2, txnres3) {

                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let splitItem = txnres3.rows.item(j);
                                                    let { IMAGE1, IMAGE2, IMAGE_LABEL } = splitItem
                                                    let obj1 = {};
                                                    obj1["ImageName"] = (IMAGE1 != null ? IMAGE1 : '')
                                                    obj1["ImageType"] = (IMAGE_LABEL != null ? IMAGE_LABEL : '')
                                                    // let obj1={'Image1':(IMAGE1!=null?IMAGE1:''),'Image2':(IMAGE2!=null?IMAGE2:'')};

                                                    // obj1['VisibilityDefinitionId']=VisibilityDefinitionId
                                                    obj1['ItemId'] = ItemId
                                                    obj1['MID'] = MID;

                                                    allWindowSplitImages.push(obj1);
                                                    if (IMAGE1 != null && IMAGE1 != '') {
                                                        let imgPath = common_ImagePath + IMAGE1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: IMAGE1,
                                                            filetype: 'image',
                                                            folderName: 'WareHouseCampaignImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }
                                                    if (IMAGE2 != null && IMAGE2 != '') {
                                                        let imgPath = common_ImagePath + IMAGE2;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: IMAGE2,
                                                            filetype: 'image',
                                                            folderName: 'WareHouseCampaignImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }

                                                    if (j == txnres3.rows.length - 1) {
                                                        console.log('all images added')
                                                        resolve(allWindowSplitImages);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allWindowSplitImages);
                                            }

                                        }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                    });
                                });
                            }

                            obj['WareHouseSplitImages'] = await getWindowSplits();
                        }

                        if (IsPresent == 1) {

                            async function getWindowQA() {

                                let selectlist_q1 = ` DISTINCT  q.QUESTION_ID as ItemQuestionId,q.QUESTION_CODE as ItemQuestionCode,wq.ItemQuestionName,wq.ItemAnswerShowCamera,wq.QuestionType,wq.ItemShowCamera,wq.ItemCameraMandatory,wq.ItemLengthValidationRequired,wq.ItemMinimumChar,wq.ItemMaximumChar,wq.ItemDecimalPoint,wq.ItemDateRangeMin,wq.ItemDateRangeMax,wq.ItemVoiceLengthInMinutes,wq.ItemDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as ItemShowCamera,q.IMAGE1 as Image1  `;
                                let join_q2 = ` inner join Mapping_WarehouseCampaignItemQuestion mq on mq.ItemQuestionId=wq.ItemQuestionId and q.ITEM_ID=mq.ItemId`;
                                let join_q1 = ` inner join Master_WarehouseItemQuestion wq on wq.ItemQuestionId=q.QUESTION_ID `;
                                let q3 = `select ${selectlist_q1} from ${AppTables.WAREHOUSE_CAMPAIGN_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.WAREHS_HEADER_ID='${WAREHSHeaderId}' order by wq.ItemQuestionSequence  `;

                                let allQAs = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {
                                        txn.executeSql(q3, [], async function (txn2, txnres3) {
                                            console.log('getWindowQA Warehouse App:', txnres3.rows.length);
                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let QAData = txnres3.rows.item(j);
                                                    let { ItemQuestionId, AnswerId, Answer, ItemAnswerShowCamera, Image1 } = QAData
                                                    let showImage1 = (ItemAnswerShowCamera == 'true' || ItemAnswerShowCamera == 1) ? 1 : 0;
                                                    let obj1 = {};
                                                    obj1['MID'] = MID;
                                                    obj1['ItemId'] = ItemId
                                                    obj1['ItemQuestionId'] = ItemQuestionId
                                                    obj1['AnswerId'] = AnswerId
                                                    obj1['Answer'] = Answer
                                                    obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                    allQAs.push(obj1);

                                                    if (showImage1 == 1 && Image1 != null && Image1 != '') {
                                                        let imgPath = common_ImagePath + Image1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: Image1,
                                                            filetype: 'image',
                                                            folderName: 'WareHouseCampaignImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }
                                                    if (j == txnres3.rows.length - 1) {
                                                        resolve(allQAs);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allQAs);
                                            }

                                        }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                    });
                                });
                            }

                            obj['QuestionAnswers'] = await getWindowQA();

                        }
                        else {
                            obj['WareHouseSplitImages'] = [];
                            obj['QuestionAnswers'] = []

                        }

                        allChilds.push(obj);
                    }

                    let upkName = UploadKeyName != null && UploadKeyName != 'undefined' && UploadKeyName != '' ? UploadKeyName : 'WareHouseCampaign';
                    postData['MID'] = MID;
                    postData['Keys'] = upkName;
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;


                    console.log('WareHouseCampaign postdata:', upkName, postData);
                    // return
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });

}
export function getDataForWareHouseDeploy(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName, InnerScreenConfig } = KpiData

    const KPIConfig = {};
    InnerScreenConfig?.split(",")?.forEach((value, index) => {
        KPIConfig[value] = false;
    });

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;

            let selectlist = ` Distinct w.STORE_ID as StoreId,w.WAREHS_HEADER_ID as WAREHSHeaderId,w.CAMPAIGN_ID,wd.ItemId,wd.ItemCode,wd.ItemName,wd.ItemCategory,wd.ItemCategoryId,w.IS_PRESENT as IsPresent,w.ITEM_QTY as itemQty,w.KPITYPE as KpiType, w.REASON as Reason,w.REASON_ID as ReasonId,w.MAPPING_TYPE as MappingType`;
            let join = ` inner join Master_WarehouseItem wd on w.ITEM_ID=wd.ItemId `;
            let q = ` Select ${selectlist} from ${AppTables.WAREHOUSE_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}' and MENU_ID='${MenuId}' `;


            let allChilds = [], allKPIfiles = [], isSpecificKPI = false;
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                console.log('wh count:', MenuId, txnres2.rows.length)
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        // KpiTypId,
                        let { WAREHSHeaderId, CameraSplitNo, ItemId, ItemCode, ItemName, ItemCategory, ItemCategoryId, itemQty, KpiType, Reason, IsPresent, CAMPAIGN_ID, MappingType, ReasonId } = data;
                        let obj = {};

                        // let isImage1=(VisibilityImage1=='true' || VisibilityImage1==1)?1:0;
                        // let isImage2=(VisibilityImage2=='true' || VisibilityImage2==1)?1:0;

                        // let {WHRESHeaderId,ItemId,ItemCode,ItemName,ItemCategory,ItemCategoryId,itemQty,KpiTypId,KpiTyp,IsPresent}=data;
                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['MenuId'] = MenuId;
                        obj['ItemId'] = ItemId;
                        obj['CampaignId'] = CAMPAIGN_ID;
                        // obj['ItemCode']=ItemCode;
                        // obj['ItemName']=ItemName;   
                        // obj['ItemCategory']=ItemCategory;
                        obj['ItemCategoryId'] = ItemCategoryId;
                        obj['itemQty'] = itemQty;
                        // obj['KpiTypId']=KpiTypId;
                        obj['DeploymentType'] = KpiType;
                        //new added
                        obj['NonDeploymentReason'] = Reason;
                        obj['NonDeploymentReasonId'] = ReasonId;
                        obj['MappingType'] = MappingType || "";
                        obj['IsPresent'] = IsPresent;



                        // if( KPIConfig?.HidePresentYesNo==false ? true : IsPresent==1){
                        console.log('add warehouse vis ')


                        async function getWindowSplits() {
                            let q2 = `select * from ${AppTables.WAREHOUSE_IMAGES} where WAREHS_HEADER_ID='${WAREHSHeaderId}' and  STORE_ID='${StoreId}' `;

                            let allWindowSplitImages = [];
                            return new Promise((resolve, reject) => {
                                db.transaction(async function (txn) {

                                    txn.executeSql(q2, [], async function (txn2, txnres3) {

                                        if (txnres3.rows.length > 0) {
                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                let splitItem = txnres3.rows.item(j);
                                                let { IMAGE1, IMAGE2, IMAGE_LABEL } = splitItem
                                                let obj1 = {};
                                                obj1["ImageName"] = (IMAGE1 != null ? IMAGE1 : '')
                                                obj1["ImageType"] = (IMAGE_LABEL != null ? IMAGE_LABEL : '')
                                                // let obj1={'Image1':(IMAGE1!=null?IMAGE1:''),'Image2':(IMAGE2!=null?IMAGE2:'')};

                                                // obj1['VisibilityDefinitionId']=VisibilityDefinitionId
                                                obj1['ItemId'] = ItemId
                                                obj1['MID'] = MID;

                                                allWindowSplitImages.push(obj1);
                                                if (IMAGE1 != null && IMAGE1 != '') {
                                                    let imgPath = common_ImagePath + IMAGE1;
                                                    let file = {
                                                        uri: imgPath,
                                                        type: 'image/jpeg',
                                                        name: IMAGE1,
                                                        filetype: 'image',
                                                        folderName: 'WareHouseDeployImages',
                                                    }
                                                    allKPIfiles.push(file);
                                                }
                                                if (IMAGE2 != null && IMAGE2 != '') {
                                                    let imgPath = common_ImagePath + IMAGE2;
                                                    let file = {
                                                        uri: imgPath,
                                                        type: 'image/jpeg',
                                                        name: IMAGE2,
                                                        filetype: 'image',
                                                        folderName: 'WareHouseDeployImages',
                                                    }
                                                    allKPIfiles.push(file);
                                                }

                                                if (j == txnres3.rows.length - 1) {
                                                    console.log('all images added')
                                                    resolve(allWindowSplitImages);
                                                }
                                            }
                                        }
                                        else {
                                            resolve(allWindowSplitImages);
                                        }

                                    }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                });
                            });
                        }

                        obj['WareHouseSplitImages'] = await getWindowSplits();
                        // }

                        if (KPIConfig?.HidePresentYesNo == false ? true : IsPresent == 1) {

                            async function getWindowQA() {

                                let selectlist_q1 = ` DISTINCT  q.QUESTION_ID as ItemQuestionId,q.QUESTION_CODE as ItemQuestionCode,wq.ItemQuestionName,wq.ItemAnswerShowCamera,wq.QuestionType,wq.ItemShowCamera,wq.ItemCameraMandatory,wq.ItemLengthValidationRequired,wq.ItemMinimumChar,wq.ItemMaximumChar,wq.ItemDecimalPoint,wq.ItemDateRangeMin,wq.ItemDateRangeMax,wq.ItemVoiceLengthInMinutes,wq.ItemDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as ItemShowCamera,q.IMAGE1 as Image1  `;
                                let join_q2 = ` inner join Mapping_WarehouseItemQuestion mq on mq.ItemQuestionId=wq.ItemQuestionId and q.ITEM_ID=mq.ItemId`;
                                let join_q1 = ` inner join Master_WarehouseItemQuestion wq on wq.ItemQuestionId=q.QUESTION_ID `;
                                let q3 = `select ${selectlist_q1} from ${AppTables.WAREHOUSE_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.WAREHS_HEADER_ID='${WAREHSHeaderId}' order by wq.ItemQuestionSequence  `;

                                console.log("q3-------", q3)
                                let allQAs = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {
                                        txn.executeSql(q3, [], async function (txn2, txnres3) {
                                            console.log('getWindowQA Warehouse App:', txnres3.rows.length);
                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let QAData = txnres3.rows.item(j);
                                                    let { ItemQuestionId, AnswerId, Answer, ItemAnswerShowCamera, Image1 } = QAData
                                                    let showImage1 = (ItemAnswerShowCamera == 'true' || ItemAnswerShowCamera == 1) ? 1 : 0;
                                                    let obj1 = {};
                                                    obj1['MID'] = MID;
                                                    obj1['ItemId'] = ItemId
                                                    obj1['ItemQuestionId'] = ItemQuestionId
                                                    obj1['AnswerId'] = AnswerId
                                                    obj1['Answer'] = Answer
                                                    obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                    allQAs.push(obj1);

                                                    if (showImage1 == 1 && Image1 != null && Image1 != '') {
                                                        let imgPath = common_ImagePath + Image1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: Image1,
                                                            filetype: 'image',
                                                            folderName: 'WareHouseDeployImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }
                                                    if (j == txnres3.rows.length - 1) {
                                                        resolve(allQAs);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allQAs);
                                            }

                                        }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                    });
                                });
                            }

                            obj['QuestionAnswers'] = await getWindowQA();

                        }
                        else {
                            // obj['WareHouseSplitImages']=[];
                            obj['QuestionAnswers'] = []

                        }

                        allChilds.push(obj);
                    }

                    let upkName = UploadKeyName != null && UploadKeyName != 'undefined' && UploadKeyName != '' ? UploadKeyName : 'WareHouseDeploy';
                    postData['MID'] = MID;
                    postData['Keys'] = upkName;
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;


                    console.log('WareHouse postdata:', upkName, postData);
                    // return
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_VISICOLONEAPP(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;

            // let selectlist=` w.STORE_ID as StoreId, w.PVIS_HEADER_ID as PVisHeaderId,wd.VisibilityDefinitionId,wd.VisibilityId,wd.VisibilityName,wd.VisibilityTable,wd.VisibilityField,wd.VisibilityValue,wd.ChildName,wd.VisibilityRefImage,wd.VisibilityElementCheckAssortment,wd.VisibilityElementStockRequired,w.IS_PRESENT as IsPresent,wd.VisibilityNotExistCamera,w.PVIS_NA_IMAGE as PVisNAImage,wd.VisibilityExistReasonEnable,wd.VisibilityNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.VisibilityImage1,wd.VisibilityImage2,wd.VisibilityImage1Lable,wd.VisibilityImage2Lable,wd.VisibilityImage1CameraGrid,wd.VisibilityImage2CameraGrid,w.IS_STORE_SPECIFIC as isStoreSpecific,w.REASON_REMARK`;
            // let join=` inner join Master_TargetBasedQuestion wd on w.TQQUESTIONID=wd.TgQuestionId `;
            // let q=` Select ${selectlist} from ${AppTables.VISICO_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}' and MENU_ID='${MenuId}' `;

            q = `SELECT * FROM ${AppTables.VISICO_HDR_DATA} w where w.STORE_ID='${StoreId}' and MENU_ID='${MenuId}'`

            let allChilds = [], allKPIfiles = [], isSpecificKPI = false;
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                console.log('pv count:', MenuId, txnres2.rows.length)
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { PVisHeaderId, TARGETTYPEID, TARGETID, TARGETTYPENAME, ChildName, IsPresent } = data;
                        let obj = {};

                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['MenuId'] = MenuId;
                        obj['TargetTypeId'] = TARGETTYPEID;
                        obj['TargetId'] = TARGETID;
                        obj['TargetTypeName'] = TARGETTYPENAME;
                        obj['ChildName'] = ChildName;
                        // obj['IsPresent']=IsPresent;


                        async function getWindowQA() {


                            // let selectlist_q1=` DISTINCT  q.QUESTION_ID as VisibilityQuestionId,q.QUESTION_CODE as VisibilityQuestionCode,wq.VisibilityQuestionName,wq.QuestionType,wq.VQShowCamera,wq.VQCameraMandatory,wq.VQLengthValidationRequired,wq.VQMinimumChar,wq.VQMaximumChar,wq.VQDecimalPoint,wq.VQDateRangeMin,wq.VQDateRangeMax,wq.VQVoiceLengthInMinutes,wq.VQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as VAShowCamera,q.IMAGE1 as Image1  `;
                            // let join_q2=` inner join Mapping_VisibilityQuestion mq on mq.VisibilityQuestionId=wq.VisibilityQuestionId `;
                            // let join_q1=` inner join Master_VisibilityQuestion wq on wq.VisibilityQuestionId=q.QUESTION_ID `;
                            // let q3=`select ${selectlist_q1} from ${AppTables.VISICO_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.PVIS_HEADER_ID='${PVisHeaderId}' order by wq.VisibilityQuestionSequence  `;

                            let join_q2 = `inner JOIN (select distinct TgQuestionId from Master_TargetBasedQuestion) wd on ws.TgQuestionId=wd.TgQuestionId `;
                            let join_q1 = ` inner JOIN Mapping_TargetBasedQuestion ws on w.TARGETTYPEID=ws.TargetTypeId AND w.TQQUESTIONID=ws.TgQuestionId `;
                            let q3 = `select * from ${AppTables.VISICO_CHILD_DATA} w ${join_q1} ${join_q2} where w.STORE_ID='${StoreId}' and w.MENU_ID='${MenuId}' and w.TARGETTYPEID='${TARGETTYPEID}' `;

                            let allQAs = [];
                            return new Promise((resolve, reject) => {
                                db.transaction(async function (txn) {
                                    txn.executeSql(q3, [], async function (txn2, txnres3) {
                                        console.log('getWindowQA PaidvisOne App:', txnres3.rows.length);
                                        if (txnres3.rows.length > 0) {
                                            for (var j = 0; j < txnres3.rows.length; j++) {
                                                let QAData = txnres3.rows.item(j);
                                                let { TQQUESTIONID, TARGETTYPEID, ANSWER_ID, ANSWER, IMAGE_ALLOW1, IMAGE_ALLOW2, TgaShowCamera1, TgaShowCamera2, IMAGE1, IMAGE2, TQA_QUESTION_DISABLE } = QAData
                                                let showImage1 = (IMAGE_ALLOW1 == 'true' || IMAGE_ALLOW1 == 1) ? 1 : 0;
                                                let showImage2 = (IMAGE_ALLOW2 == 'true' || IMAGE_ALLOW2 == 1) ? 1 : 0;

                                                let obj1 = {};
                                                obj1['MID'] = MID;
                                                obj1['TargetTypeId'] = TARGETTYPEID
                                                obj1['TqQuestionId'] = TQQUESTIONID
                                                obj1['AnswerId'] = ANSWER_ID
                                                obj1['Answer'] = ANSWER
                                                obj1['Image1'] = (showImage1 == 1 ? IMAGE1 : '')
                                                obj1['Image2'] = (showImage2 == 1 ? IMAGE2 : '')
                                                if (!(TQA_QUESTION_DISABLE == true || TQA_QUESTION_DISABLE == "true")) {
                                                    allQAs.push(obj1);
                                                }
                                                if (j == txnres3.rows.length - 1) {
                                                    resolve(allQAs);
                                                }
                                            }
                                        }
                                        else {
                                            resolve(allQAs);
                                        }

                                    }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                });
                            });
                        }

                        obj['QuestionAnswers'] = await getWindowQA();


                        allChilds.push(obj);
                    }

                    let upkName = UploadKeyName != null && UploadKeyName != 'undefined' && UploadKeyName != '' ? UploadKeyName : 'TGBaseOneApp';
                    postData['MID'] = MID;
                    postData['Keys'] = upkName;
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;


                    console.log('TGBASEDONEAPP postdata:', upkName, postData);
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_PROG_ONEAPP(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;

            let selectlist = ` Distinct w.STORE_ID as StoreId,w.PROG_HEADER_ID as PROGHeaderId,wd.ProgramDefinitionId,wd.ProgramId,wd.ProgramName,wd.ProgramTable,wd.ProgramField,wd.ProgramValue,wd.ChildName,wd.ProgramRefImage,wd.ProgramElementCheckAssortment,wd.ProgramElementStockRequired,w.IS_PRESENT as IsPresent,wd.ProgramNotExistCamera,w.PROG_NA_IMAGE as PROGNAImage,wd.ProgramExistReasonEnable,wd.ProgramNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,w.REMARK as Remark,wd.NoOfSplit,wd.ProgramImage1,wd.ProgramImage2,wd.ProgramImage1Lable,wd.ProgramImage2Lable,wd.ProgramImage1CameraGrid,wd.ProgramImage2CameraGrid,w.IS_STORE_SPECIFIC as isStoreSpecific,w.REASON_REMARK,w.DISPLAY_AREA,w.POS_DA_REASON_ID,w.POS_DA_REASON,w.NEG_DA_REASON_ID,w.NEG_DA_REASON`;
            let join = ` inner join Master_ProgramDefinition wd on w.PROG_DEFINITION_ID=wd.ProgramDefinitionId `;
            let q = ` Select ${selectlist} from ${AppTables.PROGRAM_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}' and MENU_ID='${MenuId}' `;


            let allChilds = [], allKPIfiles = [], isSpecificKPI = false;
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                console.log('pv count:', MenuId, txnres2.rows.length)
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { PROGHeaderId, ProgramDefinitionId, ProgramId, ProgramName, ProgramTable, ProgramField, ProgramValue, ChildName, ProgramElementStockRequired, ProgramElementCheckAssortment, NoOfSplit, IsPresent, ProgramNotExistCamera, PROGNAImage, ProgramExistReasonEnable, ProgramNotExistReasonEnable, ReasonId, Reason, ProgramImage1, ProgramImage2, Remark, ProgramImage1Lable, ProgramImage2Lable, isStoreSpecific, REASON_REMARK, DISPLAY_AREA, POS_DA_REASON_ID, POS_DA_REASON, NEG_DA_REASON_ID, NEG_DA_REASON } = data;
                        let obj = {};

                        if (i == 0) {
                            isSpecificKPI = isStoreSpecific;
                        }
                        let isStockReq = (ProgramElementStockRequired == 'true' || ProgramElementStockRequired == 1) ? 1 : 0;
                        let isCheckAssrt = (ProgramElementCheckAssortment == 'true' || ProgramElementCheckAssortment == 1) ? 1 : 0;
                        let isNaCamAvl = (ProgramNotExistCamera == 'true' || ProgramNotExistCamera == 1) ? 1 : 0;
                        let isReasonEnable = (ProgramExistReasonEnable == 'true' || ProgramExistReasonEnable == 1) ? 1 : 0;
                        let isNAReasonEnable = (ProgramNotExistReasonEnable == 'true' || ProgramNotExistReasonEnable == 1) ? 1 : 0;
                        let isImage1 = (ProgramImage1 == 'true' || ProgramImage1 == 1) ? 1 : 0;
                        let isImage2 = (ProgramImage2 == 'true' || ProgramImage2 == 1) ? 1 : 0;


                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['MenuId'] = MenuId;
                        obj['ProgramDefinitionId'] = ProgramDefinitionId;
                        obj['ProgramId'] = ProgramId;
                        obj['ProgramTable'] = ProgramTable;
                        obj['ProgramField'] = ProgramField;
                        obj['ProgramValue'] = ProgramValue;
                        obj['ChildName'] = ChildName;
                        obj['IsPresent'] = IsPresent;
                        obj['ProgramNotExistImage'] = isNaCamAvl == 1 ? PROGNAImage : '';
                        obj['ReasonId'] = ReasonId;
                        obj['Reason'] = Reason;
                        obj['Remark'] = Remark != null ? Remark : '';
                        obj['ReasonRemark'] = REASON_REMARK;
                        obj['DisplayArea'] = DISPLAY_AREA;
                        if (POS_DA_REASON != null && POS_DA_REASON != 'undefined' && POS_DA_REASON != '') {
                            obj['DisAreaReasonId'] = POS_DA_REASON_ID;
                            obj['DisAreaReason'] = POS_DA_REASON;
                        } else if (NEG_DA_REASON != null && NEG_DA_REASON != 'undefined' && NEG_DA_REASON != '') {
                            obj['DisAreaReasonId'] = NEG_DA_REASON_ID;
                            obj['DisAreaReason'] = NEG_DA_REASON;
                        }
                        else {
                            obj['DisAreaReasonId'] = 0;
                            obj['DisAreaReason'] = '';
                        }


                        if (IsPresent == 1 && parseInt(NoOfSplit) > 0) {
                            console.log('add paid vis ')


                            async function getWindowSplits() {
                                let q2 = `select * from ${AppTables.PROGRAM_IMAGES} where PROG_HEADER_ID='${PROGHeaderId}' and  STORE_ID='${StoreId}' `;

                                let allWindowSplitImages = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {

                                        txn.executeSql(q2, [], async function (txn2, txnres3) {

                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let splitItem = txnres3.rows.item(j);
                                                    let { IMAGE1, IMAGE2 } = splitItem
                                                    let obj1 = { 'Image1': (isImage1 == 1 && IMAGE1 != null ? IMAGE1 : ''), 'Image2': (isImage2 == 1 && IMAGE2 != null ? IMAGE2 : '') };
                                                    obj1['ProgramDefinitionId'] = ProgramDefinitionId
                                                    obj1['ProgramId'] = ProgramId
                                                    obj1['MID'] = MID;
                                                    // obj1['ProgramImage1Lable']=ProgramImage1Lable;
                                                    // obj1['ProgramImage2Lable']=ProgramImage2Lable;

                                                    allWindowSplitImages.push(obj1);



                                                    if (j == txnres3.rows.length - 1) {
                                                        resolve(allWindowSplitImages);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allWindowSplitImages);
                                            }

                                        }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                    });
                                });
                            }

                            obj['ProgramSplitImages'] = await getWindowSplits();
                        }

                        if (IsPresent == 1) {

                            async function getWindowQA() {


                                let selectlist_q1 = ` DISTINCT  q.QUESTION_ID as ProgramQuestionId,q.QUESTION_CODE as ProgramQuestionCode,wq.ProgramQuestionName,wq.QuestionType,wq.PQShowCamera,wq.PQCameraMandatory,wq.PQLengthValidationRequired,wq.PQMinimumChar,wq.PQMaximumChar,wq.PQDecimalPoint,wq.PQDateRangeMin,wq.PQDateRangeMax,wq.PQVoiceLengthInMinutes,wq.PQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as VAShowCamera,q.IMAGE1 as Image1  `;
                                let join_q2 = ` inner join Mapping_ProgramQuestion mq on mq.ProgramQuestionId=wq.ProgramQuestionId `;
                                let join_q1 = ` inner join Master_ProgramQuestion wq on wq.ProgramQuestionId=q.QUESTION_ID `;
                                let q3 = `select ${selectlist_q1} from ${AppTables.PROGRAM_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.PROG_HEADER_ID='${PROGHeaderId}' order by wq.ProgramQuestionSequence  `;

                                let allQAs = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {
                                        txn.executeSql(q3, [], async function (txn2, txnres3) {
                                            console.log('getWindowQA PaidvisOne App:', txnres3.rows.length);
                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let QAData = txnres3.rows.item(j);
                                                    let { ProgramQuestionId, AnswerId, Answer, VAShowCamera, Image1, QuestionType } = QAData
                                                    let showImage1 = QuestionType == 'Image' ? true : (VAShowCamera == 'true' || VAShowCamera == 1) ? 1 : 0;
                                                    let obj1 = {};
                                                    obj1['MID'] = MID;
                                                    obj1['ProgramDefinitionId'] = ProgramDefinitionId
                                                    obj1['ProgramId'] = ProgramId
                                                    obj1['ProgramQuestionId'] = ProgramQuestionId
                                                    obj1['AnswerId'] = AnswerId
                                                    obj1['Answer'] = QuestionType == 'Image' ? "" : Answer
                                                    obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                    allQAs.push(obj1);


                                                    if (j == txnres3.rows.length - 1) {
                                                        resolve(allQAs);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allQAs);
                                            }

                                        }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                    });
                                });
                            }

                            obj['QuestionAnswers'] = await getWindowQA();

                            if (isStockReq == 1) {
                                async function getWindowStock() {
                                    return new Promise((resolve, reject) => {
                                        let allStock = [];

                                        let join_s1 = '';
                                        if (isCheckAssrt) {
                                            join_s1 = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.PROG_STOCK_VALUE`;
                                        }
                                        let selectlist_s1 = ` Distinct s.PROG_STOCK_DEFINITION_ID as ProgramStockDefinitionId, s.PROG_DEFINITION_ID as ProgramDefinitionId,s.PROG_STOCK_TABLE as ProgramStockTable,s.PROG_STOCK_FIELD as ProgramStockField,s.PROG_STOCK_VALUE as ProgramStockValue,s.PROG_STOCK_MBQ as ProgramStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock,s.IS_PROG_PRESENT as isPROGPresent `;
                                        let q4 = `select ${selectlist_s1} from  ${AppTables.PROGRAM_STOCK_DATA} s ${join_s1} where  s.STORE_ID='${StoreId}' and s.PROG_HEADER_ID='${PROGHeaderId}'   `;
                                        if (isCheckAssrt) {
                                            q4 += ` and a.StoreId='${StoreId}' `;
                                        }
                                        q4 += ` order by s.PRODUCT_NAME `;


                                        db.transaction(async function (txn) {

                                            txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);
                                                        let { ProgramStockDefinitionId, ProgramStockTable, ProgramStockField, ProgramStockValue, ProgramStockMBQ, ProductName, Stock, isPROGPresent } = SData

                                                        let obj1 = {};
                                                        obj1['MID'] = MID;
                                                        obj1['ProgramDefinitionId'] = ProgramDefinitionId
                                                        obj1['ProgramId'] = ProgramId
                                                        obj1['ProgramStockDefinitionId'] = ProgramStockDefinitionId
                                                        obj1['ProgramStockTable'] = ProgramStockTable
                                                        obj1['ProgramStockField'] = ProgramStockField
                                                        obj1['ProgramStockValue'] = ProgramStockValue
                                                        obj1['ProgramStockMBQ'] = ProgramStockMBQ
                                                        obj1['ProductName'] = ProductName
                                                        obj1['Stock'] = Stock != '' && Stock != null && Stock != "null" && Stock != "undefined" ? Stock : 0;
                                                        obj1['isPROGPresent'] = isPROGPresent;
                                                        obj1['Specific'] = isSpecificKPI;

                                                        allStock.push(obj1);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    });
                                }
                                obj['StockData'] = await getWindowStock();
                            }
                            else {
                                obj['StockData'] = [];
                            }
                        }
                        else {
                            obj['ProgramSplitImages'] = [];
                            obj['QuestionAnswers'] = []
                            obj['StockData'] = [];
                        }

                        allChilds.push(obj);
                    }

                    let upkName = UploadKeyName != null && UploadKeyName != 'undefined' && UploadKeyName != '' ? UploadKeyName : 'ProgramOneApp';
                    postData['MID'] = MID;
                    postData['Keys'] = upkName;
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;


                    console.log('PROGRAMONEAPP postdata:', upkName, postData);
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_ADVONEAPP(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData


    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let q2 = ` SELECT * FROM ${AppTables.ADDITIONAL_VISIBILITY} WHERE STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
            let allChilds = [], allKPIfiles = [];
            await txn.executeSql(q2, [], async function (txn2, txnres2) {
                if (txnres2.rows.length > 0) {
                    for (let i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { STORE_ID, VISIT_DATE, PRESENT, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, DISPLAY, DISPLAY_ID, REMARK, IMAGE, ADDED_DATE, FROM_DATE, SHOWFROMDATE, TO_DATE } = data;

                        let obj = {};
                        obj['MID'] = MID;
                        obj['User_Id'] = UserId;
                        obj['Present'] = PRESENT;

                        if (PRESENT == 1) {
                            obj['CategoryId'] = CATEGORY_ID;
                            obj['SubCategoryId'] = SUB_CATEGORY_ID;
                            obj['BrandId'] = BRAND_ID;
                            obj['DisplayId'] = DISPLAY_ID;
                            obj['Remark'] = REMARK;
                            obj['addVImg'] = IMAGE != null && IMAGE != 'undefined' && IMAGE != 'null' ? IMAGE : '';

                            if (SHOWFROMDATE == true) {
                                obj['FromDate'] = FROM_DATE;
                                obj['ToDate'] = TO_DATE
                            }


                            if (IMAGE != '' && IMAGE != null) {
                                let imgPath = common_ImagePath + IMAGE;
                                let file = {
                                    uri: imgPath,
                                    type: 'image/jpeg',
                                    name: IMAGE,
                                    filetype: 'image',
                                    folderName: 'VisibilityImages',
                                }
                                allKPIfiles.push(file);
                            }

                            async function getAdditionalVisibilityStock({
                                StoreId,
                                d2,
                                CATEGORY_ID,
                                BRAND_ID,
                                DISPLAY_ID
                            }) {
                                const stkq = `SELECT DISTINCT DISPLAY_ID as DisplayId,CATEGORY_ID as CategoryId,SUB_CATEGORY_ID as SubCategoryId,BRAND_ID as BrandId,PRODUCT_ID as ProductId,PRODUCT_NAME as ProductName,STOCK_REQ as StockRequire,STOCK as Stock,IS_SELECT as isSelect FROM ${AppTables.ADDITIONAL_VISIBILITY_STOCK} WHERE STORE_ID='${StoreId}' AND VISIT_DATE='${d2}' AND CATEGORY_ID='${CATEGORY_ID}' AND BRAND_ID='${BRAND_ID}' AND DISPLAY_ID='${DISPLAY_ID}'`;
                                console.log("stk_query", stkq);
                                let stockListArr = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(txn => {
                                        txn.executeSql(
                                            stkq,
                                            [],
                                            (txn2, txnres5) => {
                                                const arrstk = [];
                                                console.log("stk_query rows:", txnres5.rows.length);
                                                if (txnres5.rows.length > 0) {
                                                    for (let k = 0; k < txnres5.rows.length; k++) {
                                                        let splitItem = txnres5.rows.item(k);
                                                        let obj2 = {};
                                                        obj2['MID'] = MID;
                                                        obj2['User_Id'] = UserId;
                                                        obj2['BrandId'] = BRAND_ID;
                                                        obj2['DisplayId'] = DISPLAY_ID;
                                                        obj2['ProductId'] = splitItem.ProductId;
                                                        obj2['Stock'] = splitItem.Stock != null && splitItem.Stock != undefined && splitItem.Stock != '' ? splitItem.Stock : 0;
                                                        stockListArr.push(obj2);

                                                        if (k == txnres5.rows.length - 1) {
                                                            console.log('all additionalSTK added')
                                                            resolve(stockListArr);
                                                        }
                                                    }
                                                } else {
                                                    resolve(stockListArr);
                                                }
                                            },
                                            (txnE, txnerr) => {
                                                console.error("SQL error:", txnerr);
                                                resolve(stockListArr);
                                                return true;
                                            }
                                        );
                                    });
                                });
                            }
                            //fghjkl;kjhgf
                            const stockList = await getAdditionalVisibilityStock({
                                StoreId,
                                d2,
                                CATEGORY_ID,
                                BRAND_ID,
                                DISPLAY_ID
                            });

                            obj['StockList'] = stockList;
                        }
                        else {
                            obj['CategoryId'] = 0;
                            obj['SubCategoryId'] = 0;
                            obj['BrandId'] = 0;
                            obj['DisplayId'] = 0;
                            obj['Remark'] = "";
                            obj['addVImg'] = "";
                            obj['StockList'] = [];
                        }

                        allChilds.push(obj);
                    }
                    postData['MID'] = MID;
                    postData['Keys'] = 'AddVisibility';
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_COMPVONEAPP(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData
    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {

            let q2 = ` SELECT Distinct  * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
            let allChilds = [], allKPIfiles = [];
            await txn.executeSql(q2, [], async function (txn2, txnres2) {
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { STORE_ID, VISIT_DATE, PRESENT, COMPANY, COMPANY_ID, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, DISPLAY, DISPLAY_ID, REMARK, IMAGE, ADDED_DATE } = data;
                        let obj = {};
                        obj['MID'] = MID;
                        obj['User_Id'] = UserId;
                        obj['Present'] = PRESENT;
                        if (PRESENT == 1) {
                            obj['CompanyId'] = COMPANY_ID;
                            obj['CategoryId'] = CATEGORY_ID;
                            obj['SubCategoryId'] = SUB_CATEGORY_ID;
                            obj['BrandId'] = BRAND_ID;
                            obj['DisplayId'] = DISPLAY_ID;
                            obj['Remark'] = REMARK;
                            obj['CompVImg'] = IMAGE != null && IMAGE != 'undefined' && IMAGE != 'null' ? IMAGE : '';

                            if (IMAGE != '') {
                                let imgPath = common_ImagePath + IMAGE;
                                let file = {
                                    uri: imgPath,
                                    type: 'image/jpeg',
                                    name: IMAGE,
                                    filetype: 'image',
                                    folderName: 'CompetitionVisibilityImages',
                                }
                                allKPIfiles.push(file);
                            }
                        }
                        else {
                            obj['CompanyId'] = 0;
                            obj['CategoryId'] = 0;
                            obj['SubCategoryId'] = 0;
                            obj['BrandId'] = 0;
                            obj['DisplayId'] = 0;
                            obj['Remark'] = "";
                            obj['CompVImg'] = "";
                        }

                        allChilds.push(obj);
                    }
                    postData['MID'] = MID;
                    postData['Keys'] = 'CompVisibility';
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });

}

export function getDataFor_RETURN_STOCK(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment().format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData


    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let q2 = ` SELECT * FROM ${AppTables.RETURN_STOCK} WHERE STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
            let allChilds = [], allKPIfiles = [];
            await txn.executeSql(q2, [], async function (txn2, txnres2) {
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { STORE_ID, VISIT_DATE, PRESENT, JSON_DATA, IS_UPDATED, ADDED_DATE } = data;

                        let obj = {};
                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = STORE_ID;
                        obj['IsPresent'] = PRESENT;
                        // ✅ Parse JSON_DATA if exists
                        let parsedData = [];
                        try {
                            parsedData = JSON_DATA ? JSON.parse(JSON_DATA) : [];
                        } catch (e) {
                            console.log("Error parsing JSON_DATA:", e);
                        }
                        obj['ReturnStk_Data'] =
                            PRESENT == 1
                                ? parsedData.map(item => ({
                                    CategoryId: item?.CategoryId,
                                    SubCategoryId: item?.SubCategoryId,
                                    BrandId: item?.BrandId,
                                    ProductId: item?.ProductId,
                                    Quantity: parseInt(item?.Quantity) || 0, // ensure number
                                    ReturnTypeId: item?.ReturnTypeId,
                                    IsImageTaken: item?.IsImageTaken,
                                    IsRemarkTaken: item?.IsRemarkTaken,
                                    Remark: item.Remark || "",
                                    Image1: item.Image1 || "",
                                }))
                                : [];

                        allChilds.push(obj);
                        console.log("returnStock", JSON.stringify(allChilds))
                    }
                    postData.MID = MID;
                    postData.Keys = 'RetunStock';
                    postData.JsonData = JSON.stringify(allChilds);
                    postData.UserId = UserId;
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_ORDER_SIMPLIFY(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment().format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData


    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let q2 = ` SELECT * FROM ${AppTables.ORDER_SIMPLIFY} WHERE STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` `;
            let allChilds = [], allKPIfiles = [];
            await txn.executeSql(q2, [], async function (txn2, txnres2) {
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { STORE_ID, VISIT_DATE, PRESENT, REASON_ID, REASON, JSON_DATA, IS_UPDATED, ADDED_DATE } = data;

                        let obj = {};
                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = STORE_ID;
                        obj['IsPresent'] = PRESENT;
                        obj['NonOrderResonId'] = PRESENT != 1 ? REASON_ID : 0;
                        // ✅ Parse JSON_DATA if exists
                        let parsedData = [];
                        try {
                            parsedData = JSON_DATA ? JSON.parse(JSON_DATA) : [];
                        } catch (e) {
                            console.log("Error parsing JSON_DATA:", e);
                        }
                        obj['Orders_Data'] =
                            PRESENT == 1
                                ? parsedData.map(item => ({
                                    CategoryId: item?.CategoryId,
                                    SubCategoryId: item?.SubCategoryId,
                                    BrandId: item?.BrandId,
                                    ProductId: item?.ProductId,
                                    Quantity: parseInt(item?.Quantity) || 0, // ensure number
                                    PackType: item?.PackType,
                                    ImageAllow: item?.ImageAllow,
                                    RemarkAllow: item?.RemarkAllow,
                                    Remark: item.Remark || "",
                                    Image1: item.Image1 || "",
                                }))
                                : [];

                        allChilds.push(obj);
                        console.log("OrderSimplify", JSON.stringify(allChilds))
                    }
                    postData.MID = MID;
                    postData.Keys = 'OrderSimplify';
                    postData.JsonData = JSON.stringify(allChilds);
                    postData.UserId = UserId;
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}

export function getDataFor_WINDOW(storeData, KpiData, UserId, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId, StoreClassId, StoreCategoryId } = storeData;
    let { ScreenName, MenuId, UploadKeyName } = KpiData

    var postData = {};
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let txn1 = txn;
            let selectlist = ` Distinct w.STORE_ID as StoreId,w.WINDOW_HEADER_ID as windowHeaderId,wd.WindowDefinitionId,wd.WindowId,wd.WindowName,wd.WindowTable,wd.WindowField,wd.WindowValue,wd.ChildName,wd.WindowRefImage,wd.WindowElementCheckAssortment,wd.WindowElementStockRequired,w.IS_PRESENT as IsPresent,wd.WindowNotExistCamera,w.WINDOW_NA_IMAGE as WindowNAImage,wd.WindowExistReasonEnable,wd.WindowNotExistReasonEnable,w.REASON_ID as ReasonId,w.REASON as Reason,wd.NoOfSplit,wd.WindowImage1,wd.WindowImage2,wd.WindowImage1Lable,wd.WindowImage2Lable,wd.WindowImage1CameraGrid,wd.WindowImage2CameraGrid`;
            let join = ` inner join Master_WindowDefinition wd on w.WINDOW_DEFINITION_ID=wd.WindowDefinitionId and MenuId='${MenuId}' `;
            let q = ` Select ${selectlist} from ${AppTables.WINDOW_HDR_DATA} w  ${join} where w.STORE_ID='${StoreId}' and w.MENU_ID='${MenuId}'  `;

            let allChilds = [], allKPIfiles = [];
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                if (txnres2.rows.length > 0) {
                    for (var i = 0; i < txnres2.rows.length; i++) {
                        let data = txnres2.rows.item(i);
                        let { windowHeaderId, WindowDefinitionId, WindowId, WindowName, WindowTable, WindowField, WindowValue, ChildName, WindowElementStockRequired, WindowElementCheckAssortment, NoOfSplit, IsPresent, WindowNotExistCamera, WindowNAImage, WindowExistReasonEnable, WindowNotExistReasonEnable, ReasonId, Reason, WindowImage1, WindowImage2 } = data;
                        let obj = {};

                        let isStockReq = (WindowElementStockRequired == 'true' || WindowElementStockRequired == 1) ? 1 : 0;
                        let isCheckAssrt = (WindowElementCheckAssortment == 'true' || WindowElementCheckAssortment == 1) ? 1 : 0;
                        let isNaCamAvl = (WindowNotExistCamera == 'true' || WindowNotExistCamera == 1) ? 1 : 0;
                        let isReasonEnable = (WindowExistReasonEnable == 'true' || WindowExistReasonEnable == 1) ? 1 : 0;
                        let isNAReasonEnable = (WindowNotExistReasonEnable == 'true' || WindowNotExistReasonEnable == 1) ? 1 : 0;
                        let isImage1 = (WindowImage1 == 'true' || WindowImage1 == 1) ? 1 : 0;
                        let isImage2 = (WindowImage2 == 'true' || WindowImage2 == 1) ? 1 : 0;


                        obj['MID'] = MID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['MenuId'] = MenuId;
                        obj['WindowDefinitionId'] = WindowDefinitionId;
                        obj['WindowId'] = WindowId;
                        obj['WindowTable'] = WindowTable;
                        obj['WindowField'] = WindowField;
                        obj['WindowValue'] = WindowValue;
                        obj['ChildName'] = ChildName;
                        obj['IsPresent'] = IsPresent;
                        obj['WindowNotExistImage'] = isNaCamAvl == 1 ? WindowNAImage : '';
                        obj['ReasonId'] = ReasonId;
                        obj['Reason'] = Reason;



                        if (isNaCamAvl == 1 && WindowNAImage != '') {
                            let imgPath = common_ImagePath + WindowNAImage;
                            let file = {
                                uri: imgPath,
                                type: 'image/jpeg',
                                name: WindowNAImage,
                                filetype: 'image',
                                folderName: 'WindowImages',
                            }
                            allKPIfiles.push(file);
                        }


                        if (IsPresent == 1 && parseInt(NoOfSplit) > 0) {
                            console.log('add split windows')


                            async function getWindowSplits() {
                                let q2 = `select * from ${AppTables.WINDOW_IMAGES} where WINDOW_HEADER_ID='${windowHeaderId}' and  STORE_ID='${StoreId}' and MENU_ID='${MenuId}'  `;

                                let allWindowSplitImages = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {

                                        txn.executeSql(q2, [], async function (txn2, txnres3) {

                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let splitItem = txnres3.rows.item(j);
                                                    let { IMAGE1, IMAGE2 } = splitItem
                                                    let obj1 = { 'Image1': (isImage1 == 1 && IMAGE1 != null ? IMAGE1 : ''), 'Image2': (isImage2 == 1 && IMAGE2 != null ? IMAGE2 : '') };
                                                    obj1['WindowDefinitionId'] = WindowDefinitionId
                                                    obj1['WindowId'] = WindowId
                                                    obj1['MID'] = MID;

                                                    allWindowSplitImages.push(obj1);
                                                    if (isImage1 == 1 && IMAGE1 != null && IMAGE1 != '') {
                                                        let imgPath = common_ImagePath + IMAGE1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: IMAGE1,
                                                            filetype: 'image',
                                                            folderName: 'WindowImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }
                                                    if (isImage2 == 1 && IMAGE2 != null && IMAGE2 != '') {
                                                        let imgPath = common_ImagePath + IMAGE2;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: IMAGE2,
                                                            filetype: 'image',
                                                            folderName: 'WindowImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }

                                                    if (j == txnres3.rows.length - 1) {
                                                        console.log('all images added')
                                                        resolve(allWindowSplitImages);

                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allWindowSplitImages);
                                            }

                                        }, function (txnE, txnerr) { console.log(txnerr); resolve(allWindowSplitImages); },);

                                    });
                                });
                            }
                            let windowSpliteImgData = await getWindowSplits();
                            obj['WindowSplitImages'] = windowSpliteImgData
                        }

                        if (IsPresent == 1) {

                            async function getWindowQA() {

                                let selectlist_q1 = ` DISTINCT  q.QUESTION_ID as WindowQuestionId,q.QUESTION_CODE as WindowQuestionCode,wq.WindowQuestionName,wq.QuestionType,wq.WQShowCamera,wq.WQCameraMandatory,wq.WQLengthValidationRequired,wq.WQMinimumChar,wq.WQMaximumChar,wq.WQDecimalPoint,wq.WQDateRangeMin,wq.WQDateRangeMax,wq.WQVoiceLengthInMinutes,wq.WQDefaultQuestionEnable,q.ANSWER as Answer,q.ANSWER_ID as AnswerId,q.MULTI_OPTIONS_IDS as multi_op_ids,q.IMAGE_ALLOW1 as WAShowCamera,q.IMAGE1 as Image1  `;
                                let join_q2 = ` inner join Mapping_WindowQuestion mq on mq.WindowQuestionId=wq.WindowQuestionId `;
                                let join_q1 = ` inner join Master_WindowQuestion wq on wq.WindowQuestionId=q.QUESTION_ID `;
                                let q3 = `select ${selectlist_q1} from ${AppTables.WINDOW_CHILD_DATA} q ${join_q1} ${join_q2} where q.STORE_ID='${StoreId}' and q.WINDOW_DEFINITION_ID='${WindowDefinitionId}' and q.WINDOW_ID='${WindowId}' and q.MENU_ID='${MenuId}'  order by wq.WindowQuestionSequence  `;

                                console.log("")
                                let allQAs = [];
                                return new Promise((resolve, reject) => {
                                    db.transaction(async function (txn) {
                                        txn.executeSql(q3, [], async function (txn2, txnres3) {

                                            if (txnres3.rows.length > 0) {
                                                for (var j = 0; j < txnres3.rows.length; j++) {
                                                    let QAData = txnres3.rows.item(j);
                                                    let { WindowQuestionId, AnswerId, Answer, WAShowCamera, Image1 } = QAData
                                                    let showImage1 = (WAShowCamera == 'true' || WAShowCamera == 1) ? 1 : 0;
                                                    let obj1 = {};
                                                    obj1['MID'] = MID;
                                                    obj1['WindowDefinitionId'] = WindowDefinitionId
                                                    obj1['WindowId'] = WindowId
                                                    obj1['WindowQuestionId'] = WindowQuestionId
                                                    obj1['AnswerId'] = AnswerId
                                                    obj1['Answer'] = Answer
                                                    obj1['Image1'] = (showImage1 == 1 ? Image1 : '')

                                                    allQAs.push(obj1);

                                                    if (showImage1 == 1 && Image1 != null && Image1 != '') {
                                                        let imgPath = common_ImagePath + Image1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: Image1,
                                                            filetype: 'image',
                                                            folderName: 'WindowImages',
                                                        }
                                                        allKPIfiles.push(file);
                                                    }
                                                    if (j == txnres3.rows.length - 1) {
                                                        resolve(allQAs);
                                                    }
                                                }
                                            }
                                            else {
                                                resolve(allQAs);
                                            }

                                        }, function (txnE, txnerr) { console.log('test', txnerr); resolve(allQAs); },);
                                    });
                                });
                            }

                            obj['QuestionAnswers'] = await getWindowQA();

                            if (isStockReq == 1) {
                                async function getWindowStock() {
                                    return new Promise((resolve, reject) => {
                                        let allStock = [];
                                        let join_s1 = ''
                                        if (isCheckAssrt == 1) {
                                            join_s1 = ` inner join Mapping_ProductAssortmentStorewise a on a.ProductId=s.WINDOW_STOCK_VALUE`;
                                        }
                                        let selectlist_s1 = ` Distinct s.WINDOW_STOCK_DEFINITION_ID as WindowStockDefinitionId, s.WINDOW_DEFINITION_ID as WindowDefinitionId,s.WINDOW_STOCK_TABLE as WindowStockTable,s.WINDOW_STOCK_FIELD as WindowStockField,s.WINDOW_STOCK_VALUE as WindowStockValue,s.WINDOW_STOCK_MBQ as WindowStockMBQ,s.PRODUCT_NAME as ProductName, s.STOCK as Stock `;
                                        let q4 = `select ${selectlist_s1} from  ${AppTables.WINDOW_STOCK_DATA} s ${join_s1} where s.WINDOW_DEFINITION_ID='${WindowDefinitionId}' and s.STORE_ID='${StoreId}' and w.MENU_ID='${MenuId}'   `;
                                        if (isCheckAssrt) {
                                            q4 += ` and a.StoreId='${StoreId}' `;
                                        }
                                        q4 += ` order by s.PRODUCT_NAME `;


                                        db.transaction(async function (txn) {

                                            txn.executeSql(q4, [], async function (txn2, txnres3) {
                                                if (txnres3.rows.length > 0) {
                                                    for (var j = 0; j < txnres3.rows.length; j++) {
                                                        let SData = txnres3.rows.item(j);
                                                        let { WindowStockDefinitionId, WindowStockValue, Stock } = SData

                                                        let obj1 = {};
                                                        obj1['MID'] = MID;
                                                        obj1['WindowDefinitionId'] = WindowDefinitionId
                                                        obj1['WindowId'] = WindowId
                                                        obj1['WindowStockDefinitionId'] = WindowStockDefinitionId
                                                        obj1['WindowStockValue'] = WindowStockValue
                                                        obj1['Stock'] = Stock != '' && Stock != null && Stock != "null" && Stock != "undefined" ? Stock : 0;

                                                        allStock.push(obj1);
                                                        if (j == txnres3.rows.length - 1) {
                                                            resolve(allStock);
                                                        }
                                                    }
                                                }
                                                else {
                                                    resolve(allStock);
                                                }

                                            }, function (txnE, txnerr) { console.log(txnerr); resolve(allStock); },);

                                        });
                                    });
                                }
                                obj['StockData'] = await getWindowStock();
                            }
                            else {
                                obj['StockData'] = [];
                            }
                        }
                        else {
                            obj['WindowSplitImages'] = [];
                            obj['QuestionAnswers'] = []
                            obj['StockData'] = [];

                        }

                        allChilds.push(obj);
                    }

                    let upkName = UploadKeyName != null && UploadKeyName != 'undefined' && UploadKeyName != '' ? UploadKeyName : 'Windows';
                    postData['MID'] = MID;
                    postData['Keys'] = upkName;//'Windows'
                    postData['JsonData'] = JSON.stringify(allChilds);
                    postData['UserId'] = UserId;

                    resolve({ 'Files': allKPIfiles, 'PostData': postData });
                }
                else {
                    resolve({ 'PostData': postData });
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return postData;
    });
}


export async function getDB_UploadData(storeData, KPIname, UserId) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, EmpId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId } = storeData;

    switch (KPIname) {
        case 'DBPOSMONEAPP':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {

                        let selectlist = `Distinct w.DISTRIBUTOR_ID as DistributorId,w.POSM_HEADER_ID as posmHeaderId,wd.POSMDefinitionId,wd.PosmId,wd.POSMName,wd.PosmTypeId,wd.POSMTypeName,wd.POSMTable,wd.POSMField,wd.POSMValue,wd.ChildName,w.IS_PRESENT as IsPresent,w.POSM_IMAGE as POSMImage,w.STOCK_QTY as StockQty`;
                        let join = ` inner join Master_POSMDefinition wd on w.POSM_DEFINITION_ID=wd.POSMDefinitionId `;
                        let q = ` Select ${selectlist} from ${AppTables.DBPOSM_HDR_DATA} w  ${join} where w.DISTRIBUTOR_ID='${StoreId}'  `;

                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { posmHeaderId, POSMDefinitionId, PosmId, POSMName, PosmTypeId, POSMTypeName, POSMTable, POSMField, POSMValue, ChildName, IsPresent, POSMImage, StockQty } = data;
                                    let obj = {};

                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['DistributorId'] = StoreId;
                                    obj['POSMDefinitionId'] = POSMDefinitionId;
                                    obj['POSMId'] = PosmId;
                                    obj['POSMTable'] = POSMTable;
                                    obj['POSMField'] = POSMField;
                                    obj['POSMValue'] = POSMValue;
                                    obj['ChildName'] = ChildName;
                                    obj['IsPresent'] = IsPresent;
                                    obj['POSMImage'] = POSMImage != null && POSMImage != 'undefined' ? POSMImage : '';
                                    obj['StockQty'] = StockQty != null && StockQty != "null" && StockQty != 'undefined' && StockQty != undefined && StockQty != '' ? StockQty : 0;

                                    if (POSMImage != null && POSMImage != 'undefined' && POSMImage != '') {
                                        let imgPath = common_ImagePath + POSMImage;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: POSMImage,
                                            filetype: 'image',
                                            folderName: 'DBPOSMImages',
                                        }
                                        allKPIfiles.push(file);
                                    }
                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'DBPOSM';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                // console.log('POSM',postData)
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }
        case 'DBWINDOWONEAPP':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {

                        let selectlist = ` Distinct w.DISTRIBUTOR_ID as DistributorId,w.WINDOW_HEADER_ID as WindowHeaderId,wd.WindowDefinitionId,wd.WindowId,wd.WindowName,wd.WindowTable,wd.WindowField,wd.WindowValue,wd.ChildName,w.IS_PRESENT as IsPresent,w.WINDOW_IMAGE as WindowImage,w.STOCK_QTY as StockQty`;
                        let join = ` inner join Master_WindowDefinition wd on w.WINDOW_DEFINITION_ID=wd.WindowDefinitionId `;
                        let q = ` Select ${selectlist} from ${AppTables.DB_WINDOW_HDR_DATA} w  ${join} where w.DISTRIBUTOR_ID='${StoreId}'  `;

                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { windowHeaderId, WindowDefinitionId, WindowId, WindowName, WindowTable, WindowField, WindowValue, ChildName, IsPresent, WindowImage, StockQty } = data;
                                    let obj = {};


                                    obj['MID'] = MID;
                                    obj['UserId'] = UserId;
                                    obj['DistributorId'] = StoreId;
                                    obj['WindowDefinitionId'] = WindowDefinitionId;
                                    obj['WindowId'] = WindowId;
                                    obj['WindowTable'] = WindowTable;
                                    obj['WindowField'] = WindowField;
                                    obj['WindowValue'] = WindowValue;
                                    obj['ChildName'] = ChildName;
                                    obj['IsPresent'] = IsPresent;
                                    obj['WindowImage'] = WindowImage != null && WindowImage != 'undefined' ? WindowImage : '';
                                    obj['StockQty'] = StockQty != null && StockQty != "null" && StockQty != 'undefined' && StockQty != undefined && StockQty != '' ? StockQty : 0;

                                    if (WindowImage != null && WindowImage != 'undefined' && WindowImage != '') {
                                        let imgPath = common_ImagePath + WindowImage;
                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: WindowImage,
                                            filetype: 'image',
                                            folderName: 'DBWindowImages',
                                        }
                                        allKPIfiles.push(file);
                                    }
                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'DBWindow';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;

                                // console.log('DB Window',postData)
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txnE, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });
            }

        case 'DBVISICOOLERONEAPP':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.DB_VISICOOLER} WHERE DISTRIBUTOR_ID='${StoreId}' and VISIT_DATE='${d2}' `;
                        let allChilds = [], allKPIfiles = [];
                        await txn.executeSql(q2, [], async function (txn2, txnres2) {
                            if (txnres2.rows.length > 0) {
                                for (var i = 0; i < txnres2.rows.length; i++) {
                                    let data = txnres2.rows.item(i);
                                    let { STORE_ID, VISIT_DATE, PRESENT, QRCODE, ASSETCODE, CATEGORY, CATEGORY_ID, SUB_CATEGORY, SUB_CATEGORY_ID, BRAND, BRAND_ID, DISPLAY, DISPLAY_ID, REMARK, IMAGE, ADDED_DATE } = data;
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['User_Id'] = UserId;
                                    obj['QRCode'] = QRCODE;
                                    obj['AssetCode'] = ASSETCODE;
                                    obj['Image'] = IMAGE;
                                    obj['Image'] = IMAGE != null && IMAGE != 'undefined' ? IMAGE : '';

                                    // if(IMAGE!='')
                                    if (IMAGE != null && IMAGE != 'undefined' && IMAGE != '') {

                                        // let imgPath=ImageFolderPath+'DBVISICOOLERONEAPP'+"/"+IMAGE;
                                        let imgPath = common_ImagePath + data.IMAGE;
                                        // console.log("commonimagepath-22--",imgPath,+" "+ImageFolderPath);

                                        let file = {
                                            uri: imgPath,
                                            type: 'image/jpeg',
                                            name: IMAGE,
                                            filetype: 'image',
                                            folderName: 'DistributorVisicoolerImages',

                                        }
                                        allKPIfiles.push(file);
                                    }


                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'DBVisicooler';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                // postData['EmpId']=storeData.MerchandiserId;
                                console.log('CompVisi PostData---', postData)
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                        }, function (txn2, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

                    });
                }).then((val) => {
                    return val;
                }).catch((err) => {
                    console.log(err);
                    return postData;
                });

            }

    }
}

async function getDisplayCheckList(DisplayId, SubCategoryId, storeData1 = {}, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    var result = await new Promise((resolve, reject) => {
        db.transaction(async function (txn) {

            let { StoreId } = storeData1;
            let join = `Inner join Mapping_DisplayChecklist v on p.ChecklistId=v.ChecklistId`;
            let join2 = `Left join (Select * From ${AppTables.PAID_VIS_CHECKLIST} Where STORE_ID='${StoreId}'  ` + (!previousDayUpload ? ` and VISIT_DATE='${d2}' ` : '') + ` and SUB_CATEGORY_ID='${SubCategoryId}' and DISPLAY_ID='${DisplayId}') as T on p.ChecklistId=T.CHECKLIST_iD `;
            let q = `Select Distinct p.ChecklistId as ChecklistId,p.ChecklistName as ChecklistName ,ifnull(T.REASON,'')as REASON,ifnull(T.REASON_ID,0)as REASON_ID from Master_Checklist p ${join} ${join2} Where v.DisplayId ='${DisplayId}'`;

            await txn.executeSql(q, [], async function (txn2, txnres) {

                if (txnres.rows.length > 0) {
                    let arr = [];
                    for (var i = 0; i < txnres.rows.length; i++) {
                        let data = txnres.rows.item(i);
                        arr.push(data);
                    }
                    resolve(arr);
                }
                else {
                    resolve([]);
                }
            }, function (txnE, txnerr) { console.log(txnerr); setProcessing(false); resolve([]) },);

        });
    }).then((val) => {
        return { 'Results': val };
    }).catch((err) => {
        return { 'Error': err };
    });
    return result;
}


export async function UploadDataWithoutWait(storeData, postData, KPIdata, url) {
    return await UploadData2(url, postData)
        .then((res) => {
            if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {
                // console.log(KPIdata+' uploaded');
                return true;
            }
            return false;
        }).catch((err) => {
            console.log(err);
            return false;
        });

}

export async function UploadImagesWithoutWait(postData, url) {
    console.log(url, postData);
    return await UploadFormData(url, postData)
        .then((res) => {
            console.log('test:', res);
            if (typeof res == 'object' && res.error != null) {
                return false;
            }
            else if (res.includes('Success')) {
                console.log('image uploaded');
                return true;
            }
            return false;
        })
        .catch((err) => {
            console.log(err);
            return false;
        });
}

export async function uploadStockDataChunks(stockChunks, url) {
    try {
        let allSuccess = true; // track overall status
        console.log(`📦 Total chunks to upload: ${stockChunks.length}`);
        // Upload each chunk as a single request
        for (const chunk of stockChunks) {
            try {
                // Upload the full PostData object
                //console.log("chunk.PostData",chunk.PostData)
                const result = await uploadSingleSKU(chunk.PostData, url);
                // Check server response
                if (result.UploadJsonResult && result.UploadJsonResult.toLowerCase() === "success") {
                    console.log(`✅ Uploaded Chunk}`);
                } else {
                    console.warn(`⚠️ Server failed for Chunk`);
                    allSuccess = false;
                }
            } catch (err) {
                console.error(`❌ Failed Chunk`, err);
                allSuccess = false;
            }
        }

        return allSuccess

    } catch (err) {
        console.error("🔥 Error uploading stock data", err);
        return { status: "error", message: err.message };
    }
}

export async function uploadSingleSKU(singleSkuData, url) {
    const response = await fetch(url, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        },
        body: JSON.stringify(singleSkuData),
    });

    if (!response.ok) {
        throw new Error(`Server error ${response.status}`);
    }

    return response.json();
}

export async function getChunk_dataStk() {
    let AllKPIFields = await getKPIFields({ ScreenName: "STOCK" });
    let isJsonDataBreakIndex = AllKPIFields.findIndex(
        i => i.KPIFieldName === "JsonDataBreak"
    );
    let isJsonDataBreakPIObj = isJsonDataBreakIndex >= 0 ? AllKPIFields[isJsonDataBreakIndex] : {};
    let isJsonDataBreakEnable = isJsonDataBreakIndex >= 0 ? isJsonDataBreakPIObj["KPIFieldEnable"] : false;
    let KPIFieldDisplayValue = isJsonDataBreakIndex >= 0 ? Number(isJsonDataBreakPIObj["KPIFieldDisplayName"]) : 0;
    console.log("chunk_size", KPIFieldDisplayValue)
    return isJsonDataBreakEnable && KPIFieldDisplayValue > 0
        ? KPIFieldDisplayValue
        : 0;
}


export async function uploadAllData(
    props,
    storeData,
    allKPIs = [],
    UserId,
    JCP_TYPE,
    allow_DataUpload = true,
    UpdateUploadCountLocal = () => { },
    previousDayUpload = false
) {
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);

    let uploadedCount = 0;
    let allfiles = await getAllFolderImages();
    console.log("allfiles to upload:", allfiles.length);

    // run uploads in parallel
    await Promise.all(
        allKPIs.map(async (KpiData) => {
            let { ScreenName, MenuId } = KpiData;
            let res = await getUploadData(storeData, KpiData, UserId, previousDayUpload);
            console.log("res_uploadData:", allow_DataUpload, ScreenName, MenuId, typeof res, res != false);
            if (typeof res === "object" && res != false) {
                if (allow_DataUpload === true) {
                    let CHUNK_SIZE = 0
                    if (ScreenName === 'STOCK') {
                        CHUNK_SIZE = await getChunk_dataStk();
                    }
                    let pdata = ScreenName === 'STOCK' && CHUNK_SIZE > 0 ? res : res.PostData;
                    if (pdata && typeof pdata === "object" && Object.keys(pdata).length > 0) {
                        // upload by parts if needed
                        if (ScreenName === 'STOCK' && CHUNK_SIZE > 0) {
                            console.log("inside_method_check")
                            let isuploaded = await uploadStockDataChunks(pdata, url);
                            console.log("stock_final_status", isuploaded);
                            if (isuploaded) {
                                uploadedCount++;
                            }
                        }
                        else if (ScreenName === "OPSTOCK" && pdata.UploadByPart) {
                            let isUploaded = await UploadByPart(pdata, storeData, KpiData, url);
                            if (isUploaded) uploadedCount++;
                        } else {
                            let isUploaded = await UploadDataWithoutWait(storeData, pdata, KpiData, url);
                            console.log("isUploaded:", ScreenName, MenuId, ":", isUploaded);
                            if (isUploaded) uploadedCount++;
                        }
                    } else {
                        uploadedCount++; // no data, skip
                    }
                } else {
                    uploadedCount++;
                }
            } else {
                uploadedCount++;
            }

            UpdateUploadCountLocal(uploadedCount);
        })
    );

    // ✅ Only runs once after ALL uploads are done
    console.log("allUploaded", uploadedCount, "/", allKPIs.length);

    if (allow_DataUpload) {
        let tbname = JCP_TYPE;
        await uploadStoreStatus(props, storeData, "D", tbname, previousDayUpload);
    }

    console.log("allfiles:", allfiles.length);
    return allfiles;
}


// export async function uploadAllData(props, storeData, allKPIs = [], UserId, JCP_TYPE, allow_DataUpload = true, UpdateUploadCountLocal = () => { }, previousDayUpload = false) {
//     const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);

//     let uploadedCount = 0;
//     let allfiles = await getAllFolderImages();
//     console.log('allfiles to upload:', allfiles.length);
//     return await Promise.all(
//         allKPIs.map(async (KpiData, index) => {
//             let { ScreenName, MenuId } = KpiData;
//             let res = await getUploadData(storeData, KpiData, UserId, previousDayUpload);
//             console.log('res:', ScreenName, MenuId, typeof res, res != false);
//             if (typeof res == 'object' && res != false) {
//                 if (allow_DataUpload == true) {
//                     let pdata = res.PostData;
//                     if (pdata != null && typeof pdata == 'object' && Object.keys(pdata).length > 0) {
//                         // post data exist then upload data 
//                         //upload by parts if data is large
//                         if (ScreenName == 'OPSTOCK' && pdata.UploadByPart != null && pdata.UploadByPart == true) {
//                             let isUploaded = await UploadByPart(pdata, storeData, KpiData, url);
//                             if (isUploaded == true) {
//                                 uploadedCount++;
//                             }
//                             else {
//                                 console.log('data not uploaded for ScreenName: ', ScreenName);
//                             }
//                         }
//                         else {
//                             //upload single time for each KPI if by parts not enabled
//                             let isUploaded = await UploadDataWithoutWait(storeData, res.PostData, KpiData, url);
//                             console.log('isUploaded:', ScreenName, MenuId, ':', isUploaded);
//                             if (isUploaded == true) {
//                                 uploadedCount++;
//                             }
//                         }
//                     }
//                     else {
//                         // data does noot exists for this KPI - may because it is disabled
//                         uploadedCount++;
//                     }
//                 }
//                 else {
//                     uploadedCount++;
//                 }

//                 UpdateUploadCountLocal(uploadedCount);

//                 console.log('upload all len: ', ScreenName, MenuId, uploadedCount, allKPIs.length);

//                 if (uploadedCount == allKPIs.length) {
//                     console.log('allUploaded');

//                     if (allow_DataUpload == true) {
//                         let tbname = JCP_TYPE;
//                         // all data uploaded, Now update status D
//                         await uploadStoreStatus(props, storeData, 'D', tbname, previousDayUpload);
//                     }
//                     // props.updateStoreStatuslocal?await props.updateStoreStatuslocal('D',storeData):'';
//                     // await uploadAllImages(props,storeData,allfiles,tbname);
//                     console.log('allfiles:', allfiles.length)
//                     return allfiles;
//                 }
//             }
//             else {
//                 uploadedCount++;
//                 UpdateUploadCountLocal(uploadedCount);
//                 return [];
//             }
//         })
//     ).then((val) => {
//         return allfiles;
//     });
// }

export async function UploadByPart(pdata, storeData, KpiData, url) {
    let { MID, Keys, UserId, PartsCount, PartsData, AllImages } = pdata;
    let isUploaded = true;
    let promises = [];
    for (let i = 0; i < PartsCount; i++) {
        promises.push(
            new Promise(async (resolve, reject) => {
                let postData = {};
                let alljsonData = {};
                let part_dObj = PartsData[i];
                // "PartNo":i,"Products":allProducts
                let part_d = part_dObj.Products != null ? part_dObj.Products : {};

                if (i == 0) {
                    alljsonData['StockImgs'] = AllImages;
                }
                else {
                    alljsonData['StockImgs'] = AllImages;
                }
                alljsonData['StockChilds'] = part_d;

                postData['MID'] = MID;
                postData['Keys'] = Keys;
                postData['JsonData'] = JSON.stringify(alljsonData);
                postData['UserId'] = UserId;

                console.log("pdata for partcount:", i, postData);
                let isUploadedThis = await UploadDataWithoutWait(storeData, postData, KpiData, url);
                if (!isUploadedThis) {
                    isUploaded = false;
                }
                resolve(isUploadedThis);
            })
        );
    }


    return new Promise.all(promises).then((res) => {
        console.log("Part upload status:", res);
        return isUploaded;
    }).catch((e) => {
        console.log(e);
        return false;
    })
}


export async function uploadAll_DBData(props, storeData, allKPIs = [], UserId, JCP_TYPE, allow_DataUpload = true, loc, UpdateUploadCountLocal = () => { }) {
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);

    let uploadedCount = 0;

    let allfiles = await getAllFolderImages();
    return await Promise.all(
        allKPIs.map(async (item, index) => {
            let name = item.ScreenName;
            let res = await getDB_UploadData(storeData, name, UserId);

            let KPIfiles = res.Files || [];
            console.log('KPIfiles len:', KPIfiles.length)

            // async function mergeFiles(){
            //     return new Promise((resolve,reject)=>{
            //         if(KPIfiles.length>0){
            //             for(var i=0;i<KPIfiles.length;i++){
            //                 let file=KPIfiles[i];
            //                 allfiles.push(file);
            //                 if(i==KPIfiles.length-1){
            //                     resolve(true);
            //                 }
            //             }
            //         }
            //         else{
            //             resolve(true);
            //         }
            //     });
            // }

            // let ismerged=await mergeFiles();
            // console.log('ismerged:',ismerged,allfiles.length)

            if (typeof res == 'object' && res != false) {

                if (allow_DataUpload == true) {
                    let isUploaded = await UploadDataWithoutWait(storeData, res.PostData, name, url);
                    console.log('isUploaded:', name, ',:', isUploaded);
                    if (isUploaded == true) {
                        uploadedCount++;
                    }
                }
                else {
                    uploadedCount++;
                }

                UpdateUploadCountLocal(uploadedCount);

                if (uploadedCount == allKPIs.length) {
                    console.log('allUploaded');

                    if (allow_DataUpload == true) {
                        let tbname = JCP_TYPE;
                        // all data uploaded, Now update status D
                        await uploadDBStatus(props, storeData, 'D', tbname, loc);
                    }
                    console.log('allfiles:', allfiles.length)
                    return allfiles;
                }
            }
            else {
                uploadedCount++;
                UpdateUploadCountLocal(uploadedCount);
                return [];
            }
        })
    ).then((val) => {
        return allfiles;
    });
}

export async function uploadDBStatus(props, storeData, Status, tbname, loc) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { MID, StoreId } = storeData;
    let pdata = {
        "DistributorId": storeData.StoreId,
        "VisitDate": d2,
        "Latitude": (loc?.lat || ''),
        "Longitude": (loc?.lng || ''),
        "ReasonId": 0,
        // "Remark":"",
        // "Appversion":AppVersion,
        "UploadStatus": Status,
        "UserId": (props.UserId || ''),
        "CheckInImage": storeData.CHECKIN_IMAGE != null ? storeData.CHECKIN_IMAGE : '',
        "CheckoutImage": "",
    };

    const url2 = props.baseurl + getMethodName(METHODS.DISTRIBUTOR_COVERAGE);
    return await UploadData2(url2, pdata)
        .then(async (res) => {
            console.log('status uploadres:', res);
            if (parseInt(res) > 0) {
                let datan1 = { StoreId: storeData.StoreId, UploadStatus: Status, tbname: tbname };
                let isUpdated = await UpdateDistributorStatus(props, datan1);
                return isUpdated;
            }
            else {
                return false;
            }
        })
        .catch((err) => {
            console.log(err);
            return false;
        });
}

export async function uploadStoreStatus(props, storeData, Status, tbname, previousDayUpload = false) {

    let { MID, StoreId } = storeData;
    let pdata = {
        "Mid": MID,
        "Status": Status,
    };
    const url2 = props.baseurl + getMethodName(METHODS.COVERAGESTATUS_DETAIL_METHOD);
    return await UploadData2(url2, pdata)
        .then(async (res) => {

            console.log('status uploadres:', res);
            if (!res.error) {
                let datan1 = { StoreId: storeData.StoreId, UploadStatus: Status, tbname: tbname };
                let isUpdated = await UpdateStoreStatus(props, datan1, null, previousDayUpload);
                console.log('status uploadres:', isUpdated)
                return isUpdated;
            }

        })
        .catch((err) => {
            console.log(err);
            return false;
        });
}



// export async function UpdateIRUploadStatus_G(props,TempSessionId,UnSessionId,StoreId){
//     let IRUploadTables=getIRTables();

//     return new Promise.all(

//       IRUploadTables.map((item,index)=>{
//         let {TB_Upload,TB_Image}=item;
//         db.transaction(async function (txn) { 

//           //check if temp session id exists in particular KPI or not
//           let sel_q=`Select * from ${TB_Upload} where TEMP_SESSION_ID='${TempSessionId}' and STORE_ID='${StoreId}' `;
//           await txn.executeSql(sel_q,[],async function (txn2, txnres) { 

//             if(txnres.rows.length>0){
//               //If Temp session id exists in particular KPI the update its status
//               console.log('Updated IR Upload Status for tables',TB_Upload,TB_Image,TempSessionId);

//               let q=`Update ${TB_Upload} set UN_SESSION_ID='${UnSessionId}',UPLOAD_STATUS='1',SYNC_STATUS='Synced' where  TEMP_SESSION_ID='${TempSessionId}' and STORE_ID='${StoreId}' `;//VISIT_DATE='${d2}'
//               await txn.executeSql(q,[],async function (txn2, txnres) { 
//                   console.log('Updated IR Upload Status');

//                   let q2=`Update ${TB_Image} set UN_SESSION_ID='${UnSessionId}' where  TEMP_SESSION_ID='${TempSessionId}' and STORE_ID='${StoreId}' `;//VISIT_DATE='${d2}' and
//                   await txn.executeSql(q2,[],async function (txn2, txnres2) { 
//                       console.log('Updated IR Upload Status');
//                       return true;
//                   },function (txnE,txnerr) { console.log(txnerr);return false; },);

//               },function (txnE,txnerr) { console.log(txnerr);return false; },);
//             }
//             else{
//                 return false;
//             }
//           },function (txnE,txnerr) { console.log(txnerr);return false; },);
//         }); 

//       })

//     ).catch((Err)=>{
//         console.log('Error in UpdateIRUploadStatus:',Err);
//         return false;
//     })



// }

// all Tables having Temp Session Ids for IRsession
export function getIRTables(props) {
    console.log("props.IR_Creds", props.IR_Creds);
    let IR_Creds = props.IR_Creds != null && props.IR_Creds != "" ? JSON.parse(props.IR_Creds) : [];
    let IR_CredsObj = IR_Creds.length > 0 ? IR_Creds[0] : {};
    let PVis_IRCreds = IR_CredsObj.Visibility != null && IR_CredsObj.Visibility.length > 0 ? IR_CredsObj.Visibility[0] : {};
    let Wind_IRCreds = IR_CredsObj.Window != null && IR_CredsObj.Window.length > 0 ? IR_CredsObj.Window[0] : {};
    let SOS_IRCreds = IR_CredsObj.ShareOfShelf != null && IR_CredsObj.ShareOfShelf.length > 0 ? IR_CredsObj.ShareOfShelf[0] : {};
    let AVis_IRCreds = IR_CredsObj.AdditionalVisibility != null && IR_CredsObj.AdditionalVisibility.length > 0 ? IR_CredsObj.AdditionalVisibility[0] : {};
    let CVis_IRCreds = IR_CredsObj.CompVisibility != null && IR_CredsObj.CompVisibility.length > 0 ? IR_CredsObj.CompVisibility[0] : {};
    let PROMO_IRCreds = IR_CredsObj.Promotion != null && IR_CredsObj.Promotion.length > 0 ? IR_CredsObj.Promotion[0] : {};

    let IRUploadTables = [
        { "TB_Image": AppTables.SOS_IR_IMAGES, "TB_Upload": AppTables.SOS_IRUPLOAD, 'ScreenName': 'SOSONEAPP_IR', 'category_name': SOS_IRCreds.category_name, 'task_name': SOS_IRCreds.task_name, 'photo_type': SOS_IRCreds.photo_type, IsMenuIdPresent: false },
        { "TB_Image": AppTables.PAIDVIS_IR_IMAGES, "TB_Upload": AppTables.PAIDVIS_IRUPLOAD, 'ScreenName': 'PAIDVISIONEAPP_IR', 'category_name': PVis_IRCreds.category_name, 'task_name': PVis_IRCreds.task_name, 'photo_type': PVis_IRCreds.photo_type, IsMenuIdPresent: true },
        { "TB_Image": AppTables.ADDVIS_IR_IMAGES, "TB_Upload": AppTables.ADDVIS_IRUPLOAD, 'ScreenName': 'ADDITIONALVISI_IR', 'category_name': AVis_IRCreds.category_name, 'task_name': AVis_IRCreds.task_name, 'photo_type': AVis_IRCreds.photo_type, IsMenuIdPresent: false },
        { "TB_Image": AppTables.COMPVIS_IR_IMAGES, "TB_Upload": AppTables.COMPVIS_IRUPLOAD, 'ScreenName': 'COMPVISI_IR', 'category_name': CVis_IRCreds.category_name, 'task_name': CVis_IRCreds.task_name, 'photo_type': CVis_IRCreds.photo_type, IsMenuIdPresent: false },
        { "TB_Image": AppTables.WINDOW_IR_IMAGES, "TB_Upload": AppTables.WINDOW_IRUPLOAD, 'ScreenName': 'WINDOW_IR', 'category_name': Wind_IRCreds.category_name, 'task_name': Wind_IRCreds.task_name, 'photo_type': Wind_IRCreds.photo_type, IsMenuIdPresent: true },
        { "TB_Image": AppTables.PROMO_IR_IMAGES, "TB_Upload": AppTables.PROMO_IRUPLOAD, 'ScreenName': 'PROMOTIONONEAPP_IR', 'category_name': PROMO_IRCreds.category_name, 'task_name': PROMO_IRCreds.task_name, 'photo_type': PROMO_IRCreds.photo_type, IsMenuIdPresent: true },
    ];
    return IRUploadTables;
}
export async function getPendingIRImages(props) {
    console.log("SyncIRsessions called");
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');

    let sessionListWithDetails = [];
    let IRUploadTables = getIRTables(props);
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            function getJPQuery(PJPTableName, PJPJoinType = 'inner') {

                let join = `${PJPJoinType} Join ${PJPTableName} JP on IR.STORE_ID=JP.StoreId and IR.VISIT_DATE=JP.VisitDate `;
                let unions = ``;
                for (let i = 0; i < IRUploadTables.length; i++) {
                    let item = IRUploadTables[i];
                    let { TB_Image, TB_Upload, ScreenName, category_name, task_name, photo_type, IsMenuIdPresent } = item;
                    let join2 = `left outer Join Menu_Master menu on menu.ScreenName='${ScreenName}' ${IsMenuIdPresent ? ' and menu.MenuId=IR.MENU_ID ' : ''} `;
                    let Sess_subq = `(select distinct tb2.STORE_ID,tb2.TEMP_SESSION_ID,count(tb2.IMAGE1) as SessImageCount from ${TB_Image} tb2 group by tb2.STORE_ID,tb2.TEMP_SESSION_ID) `;
                    let join3 = `inner Join ${Sess_subq}  Img on Img.TEMP_SESSION_ID=IR.TEMP_SESSION_ID and Img.STORE_ID=IR.STORE_ID `;
                    unions += unions != '' ? ' UNION ' : '';
                    unions += `Select Distinct IR.STORE_ID as StoreId,IR.VISIT_DATE as VisitDate,count(IR.TEMP_SESSION_ID) as SessionCount,
                    sum(IFNULL(Img.SessImageCount,0)) as ImageCount,
                    '${TB_Upload}' as TableName1,'${TB_Image}' as TableName2,'${ScreenName}' as ScreenName,JP.StoreCode,JP.StoreName,menu.MenuName,'0' as IRUploadedCount
                    FROM ${TB_Upload} IR ${join3} ${join} ${join2} 
                    where IR.SYNC_STATUS!='Synced' group by IR.STORE_ID,IR.VISIT_DATE   `;
                }
                let commonQ = unions;
                console.log("commonQ:", commonQ);
                return commonQ;
            }

            let MappingJP = getJPQuery('Mapping_JourneyPlan', 'left outer');
            let AdhocJP = getJPQuery('Adhoc_JourneyPlan');
            let q = `${MappingJP}  UNION ${AdhocJP}`;

            if (props.ShowNonMerList == true) {
                let NonMerchJP = getJPQuery('NonMerchandising_JourneyPlan');
                q += ` UNION ${NonMerchJP} `;
            }
            if (props.ShowNonProgram == true) {
                let NonProgJP = getJPQuery('NonProgram_JourneyPlan');
                q += ` UNION ${NonProgJP} `;
            }
            if (props.ShowStoreSearch == true) {
                let SearchStoreJP = getJPQuery('StoreSearch_JourneyPlan');
                q += ` UNION ${SearchStoreJP} `;
            }
            if (props.ShowBeatPlanList == true) {
                let RouteJP = getJPQuery('JourneyPlan_RouteWise');
                q += ` UNION ${RouteJP} `;
            }

            q += ` order by IR.VISIT_DATE,IR.STORE_ID  `;

            // Add joins for other JCP types
            let allChilds = [];
            console.log("allPendingImagesList q:", q);
            await txn.executeSql(q, [], async function (txn2, txnres) {
                if (txnres.rows.length > 0) {
                    for (let i = 0; i < txnres.rows.length; i++) {
                        let data = txnres.rows.item(i);
                        sessionListWithDetails.push(data);

                        if (i == txnres.rows.length - 1) {
                            resolve(sessionListWithDetails);
                        }
                    }
                }
                else {
                    resolve(sessionListWithDetails);
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve(sessionListWithDetails); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return sessionListWithDetails;
    });
}

export async function getPendingIRImagesDetails(props) {
    console.log("SyncIRsessions called");
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');

    let sessionListWithDetails = [];
    let IRUploadTables = getIRTables(props);
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            function getJPQuery(PJPTableName) {

                let join = `Inner Join ${PJPTableName} JP on IR.STORE_ID=JP.StoreId `;
                let unions = ``;
                for (let i = 0; i < IRUploadTables.length; i++) {
                    let item = IRUploadTables[i];
                    let { TB_Image, TB_Upload, ScreenName, category_name, task_name, photo_type } = item;
                    let join2 = `left outer Join Menu_Master menu on menu.ScreenName='${ScreenName}' `;
                    unions += unions != '' ? ' UNION ' : '';
                    //,'SOSONEAPP' as ScreenName
                    // unions+=`Select IR.STORE_ID,IR.TEMP_SESSION_ID,'${TB_Upload}' as TableName1,'${TB_Image}' as TableName2,'${category_name}' as IRCategoryName,'${task_name}' as IRTaskName,'${photo_type}' as IRPhotoType,'${ScreenName}' as ScreenName,JP.StoreCode,JP.StoreName,IR.STORE_ID as StoreId FROM ${TB_Upload} IR ${join} where IR.SYNC_STATUS!='Synced'`;
                    unions += `Select Distinct JP.StoreId,IR.TEMP_SESSION_ID,IR.SESSION_STORECODE as IRStoreCode,IR.SESSION_TASKNAME as IRTaskName,IR.SESSION_CATNAME as IRCategoryName,IR.SESSION_PHOTOTYPE as IRPhotoType,'${TB_Upload}' as TableName1,'${TB_Image}' as TableName2,'${ScreenName}' as ScreenName,JP.StoreCode,JP.StoreName,menu.MenuName FROM ${TB_Upload} IR ${join} ${join2} where IR.SYNC_STATUS!='Synced'`;
                }
                // let commonQ=`Select Distinct IR2.STORE_ID,IR2.TEMP_SESSION_ID,'' as TableName1,'' as TableName2,IR2.IRCategoryName,IR2.IRTaskName,IR2.IRPhotoType,'' as ScreenName,IR2.StoreCode,IR2.StoreName,IR2.StoreId from 
                //  (${unions}) IR2`;
                let commonQ = unions;
                console.log("commonQ:", commonQ);
                return commonQ;
            }

            let MappingJP = getJPQuery('Mapping_JourneyPlan');
            let AdhocJP = getJPQuery('Adhoc_JourneyPlan');
            let q = `${MappingJP}  UNION ${AdhocJP}`;

            if (props.ShowNonMerList == true) {
                let NonMerchJP = getJPQuery('NonMerchandising_JourneyPlan');
                q += ` UNION ${NonMerchJP} `;
            }
            if (props.ShowNonProgram == true) {
                let NonProgJP = getJPQuery('NonProgram_JourneyPlan');
                q += ` UNION ${NonProgJP} `;
            }

            if (props.ShowStoreSearch == true) {
                let SearchStoreJP = getJPQuery('StoreSearch_JourneyPlan');
                q += ` UNION ${SearchStoreJP} `;
            }
            if (props.ShowBeatPlanList == true) {
                let RouteJP = getJPQuery('JourneyPlan_RouteWise');
                q += ` UNION ${RouteJP} `;
            }

            // Add joins for other JCP types
            let allChilds = [];

            await txn.executeSql(q, [], async function (txn2, txnres) {
                if (txnres.rows.length > 0) {
                    for (let i = 0; i < txnres.rows.length; i++) {
                        let data = txnres.rows.item(i);
                        sessionListWithDetails.push(data);

                        if (i == txnres.rows.length - 1) {
                            resolve(sessionListWithDetails);
                        }
                    }
                }
                else {
                    resolve(sessionListWithDetails);
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve(sessionListWithDetails); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return sessionListWithDetails;
    });
}

export async function SyncIRsessions(props, type = "1", storeWise = false, store_item = {}) {
    console.log("SyncIRsessions called");
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let defData = { isUploadStarted: false, noDataFound: false, success: false, AllDataUploaded: false, sessionList: [], sessionListWithDetails: [] };
    let IRUploadTables = getIRTables(props);
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            function getJPQuery(PJPTableName) {

                let join = `Inner Join ${PJPTableName} JP on IR.STORE_ID=JP.StoreId `;
                let unions = ``;
                for (let i = 0; i < IRUploadTables.length; i++) {
                    let item = IRUploadTables[i];
                    let { TB_Image, TB_Upload, ScreenName, category_name, task_name, photo_type } = item;
                    if (!storeWise || (storeWise && store_item != null && ScreenName == store_item.ScreenName)) {

                        unions += unions != '' ? ' UNION ' : '';
                        //,'SOSONEAPP' as ScreenName
                        // unions+=`Select IR.STORE_ID,IR.TEMP_SESSION_ID,'${TB_Upload}' as TableName1,'${TB_Image}' as TableName2,'${category_name}' as IRCategoryName,'${task_name}' as IRTaskName,'${photo_type}' as IRPhotoType,'${ScreenName}' as ScreenName,JP.StoreCode,JP.StoreName,IR.STORE_ID as StoreId FROM ${TB_Upload} IR ${join} where IR.SYNC_STATUS!='Synced'`;
                        unions += `Select Distinct IR.STORE_ID,IR.TEMP_SESSION_ID,IR.SESSION_STORECODE as IRStoreCode,IR.SESSION_TASKNAME as IRTaskName,IR.SESSION_CATNAME as IRCategoryName,IR.SESSION_PHOTOTYPE as IRPhotoType,'${TB_Upload}' as TableName1,'${TB_Image}' as TableName2,'${ScreenName}' as ScreenName,JP.StoreCode,JP.StoreName,IR.STORE_ID as StoreId,IR.VISIT_DATE as VisitDate FROM ${TB_Upload} IR ${join} where IR.SYNC_STATUS!='Synced'`;
                        if (storeWise) {
                            let { StoreId } = store_item;
                            unions += ` and IR.STORE_ID='${StoreId}'`;
                        }
                    }
                }
                // let commonQ=`Select Distinct IR2.STORE_ID,IR2.TEMP_SESSION_ID,'' as TableName1,'' as TableName2,IR2.IRCategoryName,IR2.IRTaskName,IR2.IRPhotoType,'' as ScreenName,IR2.StoreCode,IR2.StoreName,IR2.StoreId from 
                //  (${unions}) IR2`;
                let commonQ = unions;
                console.log("commonQ:", commonQ);
                return commonQ;
            }

            let MappingJP = getJPQuery('Mapping_JourneyPlan');
            let AdhocJP = getJPQuery('Adhoc_JourneyPlan');
            let q = `${MappingJP}  UNION ${AdhocJP}`;

            if (props.ShowNonMerList == true) {
                let NonMerchJP = getJPQuery('NonMerchandising_JourneyPlan');
                q += ` UNION ${NonMerchJP} `;
            }
            if (props.ShowNonProgram == true) {
                let NonProgJP = getJPQuery('NonProgram_JourneyPlan');
                q += ` UNION ${NonProgJP} `;
            }
            if (props.ShowStoreSearch == true) {
                let SearchStoreJP = getJPQuery('StoreSearch_JourneyPlan');
                q += ` UNION ${SearchStoreJP} `;
            }
            if (props.ShowBeatPlanList == true) {
                let RouteJP = getJPQuery('JourneyPlan_RouteWise');
                q += ` UNION ${RouteJP} `;
            }

            // Add joins for other JCP types
            let allChilds = [];

            await txn.executeSql(q, [], async function (txn2, txnres) {
                if (txnres.rows.length > 0) {
                    const promises = [];
                    let arr = [], arr1 = [];

                    for (let i = 0; i < txnres.rows.length; i++) {
                        let data = txnres.rows.item(i);
                        let { STORE_ID, TEMP_SESSION_ID, TableName1, TableName2, StoreCode, VisitDate } = data;
                        console.log("StoreCode:", StoreCode, ",StoreId:", STORE_ID, TableName1);
                        let storeData = { "StoreId": STORE_ID, "StoreCode": StoreCode, "VisitDate": VisitDate };
                        promises.push(new Promise(async (resolve, reject) => {
                            let IRStatusSyncData = await UpdateIRSyncStatus(props, i, storeData, TEMP_SESSION_ID, TableName1, TableName2);
                            let isIRDataUpdated = IRStatusSyncData['isUpdated'];
                            let IRSyncStatus = IRStatusSyncData['Status'];
                            if (IRSyncStatus == 'Failed') {
                                arr.push(TEMP_SESSION_ID);
                                arr1.push(data);
                            }
                            resolve(true);
                        }));
                        if (i == txnres.rows.length - 1) {
                            Promise.all(promises)
                                .then(async (results) => {
                                    console.log("Sync Status Updated for all stores", results);
                                    //Upload Failed Sessions arr if any 
                                    if (arr.length > 0) {
                                        let extraData = { "IsGlobal": type }
                                        let extraData1 = JSON.stringify(extraData);
                                        let isUploadStarted = await IRLogin.UploadIRSessionImages(extraData1, JSON.stringify(arr));
                                        // let isUploadStarted=true;
                                        if (isUploadStarted) {
                                            console.log("sessionListWithDetails:", arr1)
                                            // notify('All images uploaded!');
                                            defData['isUploadStarted'] = true;
                                            defData['success'] = true;
                                            defData['sessionListWithDetails'] = arr1;
                                            defData['sessionList'] = arr;
                                            resolve(defData);
                                        }
                                        else {
                                            notify('Cannot start uploading images!');
                                            resolve(defData);
                                        }
                                    }
                                    else {
                                        defData['isUploadStarted'] = false;
                                        defData['success'] = true;
                                        defData['AllDataUploaded'] = true;
                                        defData['sessionList'] = arr1;
                                        defData['sessionListWithDetails'] = arr1;
                                        resolve(defData);
                                    }

                                })
                                .catch((e) => {
                                    // Handle errors here
                                    console.log("Cannot update sync Status for all stores", e);
                                    resolve(defData);
                                });
                        }
                    }


                }
                else {
                    defData['noDataFound'] = true;
                    defData['success'] = true;
                    resolve(defData);
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve(defData); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return defData;
    });
}

export async function SyncIRsessionsInKPI(props, storeData, TableName1, TableName2, menuEnable = false, menuData = {}) {
    // TableName1: IR Upload Table for KPI
    // TableName2: IR Images Table for KPI
    console.log("SyncIRsessionsInKPI", TableName1, TableName2);
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let defData = { isUploadStarted: false, noDataFound: false, success: false, AllDataUploaded: false, sessionList: [], sessionListWithDetails: [] }
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let q = `Select Distinct STORE_ID,TEMP_SESSION_ID,SESSION_STORECODE,SESSION_TASKNAME,SESSION_CATNAME,SESSION_PHOTOTYPE,'${TableName1}' as TableName1,'${TableName2}' as TableName2,VISIT_DATE as VisitDate FROM ${TableName1} where VISIT_DATE='${d2}' and STORE_ID='${storeData.StoreId}' and SYNC_STATUS!='Synced' `;
            q += menuEnable ? ` and MENU_ID='${menuData.MenuId}' ` : '';
            let allChilds = [];

            await txn.executeSql(q, [], async function (txn2, txnres) {
                if (txnres.rows.length > 0) {
                    const promises = [];
                    let arr = [], arr1 = [];

                    for (let i = 0; i < txnres.rows.length; i++) {
                        let data = txnres.rows.item(i);
                        let { STORE_ID, TEMP_SESSION_ID, TableName1, TableName2 } = data;

                        console.log("push prmoise for TEMP_SESSION_ID:", TEMP_SESSION_ID);
                        promises.push(new Promise(async (resolve, reject) => {
                            let IRStatusSyncData = await UpdateIRSyncStatus(props, i, storeData, TEMP_SESSION_ID, TableName1, TableName2, menuEnable, menuData);
                            console.log("IRStatusSyncData:", IRStatusSyncData);
                            let isIRDataUpdated = IRStatusSyncData['isUpdated'];
                            let IRSyncStatus = IRStatusSyncData['Status'];
                            if (IRSyncStatus == 'Failed') {
                                arr.push(TEMP_SESSION_ID);
                                arr1.push(data);
                            }
                            resolve(true);
                        }));
                        if (i == txnres.rows.length - 1) {
                            Promise.all(promises)
                                .then(async (results) => {
                                    console.log("Sync Status Updated for all stores");
                                    //Upload Failed Sessions arr if any 
                                    if (arr.length > 0) {
                                        let extraData = { "IsGlobal": "0" }
                                        let extraData1 = JSON.stringify(extraData);
                                        let isUploadStarted = await IRLogin.UploadIRSessionImages(extraData1, JSON.stringify(arr));
                                        if (isUploadStarted) {
                                            // notify('All images uploaded!');
                                            defData['isUploadStarted'] = true;
                                            defData['success'] = true;
                                            defData['sessionListWithDetails'] = arr1;
                                            defData['sessionList'] = arr;
                                            resolve(defData);
                                        }
                                        else {
                                            notify('Cannot start uploading images!');
                                            resolve(defData);
                                        }
                                    }
                                    else {
                                        defData['isUploadStarted'] = false;
                                        defData['success'] = true;
                                        defData['AllDataUploaded'] = true;
                                        defData['sessionList'] = arr1;
                                        defData['sessionListWithDetails'] = arr1;
                                        resolve(defData);
                                    }

                                })
                                .catch((e) => {
                                    // Handle errors here
                                    console.log("Cannot update sync Status for all stores", e);
                                    resolve(defData);
                                });
                        }
                    }


                }
                else {
                    defData['noDataFound'] = true;
                    defData['success'] = true;
                    resolve(defData);
                }
            }, function (txnE, txnerr) { console.log(txnerr); resolve(defData); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return defData;
    });
}


export async function UpdateIRSyncStatus(props, index, storeData = {}, TempSessionId, TableName1, TableName2, menuEnable = false, menuData = {}) {
    console.log("UpdateIRSyncStatus", TempSessionId, TableName1, menuEnable);
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, VisitDate } = storeData;

    let IR_Creds = props.IR_Creds != null && props.IR_Creds != "" ? JSON.parse(props.IR_Creds) : [];
    let IR_CredsObj = IR_Creds.length > 0 ? IR_Creds[0] : {};


    let newStdata = storeData;
    if (IR_CredsObj.UseStoreCode != 1) {
        newStdata.StoreCode = newStdata.StoreId;
    }
    let obj = { "StoreData": newStdata };
    let st1 = JSON.stringify(obj);

    let SyncStatus = await IRLogin.CheckIRSessionSync(st1, TempSessionId);//IRSyncStatus.NOT_SYNCED;//

    console.log("SyncStatus for StoreId,TempSessionId (", StoreId, TempSessionId, ") is :" + SyncStatus, typeof SyncStatus)
    // only "Synced" or "Failed" or "Syncing"
    let StatusToUpdate = "Failed", UploadStatus = 0;
    if (SyncStatus == IRSyncStatus.SYNCED) {
        StatusToUpdate = "Synced";
        UploadStatus = 1;
    }
    else if (SyncStatus == IRSyncStatus.SYNCING) {
        StatusToUpdate = "Syncing";
        UploadStatus = 0;
    }
    else if (typeof SyncStatus != "string") {
        StatusToUpdate = "Failed";
        UploadStatus = 0;
    }
    else if (SyncStatus != null && SyncStatus != '' && SyncStatus.includes("No processed image for given session")) {
        console.log("update sync status to 1 ")
        StatusToUpdate = "Synced";
        UploadStatus = 1;
    }

    let defData = { 'isUpdated': false, 'Status': StatusToUpdate };

    console.log("StatusToUpdate:", StatusToUpdate, UploadStatus);
    return new Promise(async (resolve, reject) => {
        db.transaction(async function (txn) {
            let q = `Update ${TableName1} set SYNC_STATUS='${StatusToUpdate}',UPLOAD_STATUS='${UploadStatus}' where STORE_ID='${StoreId}' and VISIT_DATE='${VisitDate}' and TEMP_SESSION_ID='${TempSessionId}'   `;
            q += menuEnable ? ` and MENU_ID='${menuData.MenuId}' ` : '';
            console.log("q to update status :", q);
            await txn.executeSql(q, [], async function (txn2, txnres) {
                console.log("updated status");
                defData['isUpdated'] = true;
                resolve(defData);
            }, function (txnE, txnerr) { console.log(txnerr); resolve(defData); },);

        });

    }).catch((err) => {
        console.log("err:", err);
        return defData;
    });


}


export async function uploadAllImages(props, storeData, allfiles = [], tbname, loc, UpdateUploadCountLocal = () => { }, previousDayUpload = false) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let uploadCount = 0;
    const url = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
    console.log("needToCheck", storeData);
    var isAllUploaded = false;
    if (allfiles.length > 0) {
        return await Promise.all(
            allfiles.map(async (file, i) => {
                let index = i;
                let actualfilepath = 'file://' + file.uri;
                let isExists = await RNFS.exists(actualfilepath).then((res) => { return res; });
                console.log('isExists file', isExists, file.uri);
                if (isExists == false) {
                    uploadCount++;
                    UpdateUploadCountLocal(uploadCount);
                    if (index == allfiles.length - 1) {
                        if (uploadCount == allfiles.length) {
                            if (tbname == '') {
                                // do nothing
                            }
                            else if (tbname == 'Master_Distributor') {
                                console.log('upload U 2');
                                await uploadDBStatus(props, storeData, 'U', tbname, loc);
                            }
                            else {
                                console.log('upload U 1');
                                await uploadStoreStatus(props, storeData, 'U', tbname, previousDayUpload);
                            }

                            isAllUploaded = true;
                        }
                    }
                    return true;
                }
                let postData = new FormData();
                console.log('minm--', mime)
                postData.append('file', {
                    uri: actualfilepath,
                    // type: mime?.getType(actualfilepath) || file.type,
                    type: file.type,
                    name: file.name,
                });

                postData.append('Foldername', file.folderName);
                postData.append('Path', d2);

                let isImageUploaded = await UploadImagesWithoutWait(postData, url);
                if (isImageUploaded == true) {
                    console.log('isExists file uploaded', isExists, uploadCount, index, allfiles.length - 1);
                    uploadCount++;
                    UpdateUploadCountLocal(uploadCount);
                    await RNFS.unlink(actualfilepath);
                } else {
                    console.log('isExists file not u:', isExists, actualfilepath);
                }

                // if(index==allfiles.length-1){}

                if (uploadCount == allfiles.length) {
                    console.log('all images uploaded', allfiles.length, uploadCount);

                    // if(tbname==''){
                    //     // do nothing
                    // }
                    // else if(tbname=='Master_Distributor'){
                    //     console.log('upload U 3');
                    //     await uploadDBStatus(props,storeData,'U',tbname,loc);
                    // }
                    // else{
                    //     console.log('upload U 4');
                    //     await uploadStoreStatus(props,storeData,'U',tbname,previousDayUpload);
                    // }
                    isAllUploaded = true;
                }

                return (isImageUploaded || false);
            })
        ).then(async (val) => {
            console.log("uploadListStatus-------", val);
            let rs = val?.length > 0 ? val : []
            let uploadListStatus = true, stutusVal = false;
            rs?.map((item) => item == false && (uploadListStatus = false))
            console.log("uploadListStatus-------1", isAllUploaded && uploadListStatus, uploadListStatus, isAllUploaded);

            if (isAllUploaded && uploadListStatus) {
                if (tbname == '') {
                    // do nothing
                }
                else if (tbname == 'Master_Distributor') {
                    console.log('upload U 3');
                    stutusVal = await uploadDBStatus(props, storeData, 'U', tbname, loc);
                }
                else {
                    console.log('upload U 4');
                    stutusVal = await uploadStoreStatus(props, storeData, 'U', tbname, previousDayUpload);
                }
            }
            return stutusVal && isAllUploaded && uploadListStatus;
        })
            .catch((err) => {
                console.log(err);
                return false;
            })

    } else {
        let isupdatedU = false;
        if (tbname == '') {
            // do nothing
        }
        else if (tbname == 'Master_Distributor') {
            console.log('upload U 5');
            isupdatedU = await uploadDBStatus(props, storeData, 'U', tbname, loc);
        }
        else {
            console.log("needToCheck1", storeData);
            console.log('upload U 6');
            isupdatedU = await uploadStoreStatus(props, storeData, 'U', tbname, previousDayUpload);
        }
        console.log('on no files found to upload , isupdated::', isupdatedU);
        return true;
    }
}

export async function uploadAll_VisImages(props, allfiles = []) {
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let uploadCount = 0;
    const url = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);

    var isAllUploaded = false;
    if (allfiles.length > 0) {
        return await Promise.all(
            allfiles.map(async (file, i) => {
                let index = i;
                let actualfilepath = 'file://' + file.uri;
                let isExists = await RNFS.exists(actualfilepath).then((res) => { return res; });
                console.log('isExists file', isExists);
                if (isExists == false) {
                    uploadCount++;
                    if (index == allfiles.length - 1) {
                        if (uploadCount == allfiles.length) {
                            isAllUploaded = true;
                        }
                    }
                    return true;
                }
                let postData = new FormData();
                postData.append('file', {
                    uri: actualfilepath,
                    // type: mime?.getType(actualfilepath) || file.type,
                    type: file.type,
                    name: file.name,
                });

                postData.append('Foldername', file.folderName);
                postData.append('Path', d2);

                let isImageUploaded = await UploadImagesWithoutWait(postData, url);
                if (isImageUploaded == true) {
                    console.log('isExists file uploaded', isExists);
                    uploadCount++;
                    await RNFS.unlink(actualfilepath);
                } else {
                    console.log('isExists file not u:', isExists, actualfilepath);
                }

                if (index == allfiles.length - 1) {
                    console.log('all images uploaded', allfiles.length, uploadCount);
                    if (uploadCount == allfiles.length) {

                        isAllUploaded = true;
                    }
                }

                return (isImageUploaded || false);
            })
        ).then((val) => {
            console.log(val);
            return isAllUploaded;
        })
            .catch((err) => {
                console.log(err);
                return false;
            })

    }
    else {
        return true;
    }
}


export async function uploadAllVisitors(props, allVisitors, previousDayUpload = false) {
    console.log('uploadAllVisitors');
    return await Promise.all(
        allVisitors.map(async (item, index) => {
            let qtns = await getVisitorLoginQA(props, item);
            item['feedbackData'] = qtns;
            let isuploaded = await uploadVisitor(props, item, previousDayUpload);
            if (isuploaded == true) {
                return true;
            }
            return false
        })
    ).then((val) => {
        if (val.indexOf(false) >= 0) return false;
        else return true;
    }).catch((err) => {
        return [];
    });
}

export async function getVisitorLoginQA(props, item) {
    let questionData = [];
    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');

    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let selectlist = ` DISTINCT T.CategoryId,T.Category,T.Question,T.QuestionId, T2.*`;
            let join2 = `Inner Join ${AppTables.VISITOR_LOGIN_FEEDBACK} T2 on T.QuestionId=T2.QUESTION_ID  and T.CategoryId=T2.CATEGORY_ID`;
            let q3 = ` SELECT ${selectlist} FROM Master_VisitorLoginQuestion T ${join2} where T2.EMP_CODE='${item.EMP_CODE}' and T2.VISIT_DATE='${d2}' `;

            console.log("global get visitor qtns to upload q:", q3)
            txn.executeSql(q3, [], async function (txn2, txnres) {
                console.log('get qtns to upload count:', txnres.rows.length);
                if (txnres.rows.length > 0) {
                    for (var i = 0; i < txnres.rows.length; i++) {
                        let data = txnres.rows.item(i);
                        let { CATEGORY_ID, QUESTION_ID, QUESTION_TYPE, ANSWER, ANSWER_ID, MULTI_OPTIONS_IDS, IMAGE1, IMAGE2 } = data;
                        let obj1 = {};

                        obj1['CategoryId'] = CATEGORY_ID;
                        obj1['QuestionId'] = QUESTION_ID;
                        obj1['QuestionType'] = QUESTION_TYPE;
                        obj1['Answer'] = ANSWER;
                        obj1['AnswerId'] = ANSWER_ID;
                        obj1['MultiAnswerId'] = MULTI_OPTIONS_IDS != null && MULTI_OPTIONS_IDS != 'undefined' ? MULTI_OPTIONS_IDS : '';
                        obj1['AnswerImage1'] = IMAGE1;
                        obj1['AnswerImage2'] = IMAGE2;
                        obj1['UserId'] = props.UserId;

                        questionData.push(obj1)

                        if (i == txnres.rows.length - 1) {
                            resolve(questionData);
                        }
                    }
                }
                else {
                    resolve(questionData);
                }

            }, function (txnE, txnerr) { console.log(txnerr); return questionData; });

        });

    }).then((res) => {
        return res;
    }).catch((err) => { console.log(err); return questionData; })


}

export async function uploadVisitor(props, item, previousDayUpload = false) {
    let d2 = moment().format('MM/DD/YYYY');
    const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
    let { IN_TIME_IMAGE, OUT_TIME_IMAGE } = item;
    let obj = {
        "MID": 0,
        "CreatedBy": props.UserId,
        "EmpId": item.EMP_ID,
        "VisitDate": d2,
        "InTimeImage": item.IN_TIME_IMAGE,
        "OutTimeImage": item.OUT_TIME_IMAGE,
        "InTime": item.IN_TIME,
        "OutTime": item.OUT_TIME,
        "feedbackData": item.feedbackData,
    }
    let postData = {
        "MID": 0,
        "Keys": "Visitor_Login",
        "JsonData": JSON.stringify(obj),
        "UserId": props.UserId,
    };
    let INIMAGE = '', OUTIMAGE = '';
    if (IN_TIME_IMAGE != '' && IN_TIME_IMAGE != null) {
        let imgPath = 'file://' + common_ImagePath + IN_TIME_IMAGE;
        let file = {
            uri: imgPath,
            type: 'image/jpeg',
            name: IN_TIME_IMAGE,
            filetype: 'image',
            folderName: 'VisitorLogin',
        }
        INIMAGE = file;
    }

    if (OUT_TIME_IMAGE != '' && OUT_TIME_IMAGE != null) {
        let imgPath = 'file://' + common_ImagePath + OUT_TIME_IMAGE;
        let file = {
            uri: imgPath,
            type: 'image/jpeg',
            name: OUT_TIME_IMAGE,
            filetype: 'image',
            folderName: 'VisitorLogin',
        }
        OUTIMAGE = file;
    }


    return await UploadData2(url, postData)
        .then(async (res) => {
            console.log('res:', res);
            if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {

                console.log('props.imageUploadUrl:', props.imageUploadUrl);
                const url2 = (props.imageUploadUrl || URL_IMAGE) + getMethodName(METHODS.UPLOADIMAGES_METHOD);
                let allImageUploaded = true;
                if (INIMAGE != '') {
                    let isExists = await RNFS.exists(INIMAGE.uri).then((res) => { return res; });
                    console.log('isExists file', isExists);
                    if (isExists == true) {
                        let fileData = getImagePOSTData(INIMAGE, d2);
                        let isImageUploaded = await UploadImagesWithoutWait(fileData, url2);
                        if (isImageUploaded == false) {
                            allImageUploaded = false;
                        }
                    }
                }
                if (OUTIMAGE != '') {
                    let isExists = await RNFS.exists(OUTIMAGE.uri).then((res) => { return res; });
                    console.log('isExists file', isExists);
                    if (isExists == true) {
                        let fileData = getImagePOSTData(OUTIMAGE, d2);
                        let isImageUploaded = await UploadImagesWithoutWait(fileData, url2);
                        if (isImageUploaded == false) {
                            allImageUploaded = false;
                        }
                    }
                }
                if (allImageUploaded == true) {
                    console.log('all Visitor image uploaded');
                    return await updateVLUploadStatus(item, previousDayUpload);
                }
                else {
                    return false;
                }

            }
        })
        .catch((err) => {
            console.log(err); return false;
        });

}

export function getImagePOSTData(file, d2) {
    let actualfilepath = file.uri;
    let fileData = new FormData();
    fileData.append('file', {
        uri: actualfilepath,
        // type: mime?.getType(actualfilepath)|| file.Type,
        type: file.type,
        name: file.name,
    });

    fileData.append('Foldername', file.folderName);
    fileData.append('Path', d2);
    return fileData;
}

async function updateVLUploadStatus(item, previousDayUpload = false) {
    let d2 = moment().format('MM/DD/YYYY');
    return new Promise((resolve, reject) => {
        db.transaction(async function (txn) {
            let q = `Update ${AppTables.VISITOR_LOGIN} SET UPLOADSTATUS='U' WHERE EMP_CODE='${item.EMP_CODE}' `;
            if (!previousDayUpload) {
                q += ` AND VISIT_DATE='${d2}'`;
            }
            await txn.executeSql(q, [], async function (txn2, txnres) {
                console.log('Visitor Status Updated');
                resolve(true);
            }, function (txnE, txnerr) { console.log(txnerr); resolve(false); },);

        });
    }).then((val) => {
        return val;
    }).catch((err) => {
        console.log(err);
        return false;
    });
}
