
import moment from 'moment';
import React from 'react';
import { UploadData2, UploadData, UploadFormData, UpdateStoreStatus, bytesToSize, UpdateDistributorStatus } from '../controller/functions';
import { common_ImagePath, db, URL_IMAGE } 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';

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 = ` 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 'VISICOOLER':
            {
                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;

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


                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'DistributorPointVisicoolerSup';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                postData['EmpId'] = storeData.EmpId;
                                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;
                });

            }

    }
}


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": "",
    };
    console.log("uploadDBStatus------", Status, pdata)
    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 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 = [];
    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 getUploadData(storeData, item, UserId, MenuObj = {}) {
    console.log("item in getUploadData:", item);


    let KPIname = item
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    let { StoreId, StateId, MID, UploadStatus, Status, VisitDate, ChainId, StoreTypeId } = storeData;
    console.log('getUploadDataKPIname:', KPIname );

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

                        let selectlist = ` DISTINCT T.SubCategoryId as SubCategoryId,T1.MENUID,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.QuestionTypeNew as QuestionTypeNew,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_SurveySup 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 ${MenuObj?.MenuId ? `AND T1.MENUID='${MenuObj.MenuId}'` : ""}`;
                        let q2 = `Select ${selectlist} FROM Sup_Master_SurveyQuestion T ${join} ${join2} WHERE T1.STORE_ID='${StoreId}' AND EMP_ID='${storeData.MerchandiserId}' AND T1.VISIT_DATE= '${d2}' ORDER BY T.CategorySequence `;

                        console.log('STOREAUDIT Query:', q2);
                        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);
                                    // console.log('STOREAUDIT rows:',txnres2.rows.length,data);
                                    let { SurveyId, CategoryId, MENUID, 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['MenuId'] = MENUID;
                                        obj['EmpId'] = storeData.EmpId;
                                        obj['UserId'] = UserId;
                                        obj['Store_Id'] = StoreId;
                                        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: 'SurveyImagesSup',
                                            }
                                            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: 'SurveyImagesSup',
                                            }
                                            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: 'SurveyVoicefilesSup',
                                            }
                                            allKPIfiles.push(file);
                                        }

                                        allChilds.push(obj);
                                    }
                                }

                                postData['MID'] = MID;
                                postData['Keys'] = 'StoreSurveysSup';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                postData['EmpId'] = storeData.EmpId;
                                console.log('uploaded survey postdata ************************=>', postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txn2, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

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

            }

        case 'StorePhoto':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.STORE_IMAGES} WHERE STORE_ID='${StoreId}' AND EMP_ID='${storeData.MerchandiserId}' 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, ADDED_DATE, REMARK } = data;
                                    // console.log('data',data)
                                    let obj = {};
                                    obj['MID'] = MID;
                                    obj['EmpId'] = storeData.EmpId;
                                    obj['User_Id'] = UserId;
                                    obj['ImageTypeId'] = IMAGE_TYPE_ID;
                                    obj['Image'] = IMAGE;
                                    obj['Remark'] = REMARK;

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

                                    allChilds.push(obj);
                                    console.log('obj', obj)
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'StoreImagesSup';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                postData['EmpId'] = storeData.EmpId;

                                console.log('uploaded StoreImages postdata ************************=>', postData);
                                resolve({ 'Files': allKPIfiles, 'PostData': postData });
                            }
                            else {
                                resolve({ 'PostData': postData });
                            }
                        }, function (txn2, txnerr) { console.log(txnerr); resolve({ 'PostData': postData }); },);

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

            }

        case 'CompPromo':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.COMPETITION_PROMOTION} 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, 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, IMAGE, 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;
                                        obj['SellingPrice'] = SELLING_PRICE;
                                        obj['CompPromoImg'] = IMAGE;

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

                                    }
                                    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['CompPromoImg'] = "";
                                    }


                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'CompPromotionSup';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                console.log('uploaded CompPromo postdata ************************=>', postData)
                                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 'CompVis':
            {
                var postData = {};
                return new Promise((resolve, reject) => {
                    db.transaction(async function (txn) {
                        let q2 = ` SELECT * FROM ${AppTables.COMPETITION_VISIBILITY} WHERE STORE_ID='${StoreId}' and EMP_ID='${storeData.MerchandiserId}' 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['EmpId'] = storeData.EmpId;
                                    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;

                                        if (IMAGE != '') {
                                            let imgPath = common_ImagePath + IMAGE;
                                            let file = {
                                                uri: imgPath,
                                                type: 'image/jpeg',
                                                name: IMAGE,
                                                filetype: 'image',
                                                folderName: 'CompetitionVisibilityImagesSup',
                                            }
                                            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'] = 'CompVisibilitySup';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                postData['EmpId'] = storeData.EmpId;
                                console.log('uploaded 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;
                });

            }


        case 'VISICOOLER':
            {
                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;

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


                                    allChilds.push(obj);
                                }
                                postData['MID'] = MID;
                                postData['Keys'] = 'DistributorPointSup';
                                postData['JsonData'] = JSON.stringify(allChilds);
                                postData['UserId'] = UserId;
                                postData['EmpId'] = storeData.EmpId;
                                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;
                });

            }

        case 'VISIBILITYAUDIT':
            {
                var postData = await getDataFor_PVONEAPP(storeData, UserId);
                console.log("VISIBILITYAUDIT postData:", postData)
                return postData;
                // return false;
            }

        // posSale upload 
        //  case 'POSSALE':{
        //     {
        //         var postData = {};   
        //         return new Promise((resolve,reject)=>{
        //             db.transaction(async function (txn) {
        //                 let join =' cross Join Sup_Master_PosSaleDefinition '
        //                 let q1 = ` Select * from ${AppTables.HEADER_POSSALE_DATA} h ${join} WHERE STORE_ID='${StoreId}' 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);
        //                         console.log("posSale header data Sup",data)
        //                         let {YEAR,MONTH,CYCLEPERIOD,CYCLEPERIODID,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['CycleYear']=YEAR;
        //                         allDataUp['CycleMonth']=MONTH;
        //                         allDataUp['CyclePeriod']=CYCLEPERIOD;
        //                         allDataUp['CycleId']=CYCLEPERIODID;

        //                         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 Sup_Master_PosSaleDefinition m on p.POSDEFINITIONID=m.PosDefinitionId `
        //                         let q=` Select p.*,m.PosTable, m.PosField from ${AppTables.POSSALE_DATA} p ${join1} WHERE p.STORE_ID='${StoreId}' and 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,SALE,POSDEFINITIONID,POS_VALUE,POS_VOLUME,ISPRESENT,REASONID,REASON,PosTable,PosField}=data;
        //                                     console.log("upload data ",data)
        //                                     let obj={};

        //                                     obj['MID']=MID;
        //                                     obj['UserId']=UserId;
        //                                     obj['Store_Id']=StoreId;
        //                                     obj['ChildId']=WINDOW_ID;
        //                                     obj['ChildName']=WINDOW_NAME;
        //                                     obj['PromotorSale']=SALE;
        //                                     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['SupPosSaleImages']=posSaleImages
        //                                         }
        //                                         else{
        //                                             allDataUp['SupPosSaleImages']=[]
        //                                         }
        //                                     }
        //                                 }

        //                                 postData['MID']=MID;
        //                                 postData['Keys']='POSSaleSup';
        //                                 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['SupPosSaleImages']=posSaleImages
        //                                 }
        //                                 else{
        //                                     allDataUp['SupPosSaleImages']=[]
        //                                 }
        //                                 postData['MID']=MID;
        //                                 postData['Keys']='POSSaleSup';
        //                                 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 'POSSALE': {
            var postData = {};
            return new Promise((resolve, reject) => {
                db.transaction(async function (txn) {
                    let join = ' cross Join Sup_Master_PosSaleDefinition ';
                    let q1 = ` Select * from ${AppTables.HEADER_POSSALE_DATA} h ${join} WHERE STORE_ID='${StoreId}' 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 { YEAR, MONTH, CYCLEPERIOD, CYCLEPERIODID, 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['CycleYear'] = YEAR;
                            allDataUp['CycleMonth'] = MONTH;
                            allDataUp['CyclePeriod'] = CYCLEPERIOD;
                            allDataUp['CycleId'] = CYCLEPERIODID;
                            allDataUp['TotalPOSValue'] = TOTAL_POS_VALUE ? TOTAL_POS_VALUE : 0;
                            allDataUp['Image1'] = IMAGE1 || '';
                            allDataUp['Image2'] = IMAGE2 || '';

                            let join1 = `inner join Sup_Master_PosSaleDefinition m on p.POSDEFINITIONID=m.PosDefinitionId `;
                            let q = ` Select p.*,m.PosTable, m.PosField from ${AppTables.POSSALE_DATA} p ${join1} WHERE p.STORE_ID='${StoreId}' and 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 ? IMAGE1 : '' };
                                                    obj1['PosDefinitionId'] = PosDefinitionId;
                                                    obj1['MID'] = MID;
                                                    obj1['UserId'] = UserId;
                                                    obj1['Store_Id'] = StoreId;

                                                    if (IMAGE1) {
                                                        let imgPath = common_ImagePath + IMAGE1;
                                                        let file = {
                                                            uri: imgPath,
                                                            type: 'image/jpeg',
                                                            name: IMAGE1,
                                                            filetype: 'image',
                                                            folderName: 'SupPosSaleImages'  // Folder name for POS Sale images
                                                        };
                                                        allKPIfiles.push(file); // Adding image files to the array
                                                    }

                                                    allWindowSplitImages.push(obj1);

                                                    if (j == txnres3.rows.length - 1) {
                                                        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, SALE, 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['PromotorSale'] = SALE;
                                        obj['PosTable'] = PosTable;
                                        obj['PosField'] = PosField;
                                        obj['POSDefinitionId'] = POSDEFINITIONID;
                                        obj['POSValue'] = POS_VALUE ? POS_VALUE : '0';
                                        obj['POSVolume'] = POS_VOLUME ? POS_VOLUME : '0';
                                        obj['IsPresent'] = ISPRESENT;
                                        obj['ReasonId'] = REASONID ? REASONID : '0';
                                        obj['Reason'] = REASON;

                                        allChilds.push(obj);

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

                                    postData['MID'] = MID;
                                    postData['Keys'] = 'POSSaleSup';
                                    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['SupPosSaleImages'] = posSaleImages;
                                    } else {
                                        allDataUp['SupPosSaleImages'] = [];
                                    }
                                    postData['MID'] = MID;
                                    postData['Keys'] = 'POSSaleSup';
                                    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;
            });
        }


        default: return false;
    }

}


