var dtSearchTitleParam = [];
var btnIsClick = true;
var ajaxReloadCallBack;
window.YT = window.YT || {};
YT.Math = {};
///
/// | Dropdown | 建置dropdown
///
/// {btnId = 按鈕element Id ,dropdownId = 下拉選單 element Id}
/// [{id = input element id , name = input element name, type = input element type, other = input element other attr, parent = sub parent element id }]
$.fn.SetDropDown = function (eleObj, divObj) {
let btnEle = $("#" + eleObj.btnId);
let strHtml = ``;
btnEle.wrap("
");
strHtml += `
`;
$.each(divObj, function (index, value) {
strHtml += `
`
})
btnEle.parent("div").append(strHtml);
$("#" + eleObj.dropdownId).find(".dropdown-item-checkbox input:checked").trigger("click", "init");
}
Array.prototype.Distinct = function () {
return this.filter((value, index, self) => { return self.indexOf(value) === index; });
}
Array.prototype.DistinctBy = function (...otherCol) {
const result = [];
$.each(this, function (index, value) {
let filInd = result.findIndex(function (v, i) {
let sameNum = 0;
$.each(otherCol, function (i2, v2) {
if (v[v2] == value[v2]) {
sameNum++;
}
})
return sameNum == otherCol.length ? true : false;
})
if (filInd == -1) {
result.push(value);
}
})
return result;
}
BigInt.prototype.toJSON = function () { return this.toString() }
$.fn.classList = function () { return this[0].className.split(/\s+/); };
$.fn.replaceClass = function (oriClass, newClass) { $(this).removeClass(oriClass).addClass(newClass); return $(this) };
//阿拉伯數字轉中文
Number.prototype.toChinese = function () {
let chnNumChar = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
let chnUnitSection = ["", "萬", "億", "萬億", "億億"];
let chnUnitChar = ["", "十", "百", "千"];
let strIns = '', chnStr = '';
let unitPos = 0;
let section = this;
let zero = true;
while (section > 0) {
let v = section % 10;
if (v === 0) {
if (!zero) {
zero = true;
chnStr = chnNumChar[v] + chnStr;
}
} else {
zero = false;
if (unitPos == 0 || (unitPos == 1 && section > 1)) {
strIns = chnNumChar[v];
} else {
strIns = "";
}
strIns += chnUnitChar[unitPos];
chnStr = strIns + chnStr;
}
unitPos++;
section = Math.floor(section / 10);
}
return chnStr;
}
$(function () {
initTableEvent();
initddEleMargin();
select2bs4();
Date_Pic();
dataReadAttrbuite();
})
imgUploadFormat();
setupSltAddress();
jquValAddMethod();
YT.Math.Random = function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
///
/// Jquery validation add rule, select2 required.
///
function jquValAddMethod() {
if ($.validator) {
$.validator.addMethod("requiredSelect", function (value, element) {
let selVal = $(element).find(`option:selected`).val();
let selText = $(element).find(`option:selected`).text();
if (selVal == 0 || selText.indexOf("無") != -1) {
return false;
}
return true;
}, "必須選擇")
$.validator.addMethod("requiredCheckbox", function (value, element) {
if ($(element).find("input:checkbox:checked").length == 0) {
return false;
}
return true;
}, "必須選擇")
}
}
///
/// Jquery validation form reValid on select2 change.
///
$("body").on("change", ".select2bs4.error,.select2bs4.valid", function () {
$(this).parents("form").valid();
})
///
/// Html tag convert to HTML ASCII(Encode)
///
/// Html tag
function HtmlEncode(str) {
let encodedStr = str.replace(/[\u0000-\u9999<>\&]/gim, function (i) {
return '' + i.charCodeAt(0) + ';';
});
return encodedStr;
}
function SignEncode(str) {
str = str.replace(/[\u0022\u0027]/gim, function (i) {
return '' + i.charCodeAt(0) + ';';
})
return str;
}
///
/// login Tab class active切換
///
$("body").on("click", ".card ul.card-tab li.card-tab-option", function () {
$(".card ul.card-tab li.card-tab-option").removeClass("active");
$(this).addClass("active");
})
///
/// 判斷照片div裡是否有主圖,無主圖自動把第一張設為主圖
///
/// div element Id
function isMasterImgExist(target) {
if ($(target).find("input[type=radio]:checked").length == 0) {
$(target).find("input[type=radio]:eq(0)").prop("checked", true);
}
}
///
/// 複製文字/網址
///
/// element Id
function CopyUrlBtn(target, callback) {
let $temp = $("");
$("body").append($temp);
$temp.val($(target).text()).select();
document.execCommand("copy");
$temp.remove();
callback ? callback() : "";
}
///
/// 驗證解除
///
/// element Id
/// 下拉選單div
function closeValidate(target, selDivArr) {
let selDivStr = '';
if (Object.keys($(target).validate().settings.rules).length != 0) {
if (selDivArr != undefined && selDivArr != null) {
selDivStr = selDivArr.toString();
$(selDivStr).rules("remove", "SelRequire");
$(selDivStr).find("select").unbind();
$(selDivStr).removeClass("error");
}
$("[aria-describedby^=tooltip]").tooltip("dispose");
$(target).validate().resetForm();
}
}
///
/// 重新驗證
///
/// element Id
/// 下拉選單div
function resetValidate(target, selDivArr, validate) {
closeValidate(target, selDivArr);
validate();
$(target).valid();
}
///
/// 價錢呈現統一
///
/// 價格
function AmtFormat(Amt) {
let type = 1; // 0: parseInt(整數) , 1: parseFloat(小數點0省略) ,2: toFixed (小數點強制取位數-四捨五入)
let maxFixed = 2; //取小數點後幾位
let result; //輸出
if (Amt === null) {
return null;
}
Amt = Amt || 0;
if (type == 0) {
result = parseInt(Amt);
} else if (type == 1) {
result = parseFloat(Amt);
} else if (type == 2) {
result = parseFloat(Amt).toFixed(maxFixed);
}
return result
}
///
/// 時間格式統一
///
/// 欲轉換格式之日期時間
/// 需顯示的年月日時分秒毫秒,Y=年、M=月、d=日、H=時、m=分、s=秒、S=毫秒
/// 時區
function displayDate(dateTime, dateType = "YMdHms", locale = 'zh-TW') {
let result = '';
if (dateTime) {
let regex = /^\/Date\((\d+)\)\/$/gm;
let t = Date.parse(dateTime); //若從資料庫回傳 /Date(xxxxxxxxxxxxxx)/ DateTime格式
if (regex.test(dateTime)) {
t = parseInt(dateTime.replace(regex, '$1'));
}
//不符合時間格式
if (isNaN(t)) {
return null;
}
let options =
{
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: "3",
hourCycle: "h23",
}
let d = new Date(t).toLocaleString(locale, options);
d = new Date(d);
let year = '', month = '', day = '', hour = '', minute = '', second = '', millisecond = '', date = '', time = '';
if (dateType != "date" && dateType != "time" && dateType != "datetime") {
dateType.indexOf("Y") != -1 ? year = parseInt(d.getFullYear()) : "";
dateType.indexOf("M") != -1 ? month = parseInt(d.getMonth() + 1) : "";
dateType.indexOf("d") != -1 ? day = parseInt(d.getDate()) : "";
dateType.indexOf("H") != -1 ? hour = parseInt(d.getHours()) : "";
dateType.indexOf("m") != -1 ? minute = parseInt(d.getMinutes()) : "";
dateType.indexOf("s") != -1 ? second = parseInt(d.getSeconds()) : "";
dateType.indexOf("S") != -1 ? millisecond = parseInt(d.getMilliseconds()) : "";
} else if (dateType == "date") {
year = d.getFullYear();
month = String(d.getMonth() + 1).padStart(2, '0');
day = String(d.getDate()).padStart(2, '0');
} else if (dateType == "time") {
hour = String(d.getHours()).padStart(2, '0');
minute = String(d.getMinutes()).padStart(2, '0');
} else if (dateType == "datetime") {
year = d.getFullYear();
month = String(d.getMonth() + 1).padStart(2, '0');
day = String(d.getDate()).padStart(2, '0');
hour = String(d.getHours()).padStart(2, '0');
minute = String(d.getMinutes()).padStart(2, '0');
}
date = [year, month, day].filter(n => n).join("/");
time = [hour, minute, second, millisecond].filter(n => n).join(":");
result = date.toString() + " " + time.toString();
if (dateType == "date") {
result = date.toString();
} else if (dateType == "time") {
result = time.toString();
}
}
return $.trim(result);
}
///
/// datatable event 初始化
///
function initTableEvent() {
let windowScrollTop = 0, tableScrollTop = 0;
//排序event
if ($.fn.dataTable != undefined && $.fn.dataTable != null) {
if ($.fn.dataTable.tables(true).length != 0) { //若頁面有datatable
let table = '';
$($.fn.dataTable.tables(true)).each(function (index, value) {
table = $(value).DataTable();
let tableId = table.context[0].sTableId;
tabVis(table);
$(value).on("order.dt", function () {
$(".popover").remove(); //popover清空
}).DataTable()
$(value).on("preDraw.dt", function () {
tableScrollTop = $(`#${tableId}_wrapper .dataTables_scrollBody`).scrollTop();
windowScrollTop = $(window).scrollTop();
}).DataTable()
$(value).on("draw.dt", function () {
table.columns.adjust();
$(window).scrollTop(windowScrollTop);
$(`#${tableId}_wrapper .dataTables_scrollBody`).scrollTop(tableScrollTop);
loadDtSearchCol(table);
loadSesSearchCol();
loadTabChk(tableId);
tableHeadChkNotSort(tableId); //若head有checkbox,強制不sorting
}).DataTable()
dtReloadFn = (data) => {
$(`#${tableId}_wrapper .dataTables_scrollBody`).scrollTop(tableScrollTop);
$(window).scrollTop(windowScrollTop);
ajaxReloadCallBack != undefined && ajaxReloadCallBack != null ? ajaxReloadCallBack() : "";
}
})
table.columns.adjust();
}
}
}
///
/// jquery loaded 事件
///
function loadCallback(callback) {
select2bs4();
Date_Pic();
dataReadAttrbuite();
callback ? callback() : "";
initCkeditor();
}
///
/// dropdown aria-close 按下不消失dropdown
///
$("body").on("click", ".dropdown-menu", function (e) {
let eleId = $(this)[0].id;
let eleLen = 0;
if (eleId) {
eleLen = $(`[data-target='${eleId}'][data-toggle='dropdown'][aria-close='false']`).length;
} else {
eleLen = $(this).prevAll("button[data-toggle='dropdown'][aria-close='false']").length
}
if (eleLen != 0) {
e.stopPropagation();
}
})
///
/// | Dropdown | 該parent底下sub element沒有勾選時,預設選擇下一個parent element
///
/// dropdown sub input element
function ddSubEmptyCha(obj) {
let ddmenu = $(obj).parents(".dropdown-menu");
let parentId = $(obj).data("parent");
let chklen = ddmenu.find(`.dropdown-item-sub .dropdown-item-input[data-parent=${parentId}]:checked`).length;
if (chklen != 0) {
$("#" + parentId).prop("checked", true);
} else {
let chkRadioId = ddmenu.find(".dropdown-item-checkbox input[type=radio]:checked")[0].id;
$("#" + parentId).prop("checked", false);
if (ddmenu.find(`.dropdown-item-sub .dropdown-item-input[data-parent=${chkRadioId}]`).length != 0) {
if (ddmenu.find(`.dropdown-item-sub .dropdown-item-input[data-parent=${chkRadioId}]:checked`).length == 0) {
$(obj).prop("checked", true).change();
}
}
}
}
///
/// | Dropdown | 選擇sub element時
///
$("body").on("change click", ".dropdown-item-sub .dropdown-item-input", function () {
$(this).prop("checked", true);
//ddSubEmptyCha(this);
otherSubCha(this);
subSubCha(this);
subChkParentCha(this);
ddSelectItemChaName(this);
})
///
/// | Dropdown | 選擇篩選下拉選單項目改變按鈕名稱
///
/// dropdown input element
function ddSelectItemChaName(obj) {
let result = '';
result = $(obj).next("label").text();
//let ddmenu = $(obj).parents(".dropdown-menu");
//ddmenu.find(".dropdown-item-checkbox:not(.dropdown-item-sub) input:checked").each(function (index, value) {
// reuslt = $(value).next("label").text();
//})
$(obj).parents(".dropdown-menu").prev("button").text(result);
}
///
/// | Dropdown | 選擇parent項目 該parent底下sub項目一起勾選,若勾選沒有sub的parent項目,其他sub取消勾選
///
/// dropdown input element
function parentSubCha(obj) {
let ddmenu = $(obj).parents(".dropdown-menu");
if ($(obj).prop("checked") == true) { //該(parent)element 被勾選後
if (ddmenu.find(`.dropdown-item-sub input[data-parent=${$(obj)[0].id}]`).length != 0) { //判斷底下若有sub element
ddmenu.find(`.dropdown-item-sub input[data-parent=${$(obj)[0].id}]`).prop("checked", true); //勾選底下所有sub element
ddmenu.find(`.dropdown-item-sub input[data-parent=${$(obj)[0].id}]`).each(function (index, value) {
subSubCha("#" + $(value)[0].id);
})
} else { //判斷底下若沒有sub element
ddmenu.find(`.dropdown-item-sub input`).not(obj).prop("checked", false); //其他sub element 取消勾選
}
}
}
///
/// | Dropdown | 選擇sub parent項目 該sub parent底下sub項目一起勾選,若勾選沒有sub的sub parent項目,其他sub取消勾選
///
/// dropdown input element
function subSubCha(obj) {
let ddmenu = $(obj).parents(".dropdown-menu");
if ($(obj).prop("checked") == true) { //該(sub)element 被勾選後
if (ddmenu.find(`.dropdown-item-sub input[data-parent=${$(obj)[0].id}]`).length != 0) { //判斷底下若有sub element
ddmenu.find(`.dropdown-item-sub input[data-parent=${$(obj)[0].id}]`).prop("checked", true); //勾選底下所有sub element
}
} else { //該(sub)element 取消勾選後
if (ddmenu.find(`.dropdown-item-sub input[data-parent=${$(obj)[0].id}]`).length != 0) { //判斷底下若有sub element
ddmenu.find(`.dropdown-item-sub input[data-parent=${$(obj)[0].id}]`).prop("checked", false); //取消勾選底下所有sub element
}
}
}
///
/// | Dropdown | 選擇其中一sub項目 其他sub項目取消勾選
///
/// dropdown input element
function otherSubCha(obj) {
let ddmenu = $(obj).parents(".dropdown-menu");
let parentId = $(obj).data("parent");
ddmenu.find(`.dropdown-item-checkbox.dropdown-item-sub .dropdown-item-input`).not(obj).prop("checked", false);
}
///
/// | Dropdown | 選擇其中一sub項目 該sub parent勾選
///
/// dropdown input element
function subChkParentCha(obj) {
let parentId = $(obj).data("parent");
if ($(obj).prop("checked") == true) {
$("#" + parentId).prop("checked", true);
}
}
///
/// | Dropdown | 選擇parent element時
///
$("body").on("change click", ".dropdown-item-checkbox:not(.dropdown-item-sub) .dropdown-item-input", function () {
ddSelectItemChaName(this);
parentSubCha(this);
})
///
/// | Dropdown | 初始化 parent sub element margin
///
function initddEleMargin() {
$(".sort-dropdown .dropdown-item-checkbox:not(.dropdown-item-sub) .dropdown-item-input").each(function (index, value) {
let eleId = $(value)[0].id;
setddEleMargin(eleId, 0);
})
}
///
/// | Dropdown | set parent sub element margin
///
/// dropdown input element
/// input element css margin
function setddEleMargin(eleId, margin = 0) {
let subEle = $(`.sort-dropdown .dropdown-item-checkbox.dropdown-item-sub .dropdown-item-input[data-parent=${eleId}]`);
let subId = ``;
margin += 20;
$.each(subEle, function (index, value) {
subId = $(value)[0].id;
$(value).parent(".dropdown-item-checkbox").css("margin-left", margin + "px");
setddEleMargin(subId, margin);
})
}
///
/// | table Filter | filter tag close icon on the datatable top (以datatable搜尋)
///
$("body").on("click", ".tag-label-close[data-type='dt']", function () {
let table = $($.fn.dataTable.tables(true)).DataTable();
let id = $(this)[0].id;
let name = $(this).data("name");
$(this).parent(".tag-label").remove();
if (table) {
closeDtSearchCol(table, id, name); //欄位搜尋清除
}
})
///
/// | table Filter | filter tag close icon on the datatable top (以session傳值搜尋(尚未用到))
///
$("body").on("click", ".tag-label-close[data-type='ses']", function () {
let table = $($.fn.dataTable.tables(true)).DataTable();
let name = $(this).parent(".tag-label")[0].id.split("tagLabel_")[1].split("_")[0];
let sesName = window.location.pathname + "_" + name;
$(this).parent(".tag-label").remove();
if (table) {
closeSesSearchCol(table, sesName, $(this).parent("label"));
}
})
///
/// | table Filter | dropdown item on the datatable top
///
$("body").on("click", ".dataTables_wrapper .toolbar .dropdown-item-checkbox input", function (e, type) {
let tableId = $(this).parents(".dataTables_wrapper")[0].id.split("_wrapper")[0];
if (type != "init") { //除了初始化以外,篩選過後頁面跳回至第1頁
$.each($("#" + tableId).DataTable().context[0].aoPreSearchCols, function (index, value) {
if (value.sSearch != '') {
$("#" + tableId).DataTable().column(index).search('');
}
})
$("#" + tableId).DataTable().page(0);
}
$("#" + tableId).DataTable().ajax.reload(null, false);
})
///
/// | table Filter | Load Datatable exists searching column.
///
/// executed datatable
function loadDtSearchCol(dt) {
$.each(dt.context[0].aoPreSearchCols, function (index, value) {
let id = "dtSearch_" + index;
if (value.sSearch != '') {
if ($(`.dataTables_wrapper > .selector .tag-label:contains(${value.sSearch})`).length == 0) {
let data = dt.context[0].aoColumns[index].data;
let title = setDtSearchTitle(dt, index, value)
let btnTemp = `
`;
$(".dataTables_wrapper > .selector").append(btnTemp);
}
} else {
if ($("#" + id).length != 0) {
$("#" + id).click();
}
}
})
}
///
/// | table Filter | Set Datatable filter tag title on table top
///
/// executed datatable
/// SearchCol index
/// SearchCol value
function setDtSearchTitle(dt, index, value) {
let title = dt.context[0].aoColumns[index].filterName ?? dt.context[0].aoColumns[index].title;
let search = value.sSearch;
let filterName = dt.context[0].aoColumns[index].filterName ?? "";
if (filterName.indexOf("__TITLE__") != -1 || filterName.indexOf("__VALUE__") != -1) {
filterName = filterName.replace("__TITLE__", title);
filterName = filterName.replace("__VALUE__", search);
return filterName
} else {
return title + " : " + search;
}
}
///
/// | table Filter | Set "dtSearchTitleParam" variable, used to set Datatable filter title.
///
/// paramter string
function setDtSearchTitleParam(colName, param) {
param != null ? dtSearchTitleParam.push({ "name": colName, "text": param }) : "";
}
///
/// | table Filter | Cleaning Datatable search column when click filter tag icon.
///
/// executed Datatable
/// closeing filter icon element Id
function closeDtSearchCol(dt, id, name) {
let col = id.indexOf("dtSearch_") != -1 ? id.split("dtSearch_")[1] : "";
sessionStorage.removeItem(name);
localStorage.removeItem(name);
dt.column(col).search('').draw(false);
}
///
/// | table Filter | Load Datatable exists searching column (Session variable).
///
function loadSesSearchCol() {
$.each(Object.keys(sessionStorage), function (index, value) {
if (value.indexOf(window.location.pathname) != -1) {
let result = JSON.parse(Object.values(sessionStorage)[index]);
let btnTemp = ``;
$(".dataTables_wrapper > .selector").append(btnTemp);
}
})
}
///
/// | table Filter | Cleaning Datatable search column when click filter tag icon (Session variable).
///
/// executed Datatable
/// session name
/// tag label element
function closeSesSearchCol(dt, name, obj) {
sessionStorage.removeItem(name);
obj.remove();
dt.ajax.reload(dtReloadFn, false);
}
function tabVis(dt) {
let columnArr = dt.context[0].aoColumns;
let strHtml = ``;
$.each(columnArr, function (index, value) {
strHtml += `
`;
})
$("#table_filter").append(`
${strHtml}
`)
$("body").on("change", "input[id^=tabVis]", function () {
let idx = $(this).data("idx");
let chk = $(this).prop("checked");
dt.columns(idx).visible(chk);
dt.columns.adjust();
})
}
var tabChkArr = [];
function tableHeadChkNotSort(tabId) {
$(`#${tabId} thead input:checkbox`).each(function (index, value) {
$(value).parents("th").removeClass("sorting_asc");
$(value).parents("th").removeClass("sorting_desc");
})
}
function loadTabChk(tabId) {
$(`#${tabId}_wrapper thead tr th input:checkbox`).prop("checked", false);
$.each(tabChkArr, function (index, value) {
$(`${tabId} tbody tr td input:checkbox[data-rowid=${value.rowId}]`).prop("checked", true).change();
})
}
///
/// | Sidebar | User headshot css adjusts on sidebar collapsing.
///
$("html").on("mouseover", "body.sidebar-collapse .main-sidebar", function () {
$(this).find(".logo-link").css("width", "250px").css("overflow", "visible");
$(this).find(".logo-link img").css("left", "0px");
$(this).find(".user-panel .info").show();
}).on("mouseleave", "body.sidebar-collapse .main-sidebar", function () {
$(this).find(".logo-link").css("width", "37px").css("overflow", "hidden").css("margin", "auto");
$(this).find(".logo-link img").css("left", "-16px");
$(this).find(".user-panel .info").hide();
})
///
/// | Sidebar | User headshot css adjusts on sidebar collapsing.
///
$("body").on("click", ".nav-link[data-widget=pushmenu]", function () {
let obj = $(this).parents("body").find(".main-sidebar");
if ($(this).parents("body").hasClass("sidebar-collapse")) {
obj.find(".logo-link").css("width", "250px").css("overflow", "visible")
obj.find(".logo-link img").css("left", "0px");
obj.find(".user-panel .info").show();
} else {
obj.find(".logo-link").css("width", "37px").css("overflow", "hidden").css("margin", "auto");
obj.find(".logo-link img").css("left", "-16px");
obj.find(".user-panel .info").hide();
}
})
///
/// Set bootstrap modal and show
///
/// warning, error ,success
/// modal div element id
/// modal header h4 tag title
/// modal body content
/// modal foot button
function ShowModal(type = null, id, title, content, btnArr) {
let btnHtml = ``, titleHtml = ``, conHtml = ``;
//foot按鈕
if ($.isArray(btnArr) == true) {
$.each(btnArr, (i, v) => {
if (typeof v == "object") {
let strData = '';
if (v.dataArr) {
$.each(v.dataArr, function (index, value) {
strData += "data-" + value.key + "=" + value.value;
})
}
btnHtml += ``;
}
})
} else {
btnHtml = ``;
}
//header title
if (typeof title == "object") {
titleHtml += `