import { JSONPath as jsonpath } from "jsonpath-plus";
import _ from "lodash";
import useTranslation from "next-translate/useTranslation";
import Link from "next/link";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
import { connect } from "react-redux";
import transLookup from "../../data/lookuptranslations.json";
import PaginationControl from "./pagination";
import RepsOnResults from "./repsonresults";
import {
getBasicDNSSearchPaged,
getDNSCoords
} from "../../actions/services/searchService";
import GoogleMapReact from "google-map-react";
import { parseCookies } from "nookies";
import OSPoint from "ospoint";
import {
createWatchedCases,
deleteWatchedCases,
getWatchedCasesProxy
} from "../../actions/services/portalService";
import {
setCurrentPage,
setCurrentReference
} from "../../store/currentView/action";
import {
setSearchDetails,
setSearchResults
} from "../../store/searchOutput/action";
import {
setWatchedCases,
setWatchedCasesDetails
} from "../../store/watchedCases/action";
import { getDetailsProxy, getSearchDetailsPaged } from "../utils";
import { signIn, useSession } from "next-auth/react";
const DNSSearchResults = (props) => {
const {
searchString,
searchResultsObj,
searchDetailsObj,
setCurrentReference,
setSearchResults,
setSearchDetails,
advancedSearch,
setCurrentPage,
myportal,
watchedCases,
setWatchedCases,
setWatchedCasesDetails,
showMap,
showLoginCheck
} = props;
let { t } = useTranslation();
const router = useRouter();
const { locale } = router;
const { data: session } = useSession();
var resultsArr = searchResultsObj.value || [];
const [searchLoaded, setSearchLoaded] = useState(false);
const [showSpinnerState, setShowSpinnerState] = useState(false);
// let dataArray = [];
// //push your Json Data in the array
// if (showMap == "true") {
// dnsCoords.map((item) => {
// let point = new OSPoint(
// item.pinswg_anticipatedgridrefnorthing ||
// item.pinswg_anticipatedgridreferencenorthingtext ||
// 0,
// item.pinswg_anticipatedgridrefeasting ||
// item.pinswg_anticipatedgridreferenceeastingtext ||
// 0
// );
// let siteCoords = point.toOSGB36();
// //console.log(siteCoords);
// //console.log(item);
// dataArray.push({
// appellant:
// item[
// "_pinswg_appellant_value@OData.Community.Display.V1.FormattedValue"
// ],
// name: item.pinswg_projectname,
// lat: parseFloat(siteCoords.latitude),
// lng: parseFloat(siteCoords.longitude),
// title: item.pinswg_name,
// });
// });
// }
//console.log(dataArray);
// const ModelsMap = (map, maps) => {
// //instantiate array that will hold your Json Data
// //console.log("here");
// var prev_infowindow = false;
// //Loop through the dataArray to create a marker per data using the coordinates in the json
// console.log(dataArray.length);
// for (let i = 0; i < dataArray.length; i++) {
// const infowindow = new google.maps.InfoWindow({
// content:
// "
" +
// (_.isEmpty(dataArray[i].name)
// ? ""
// : dataArray[i].name.indexOf(";") > 0
// ? router.locale == "cy"
// ? dataArray[i].name.split(";")[1]
// : dataArray[i].name.split(";")[0]
// : dataArray[i].name) +
// "
" +
// (dataArray[i].appellant != null
// ? "" + dataArray[i].appellant + "
"
// : "") +
// "" +
// dataArray[i].title +
// "
",
// });
// let marker = new maps.Marker({
// position: { lat: dataArray[i].lat, lng: dataArray[i].lng },
// title: _.isEmpty(dataArray[i].name)
// ? ""
// : dataArray[i].name.indexOf(";") > 0
// ? router.locale == "cy"
// ? dataArray[i].name.split(";")[1]
// : dataArray[i].name.split(";")[0]
// : dataArray[i].name,
// map,
// });
// marker.addListener("click", () => {
// if (prev_infowindow) {
// prev_infowindow.close();
// }
// prev_infowindow = infowindow;
// infowindow.open({
// anchor: marker,
// map,
// shouldFocus: true,
// });
// });
// }
// };
let spinnerState = () => {
showSpinnerState == true
? setShowSpinnerState(false)
: setShowSpinnerState(true);
};
const [orderByState, setOrderbyState] = useState("createdon");
const [fieldSortState, setfieldSortState] = useState("desc");
const [selectedOption, setSelectedOption] = useState(10);
const cookies = parseCookies();
const selectWatchedCase = (loggedInUser, incidentID, appealType) => {
let updateBody = {
"pinswg_WatchedCase@odata.bind": "/incidents(" + incidentID + ")",
"pinswg_Contact@odata.bind": "/contacts(" + loggedInUser + ")",
"pinswg_appealcasetype": +appealType
};
createWatchedCases(updateBody)
.then((data) => data)
.then(() => {
getWatchedCasesProxy(cookies.pinsUser).then((data) => {
(setWatchedCases(data),
getDetailsProxy(data, "myWatchedCases").then((data) => {
setWatchedCasesDetails(data);
}));
});
});
};
const selectEmailNotifications = (
emailaddress,
loggedInUser,
incidentID,
appealType
) => {
let updateBody = {
"pinswg_WatchedCase@odata.bind": "/incidents(" + incidentID + ")",
"pinswg_Contact@odata.bind": "/contacts(" + loggedInUser + ")",
"pinswg_appealcasetype": +appealType,
"pinswg_emailnotifications": true
};
console.log("Email signed up");
createWatchedCases(updateBody)
.then((data) => data)
.then(() => {
getWatchedCasesProxy(props.accountDetails.loggedinUserId).then(
(data) => {
(setWatchedCases(data),
getDetailsProxy(data, "myWatchedCases").then(
(data) => {
setWatchedCasesDetails(data);
}
));
}
);
});
};
const isWatchedCase = (whichIncident) => {
let isWatched = jsonpath({
path:
"$..value[?(@ && @._pinswg_watchedcase_value=='" +
whichIncident +
"')]",
json: watchedCases,
eval: true
});
return isWatched;
};
const isEmailSignUp = (whichIncident) => {
let isEmail = jsonpath({
path:
"$..value[?(@ && @._pinswg_watchedcase_value=='" +
whichIncident +
"' && @.pinswg_emailnotifications==true)]",
json: watchedCases,
eval: true
});
return isEmail;
};
const deleteItem = (caseID, topThreeType) => {
let cookies = parseCookies();
topThreeType == "watchedCases" &&
deleteWatchedCases(caseID)
.then((data) => data)
.then(() => {
getWatchedCasesProxy(cookies.pinsUser).then((data) => {
let showWatchedCases = (submittedArr) => {
const required = submittedArr.value.filter((el) => {
return (
el.pinswg_representationsubmitted == null
);
});
let newObj = {};
return Object.assign(newObj, {
"@odata.count": required.length,
"value": required
});
};
data = showWatchedCases(data);
data.value.sort(function compare(a, b) {
var dateA = new Date(a.createdon);
var dateB = new Date(b.createdon);
return dateB - dateA;
});
(setWatchedCases(data),
getDetailsProxy(data, "myWatchedCases").then(
(data) => {
setWatchedCasesDetails(data);
}
));
});
});
};
function hasValidKey(obj, key) {
return (
obj.hasOwnProperty(key) &&
obj[key] !== null &&
obj[key] !== undefined &&
obj[key] !== ""
);
}
const ResultsView = (resultsArr) => {
return (
-
-
{t("search:searchresults-site-address-label")}
-
-
-
-
Type
{showSpinnerState == true ? (
{t("common:spinner-fetching-data")}
) : (
resultsArr.map((item, key) => {
let detailsObj = jsonpath({
path:
'$..[?(@ && @.ticketnumber=="' +
item.ticketnumber +
'")]',
json: searchDetailsObj,
eval: true
});
detailsObj = detailsObj[0];
var appType =
router.locale == "cy"
? jsonpath({
path:
'$..[?(@.value=="' +
item[
"pinswg_appealcasetype@OData.Community.Display.V1.FormattedValue"
] +
'")].value_cy',
json: transLookup,
eval: true
})
: item[
"pinswg_appealcasetype@OData.Community.Display.V1.FormattedValue"
] || "N/A";
appType =
appType ==
"Datblygiadau o Arwyddocâd Cenedlaethol" ||
appType ==
"Developments of National Significance"
? "DNS"
: "SIP";
return (
-
{
setCurrentReference({
"ticketnumber":
item.ticketnumber,
"currentReference":
item.title,
"currentType":
"searchResultsObj",
"incidentid":
item.incidentid,
"appealType":
item.pinswg_appealcasetype,
"showMap": showMap,
"showLoginCheck":
props.showLoginCheck
});
}}
>
{t(
"search:searchresults-case-reference-label"
)}
:
{item.title}
-
{t(
"search:searchresults-site-address-label"
)}
:
{_.has(
detailsObj,
"pinswg_projectlocation"
)
? detailsObj.pinswg_projectlocation !=
null
? detailsObj.pinswg_projectlocation.indexOf(
";"
) < 0
? detailsObj.pinswg_projectlocation
: router.locale == "cy"
? detailsObj.pinswg_projectlocation.split(
";"
)[1]
: detailsObj.pinswg_projectlocation.split(
";"
)[0]
: ""
: hasValidKey(
item,
"pinswg_caseaddress"
)
? item.pinswg_caseaddress !=
null
? item.pinswg_caseaddress.indexOf(
";"
) < 0
? item.pinswg_caseaddress
: router.locale ==
"cy"
? item.pinswg_caseaddress.split(
";"
)[1]
: item.pinswg_caseaddress.split(
";"
)[0]
: ""
: ""}
{_.has(
detailsObj,
"pinswg_siteaddressline1"
)
? detailsObj.pinswg_siteaddressline1
: ""}
{_.has(
detailsObj,
"pinswg_siteaddressline1"
) &&
detailsObj.pinswg_siteaddressline1 !=
null &&
}
{_.has(
detailsObj,
"pinswg_siteaddressline2"
)
? detailsObj.pinswg_siteaddressline2
: ""}
{_.has(
detailsObj,
"pinswg_siteaddressline2"
) &&
detailsObj.pinswg_siteaddressline2 !=
null &&
}
{_.has(
detailsObj,
"pinswg_siteaddressline1"
)
? detailsObj.pinswg_siteaddresstown
: ""}
{_.has(
detailsObj,
"pinswg_siteaddresstown"
) &&
detailsObj.pinswg_siteaddresstown !=
null &&
}
{_.has(
detailsObj,
"pinswg_siteaddressline1"
)
? detailsObj.pinswg_siteaddresscounty
: ""}
{_.has(
detailsObj,
"pinswg_siteaddresscounty"
) &&
detailsObj.pinswg_siteaddresscounty !=
null &&
}
{_.has(
detailsObj,
"pinswg_siteaddressline1"
)
? detailsObj.pinswg_siteaddresspostcode
: ""}
-
{t(
"search:searchresults-applicant-label"
)}
:
{_.has(detailsObj, [
"_pinswg_appellant_value@OData.Community.Display.V1.FormattedValue"
])
? detailsObj[
"_pinswg_appellant_value@OData.Community.Display.V1.FormattedValue"
]
: ""}
-
{t(
"search:searchresults-authority-label"
)}
:
{_.has(detailsObj, [
"_pinswg_associatedlpa_value@OData.Community.Display.V1.FormattedValue"
])
? router.locale == "cy"
? jsonpath({
path:
'$..[?(@ && @.value=="' +
detailsObj[
"_pinswg_associatedlpa_value@OData.Community.Display.V1.FormattedValue"
] +
'")].value_cy',
json: transLookup,
eval: true
})
: detailsObj[
"_pinswg_associatedlpa_value@OData.Community.Display.V1.FormattedValue"
] || "N/A"
: ""}
-
{t(
"search:searchresults-status-label"
)}
:
{router.locale == "cy"
? jsonpath({
path:
'$..[?(@ && @.value=="' +
item[
"statuscode@OData.Community.Display.V1.FormattedValue"
] +
'")].value_cy',
json: transLookup,
eval: true
})
: item[
"statuscode@OData.Community.Display.V1.FormattedValue"
] || "N/A"}
-
{t(
"search:searchresults-status-label"
)}
:
{appType}
{myportal == true && (
-
{isWatchedCase(item.incidentid)
.length >
0 ==
true ? (
) : (
)}
{isEmailSignUp(item.incidentid)
.length >
0 ==
true ? (
) : (
)}
)}
{(showLoginCheck == "true" ||
showLoginCheck == true) &&
!session && (
-
{t(
"case:watch-this-case-link"
)}
)}
);
})
)}
);
};
const pagesCount = Math.ceil(searchResultsObj["@odata.count"] / 10);
let currentPage = 0;
currentPage = decodeURI(searchResultsObj["@odata.nextLink"]).split(
"skiptoken="
)[1];
currentPage =
typeof currentPage != "undefined"
? parseInt(
decodeURI(currentPage)
.split('pagenumber="')[1]
.slice(
0,
decodeURI(currentPage)
.split('pagenumber="')[1]
.indexOf('"')
) - 1
)
: pagesCount;
const getSearchPageResults = useCallback(
(pageNumber, orderBy, fieldSort) => {
//console.log(advancedSearch, searchString, pageNumber);
getBasicDNSSearchPaged(
pageNumber,
orderBy,
fieldSort,
selectedOption
)
.then((data) => {
return data;
})
.then((data) => {
setSearchResults(data);
return getSearchDetailsPaged(data).then((data) => {
setSearchDetails(data);
setShowSpinnerState(false);
});
});
},
[selectedOption, setSearchDetails, setSearchResults]
);
const sortDataBy = (whichField) => {
setOrderbyState(whichField);
setfieldSortState("asc");
getSearchPageResults(1, whichField, fieldSortState);
whichField == orderByState
? fieldSortState == "desc"
? setfieldSortState("asc")
: setfieldSortState("desc")
: setfieldSortState("asc");
setCurrentPage(1);
setShowSpinnerState(true);
};
useEffect(() => {
if (searchLoaded) {
if (selectedOption) {
setShowSpinnerState(true);
getSearchPageResults(1, orderByState, fieldSortState);
}
} else {
setSearchLoaded(true);
}
}, [
selectedOption,
fieldSortState,
orderByState,
searchLoaded,
getSearchPageResults
]);
return (
<>
{showMap == "true" && (
{/*
ModelsMap(map, maps)
}
/> */}
)}
{searchResultsObj["@odata.count"] > 5 && (
)}
{!searchLoaded ? (
) : resultsArr.length > 0 ? (
ResultsView(resultsArr)
) : (
{t("search:searchresults-no-records-label")}
)}
{/* {resultsArr.length > 0 ? (
ResultsView(resultsArr)
) : (
{t("search:searchresults-no-records-label")}
)} */}
>
);
};
const mapDispatchToProps = (dispatch) => {
return {
setCurrentReference: (currentReference) => {
dispatch(setCurrentReference(currentReference));
},
setSearchResults: (searchResultsObj) => {
dispatch(setSearchResults(searchResultsObj));
},
setSearchDetails: (searchDetailsObj) => {
dispatch(setSearchDetails(searchDetailsObj));
},
setWatchedCases: (watchedCases) => {
dispatch(setWatchedCases(watchedCases));
},
setWatchedCasesDetails: (watchedCasesDetails) => {
dispatch(setWatchedCasesDetails(watchedCasesDetails));
},
setCurrentPage: (currentPage) => {
dispatch(setCurrentPage(currentPage));
}
};
};
const mapStateToProps = (state) => {
return {
// currentView: state.currentView,
accountDetails: state.accountDetails
// search: state.search,
// searchResultsObj: state.searchResultsObj,
};
};
export default connect(mapStateToProps, mapDispatchToProps)(DNSSearchResults);