export function getDataFor_PVONEAPP(storeData, UserId) {
    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,s.VId,s.MID as MerMID,Wd.MenuId as MerMenuId,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`;
            let join = ` inner join Sup_Master_VisibilityDefinition wd on w.PVIS_DEFINITION_ID=wd.VisibilityDefinitionId `;
            let join2 = ` inner join Sup_VisibilityAudit s on w.PVIS_DEFINITION_ID=s.VisibilityDefinitionId and  s.StoreId='${StoreId}'`;
            let q = ` Select ${selectlist} from ${AppTables.VISAUDIT_HDR_DATA} w  ${join} ${join2} where w.STORE_ID='${StoreId}' and w.VISIT_DATE='${d2}' `;


            let allChilds = [], allKPIfiles = [], isSpecificKPI = false;
            await txn.executeSql(q, [], async function (txn2, txnres2) {
                console.log('pv count:', 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, MerMID, VId, MerMenuId, 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['Mer_MId'] = MerMID;
                        obj['UserId'] = UserId;
                        obj['Store_Id'] = StoreId;
                        obj['MenuId'] = MerMenuId;
                        obj['VId'] = VId;
                        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 (IsPresent == 1 && parseInt(NoOfSplit) > 0) {
                            console.log('add paid vis ')


                            async function getWindowSplits() {
                                let q2 = `select * from ${AppTables.VISAUDIT_IMAGES} where PVIS_HEADER_ID='${PVisHeaderId}' and  STORE_ID='${StoreId}' 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, 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['VId'] = VId;
                                                    // 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: 'AuditVisibilityImagesSup',
                                                        }
                                                        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: 'AuditVisibilityImagesSup',
                                                        }
                                                        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['VisiAuditSplitImages'] = 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 `;
                                let join_q1 = ` inner join Sup_Master_VisibilityQuestion wq on wq.VisibilityQuestionId=q.QUESTION_ID `;                                
                                let q3 = `select ${selectlist_q1} from ${AppTables.VISAUDIT_CHILD_DATA} q ${join_q1} where q.STORE_ID='${StoreId}' and q.VISIT_DATE='${d2}' 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['VId'] = VId
                                                    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: 'AuditVisibilityImagesSup',
                                                        }
                                                        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_ProductAssortment a on a.ProductId=s.PVIS_STOCK_VALUE and a.StoreCategoryId='${StoreCategoryId}' and a.StoreClassId='${StoreClassId}'`;
                                        }
                                        let selectlist_s1 = `  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.VISAUDIT_STOCK_DATA} s ${join_s1} where  s.STORE_ID='${StoreId}' and s.PVIS_HEADER_ID='${PVisHeaderId}' and s.VISIT_DATE='${d2}'  `;
                                        if (isCheckAssrt) {
                                            q4 += ` and a.StateId='${StateId}' `;
                                        }
                                        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['VId'] = VId
                                                        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['VisiAuditSplitImages'] = [];
                            obj['QuestionAnswers'] = []
                            obj['StockData'] = [];

                        }

                        allChilds.push(obj);
                    }

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


                    console.log('VISIBILITYAUDIT 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 async function UploadDataWithoutWait(storeData, postData, KPIname, url) {
    return await UploadData2(url, postData)
        .then((res) => {
            if (res.UploadJsonResult != null && res.UploadJsonResult == 'Success') {
                console.log("Uploading-Status", KPIname + "---" + res.UploadJsonResult);
                return true;
            }
            return false;
        })
        .catch((err) => {
            console.log(err);
            return false;
        });

}

export async function UploadImagesWithoutWait(postData, url) {
    console.log('urldata', url, JSON.stringify(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 uploadAllData(props, storeData, allKPIs = [], UserId, JCP_TYPE, allow_DataUpload = true, MenuList = []) {
//     const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);

//     let allUploaded = false, uploadedCount = 0;
//     let allfiles = [];
//     console.log('allKPIs to upload:00000', allKPIs);
//     console.log('allKPIs to upload:', MenuList);
//     return await Promise.all(
//         allKPIs.map(async (item, index) => {
//             let MenuObj = (MenuList?.find((i) => (i.ScreenName == item?.KPI && i.MenuId == item?.MenuId))) || {}
//             //console.log("MenuObj-----", MenuObj, name, MenuList)
//             let res = await getUploadData(storeData, item, UserId, MenuObj);
//             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, item?.KPI, url);
//                     console.log('isUploaded:', item?.KPI, ',:', isUploaded, "calleeddd");
//                     if (isUploaded == true) {
//                         uploadedCount++;
//                     }
//                 }
//                 else {
//                     uploadedCount++;
//                 }

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

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

// 🔐 FUNCTION LEVEL LOCK (VERY IMPORTANT)
const uploadedStoreSet = new Set();

export async function uploadAllData(
  props,
  storeData,
  allKPIs = [],
  UserId,
  JCP_TYPE,
  allow_DataUpload = true,
  MenuList = [],
  isManualUpload = false
) {
  const url = props.baseurl + getMethodName(METHODS.UPLOADJSON_METHOD);
  console.log("storeData-->",storeData)
  const storeKey = `${storeData?.StoreId}_${storeData?.MID}`;

  // ❌ STOP DUPLICATE FUNCTION CALL
  if (!isManualUpload && uploadedStoreSet.has(storeKey)) {
    console.warn('⛔ uploadAllData already executed for store:', storeKey);
    return [];
  }
 // uploadedStoreSet.add(storeKey);

  if (!isManualUpload) {
  uploadedStoreSet.add(storeKey);
}

  let uploadedCount = 0;
  let allfiles = [];

  // ✅ REMOVE DUPLICATE KPI (KPI NAME BASIS)
//   const uniqueKPIs = allKPIs.filter(
//     (obj, index, self) =>
//       index === self.findIndex(t => t.KPI === obj.KPI)
//   );

const uniqueKPIs = allKPIs.filter(
  (obj, index, self) =>
    index === self.findIndex(
      t => t.KPI === obj.KPI && t.MenuId === obj.MenuId
    )
);


  console.log('✅ Unique KPIs:', uniqueKPIs);

  // ✅ SEQUENTIAL UPLOAD (NO Promise.all)
  for (const item of uniqueKPIs) {

    let MenuObj =
      MenuList?.find(
        i => i.ScreenName === item?.KPI && i.MenuId === item?.MenuId
      ) || {};

    const res = await getUploadData(
      storeData,
      item.KPI,
      UserId,
      MenuObj
    );

    if (!res || typeof res !== 'object') continue;

    // 🔹 Merge files
    if (Array.isArray(res.Files) && res.Files.length > 0) {
      allfiles.push(...res.Files);
    }

    // 🔹 Upload data
    if (allow_DataUpload === true) {
      const isUploaded = await UploadDataWithoutWait(
        storeData,
        res.PostData,
        item.KPI,
        url
      );

      if (isUploaded === true) {
        uploadedCount++;
      }
    } else {
      uploadedCount++;
    }
  }

  // ✅ UPDATE STORE STATUS ONLY ONCE
  if (uploadedCount === uniqueKPIs.length && allow_DataUpload === true) {
    await uploadStoreStatus(props, storeData, 'D', JCP_TYPE);
  }

  console.log('✅ Final uploaded files:', allfiles.length);
  return allfiles;
}




export async function uploadStoreStatus(props, storeData, Status, tbname) {
    let { MID, StoreId, MerchandiserId } = storeData;
    let d1 = new Date();
    let d2 = moment(d1).format('MM/DD/YYYY');
    // let pdata={
    //     "Mid":MID,
    //     "Status":Status,
    // };
    let pdata = {
        "UserId": (props.UserId || ''),
        "StoreId": storeData.StoreId,
        "MerchandiserId": MerchandiserId,
        "VisitDate": d2,
        "Status": Status,
    }
    const url2 = props.baseurl + getMethodName(METHODS.STORECOVERAGE_STATUS_METHOD);//+getMethodName(METHODS.COVERAGESTATUS_DETAIL_METHOD);
    console.log('pdata', pdata)
    console.log('url2', url2)

    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, EmpId: MerchandiserId };
                console.log('datan1:', datan1);
                let isUpdated = await UpdateStoreStatus(props, datan1);
                console.log('isUpdated:', isUpdated);
                if (isUpdated == true) {
                    return true;
                }
                else {
                    return true;
                }

            }

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

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);

    var isAllUploaded = false;
    if (allfiles.length > 0) {
        return await Promise.all(
            allfiles.map(async (file, i) => {
                let index = i;
                let actualfilepath = 'file://' + file.uri;
                console.log('actualfilepath---->', actualfilepath);

                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) {
                            // if(uploadCount==allfiles.length){
                            if (tbname == '') {
                                // do nothing
                            }
                            else if (tbname == 'Sup_MasterDistributor') {
                                await uploadDBStatus(props, storeData, 'U', tbname, loc);
                            }
                            else {
                                await uploadStoreStatus(props, storeData, 'U', tbname);
                            }
                            isAllUploaded = true;
                            // }
                        }
                    }
                    return true;
                }
                let postData = new FormData();
                postData.append('file', {
                    uri: actualfilepath,
                    type: file.type,//mime.getType(actualfilepath),
                    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);
                    console.log('isExists file not u12:', actualfilepath);
                    let isExists = await RNFS.exists(actualfilepath)
                    console.log('isExists file not u123:', actualfilepath, isExists);
                    if (isExists) {
                        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);
                    // props.updateStoreStatuslocal?await props.updateStoreStatuslocal('U',storeData):'';
                    if (uploadCount == allfiles.length) {
                        if (tbname == '') {
                            // do nothing
                        }
                        else if (tbname == 'Sup_MasterDistributor') {
                            await uploadDBStatus(props, storeData, 'U', tbname, loc);
                        }
                        else {
                            await uploadStoreStatus(props, storeData, 'U', tbname);
                        }
                    }
                    isAllUploaded = true;

                }

                return (isImageUploaded || false);
            })
        ).then((val) => {
            console.log('uploadAllImages responce--->', val);
            return isAllUploaded;
        })
            .catch((err) => {
                console.log('ERROR upload', err);
                return false;
            })

    }
    else {
        let isupdatedU = false;
        if (tbname == '') {
            // do nothing
        }
        else if (tbname == 'Sup_MasterDistributor') {
            isupdatedU = await uploadDBStatus(props, storeData, 'U', tbname);
        }
        else {
            isupdatedU = await uploadStoreStatus(props, storeData, 'U', tbname);
        }
        console.log('on no files found to upload , isupdated::', isupdatedU);

        return true;
    }
}

export async function uploadAllVisitors(props, allVisitors) {
    console.log('uploadAllVisitors');
    return await Promise.all(
        allVisitors.map(async (item, index) => {
            let isuploaded = await uploadVisitor(props, item);
            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 uploadVisitor(props, item) {
    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
    }
    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);
                }
                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: file.type,//mime.getType(actualfilepath),
        name: file.name,
    });

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

async function updateVLUploadStatus(item) {
    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}' AND VISIT_DATE='${d2}'`;
            await txn.executeSql(q, [], async function (txn2, txnres) {
                console.log('Visitor Status Updated');
                resolve(true);
            }, function (txn2, txnerr) { console.log(txnerr); resolve(false); },);

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