admin.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. ko.bindingHandlers.date = {
  2. init: function (element, valueAccessor, bindings) {
  3. ko.bindingHandlers.date._update(element, valueAccessor, bindings);
  4. },
  5. update: function (element, valueAccessor, bindings) {
  6. ko.bindingHandlers.date._update(element, valueAccessor, bindings);
  7. },
  8. _update: function (element, valueAccessor, bindings) {
  9. var value = ko.unwrap(valueAccessor());
  10. if (value) {
  11. var format = bindings.get('format');
  12. $(element).html(moment(value * 1000).format(format || 'YYYY-MM-DD'));
  13. } else {
  14. $(element).html('');
  15. }
  16. }
  17. };
  18. ko.bindingHandlers.datetimepicker = {
  19. init: function (element, valueAccessor, bindings) {
  20. var options = {
  21. format: 'YYYY-MM-DD HH:mm',
  22. sideBySide: true
  23. };
  24. if (bindings.has('datetimepickerOptions')) {
  25. options = _.assign(options, ko.unwrap(bindings.get('datetimepickerOptions')));
  26. }
  27. var date = ko.unwrap(valueAccessor());
  28. if (date) {
  29. options.defaultDate = date;
  30. }
  31. $(element).datetimepicker(options);
  32. $(element).on('dp.change', function (e) {
  33. valueAccessor()(e.date.format(options.format));
  34. });
  35. },
  36. update: function (element, valueAccessor) {
  37. var date = ko.unwrap(valueAccessor());
  38. if (date) {
  39. $(element).data('DateTimePicker').date(date);
  40. }
  41. }
  42. };
  43. ko.bindingHandlers.price = {
  44. update: function (element, valueAccess) {
  45. var value = ko.unwrap(valueAccess());
  46. if (value === null || value === undefined) {
  47. $(element).html('');
  48. } else {
  49. $(element).html(numeral(value / 100).format('0,0.00'));
  50. }
  51. }
  52. };
  53. ko.bindingHandlers.integer = {
  54. update: function (element, valueAccessor) {
  55. var value = ko.unwrap(valueAccessor());
  56. $(element).html(numeral(value).format('0,0'));
  57. }
  58. };
  59. ko.bindingHandlers.select2 = {
  60. init: function (element, valueAccessor, allBindingsAccessor) {
  61. $(element).select2(ko.unwrap(valueAccessor()));
  62. var allBindings = allBindingsAccessor();
  63. if (allBindings.value) {
  64. $(element).val(allBindings.value());
  65. }
  66. }
  67. };
  68. function scrollToElement(element, options, callback) {
  69. options = _.assign({}, { duration: 200, offset: 0 }, options);
  70. $('html,body').animate({ scrollTop: $(element).offset().top - options.offset }, options.duration, callback);
  71. }
  72. function parseQueryString() {
  73. if (!location.search || location.search.length === 1) {
  74. return {};
  75. }
  76. var pairs = location.search.substr(1).split('&');
  77. var qs = { };
  78. _.each(pairs, function (pair) {
  79. var parts = pair.split('=');
  80. qs[parts[0]] = decodeURIComponent(parts[1]);
  81. });
  82. return qs;
  83. }
  84. function buildQueryString(data) {
  85. var qs = _.chain(data)
  86. .map(function (val, key) {
  87. return key + '=' + encodeURIComponent(val);
  88. })
  89. .value()
  90. .join('&');
  91. return qs ? '?' + qs : null;
  92. }
  93. function handleAjaxError(xhr) {
  94. var error = JSON.parse(xhr.responseText);
  95. alert(error.message);
  96. }
  97. function reloadPage(delay) {
  98. delay = delay || 0;
  99. setTimeout(function () {
  100. location.href = location.pathname + location.search;
  101. }, delay);
  102. }
  103. function plainTextToHtml(text) {
  104. if (!text) {
  105. return text;
  106. }
  107. // urls to hyper links
  108. text = text.replace(/((http|https):\/\/[^\s]+)/g, function (url) {
  109. return '<a href="' + url + '" target="_blank">' + url + '</a>';
  110. });
  111. // line breaks to <br/>
  112. text = text.replace(/\n/g, '<br/>');
  113. return text;
  114. }
  115. // Modal
  116. var Modal = function () {
  117. var self = this;
  118. var id = null;
  119. var opts = null;
  120. var template =
  121. '<div class="modal fade" id="' + id + '">' +
  122. '<div class="modal-dialog">' +
  123. '<div class="modal-content">' +
  124. '<div class="modal-header" data-bind="visible: title">' +
  125. '<button type="button" class="close" data-bind="visible: showCloseButton, click: close"><span aria-hidden="true">&times;</span></button>' +
  126. '<h4 class="modal-title" data-bind="html: title"></h4>' +
  127. '</div>' +
  128. '<div class="modal-body" data-bind="html: body"></div>' +
  129. '<div class="modal-footer">' +
  130. '<!-- ko foreach: buttons -->' +
  131. '<button type="button" data-bind="attr: { \'id\': id, \'class\': \'btn \' + className }, html: text, click: $parent.onButtonClick"></button>' +
  132. '<!-- /ko -->' +
  133. '</div>' +
  134. '</div>' +
  135. '</div>' +
  136. '</div>';
  137. var defer = null;
  138. var model = null;
  139. self.$modal = function () {
  140. return $('#' + id);
  141. };
  142. self.defer = function () {
  143. return defer;
  144. };
  145. self.open = function (options) {
  146. opts = options;
  147. if (options && options.buttons) {
  148. $.each(options.buttons, function () {
  149. if (!this.id) {
  150. this.id = '__btn_' + new Date().getTime() + Math.floor(Math.random() * 1000);
  151. }
  152. if (!this.className) {
  153. this.className = 'btn-default';
  154. }
  155. })
  156. }
  157. model = {
  158. title: ko.observable(options.title),
  159. body: ko.observable(options.body),
  160. showCloseButton: ko.observable(true),
  161. buttons: ko.observableArray(options.buttons),
  162. close: function () {
  163. self.close();
  164. },
  165. onButtonClick: function (button, e) {
  166. if (button.click) {
  167. button.click.apply(self, [e]);
  168. }
  169. }
  170. };
  171. if (options.showCloseButton !== undefined) {
  172. model.showCloseButton(options.showCloseButton);
  173. }
  174. id = '__modal_' + new Date().getTime();
  175. $(document.body).append($(template).attr('id', id));
  176. ko.applyBindings(model, document.getElementById(id));
  177. var $modal = $('#' + id);
  178. if (options) {
  179. $modal.modal(options);
  180. }
  181. $modal.on('shown.bs.modal', function () {
  182. _.each(options.buttons, function (button) {
  183. if (button.clipboard) {
  184. var clipboard = new Clipboard('#' + button.id, button.clipboard);
  185. if (button.clipboard.success) {
  186. clipboard.on('success', button.clipboard.success.bind(self));
  187. }
  188. }
  189. });
  190. if (opts.callbacks && opts.callbacks.shown) {
  191. opts.callbacks.shown.apply(self);
  192. }
  193. });
  194. self.resize();
  195. $modal.modal('show');
  196. defer = $.Deferred();
  197. return defer.promise();
  198. };
  199. self.resize = function () {
  200. var winHeight = $(window).height();
  201. $('#' + id)
  202. .find('.modal-body')
  203. .css('max-height', Math.round(winHeight * 0.7) + 'px')
  204. .css('overflow', 'auto');
  205. };
  206. self.close = function (options) {
  207. var $modal = $('#' + id);
  208. $modal.modal('hide');
  209. $modal.on('hidden.bs.modal', function () {
  210. $modal.remove();
  211. });
  212. if (opts.callbacks && opts.callbacks.close) {
  213. opts.callbacks.close.apply(self);
  214. }
  215. if (options && options.reject) {
  216. defer.reject();
  217. } else {
  218. defer.resolve();
  219. }
  220. };
  221. };
  222. Modal.instance = new Modal();
  223. Modal.open = function (options) {
  224. return Modal.instance.open(options);
  225. };
  226. Modal.alert = function (options) {
  227. return Modal.instance.open({
  228. title: options.title,
  229. body: options.message,
  230. showCloseButton: false,
  231. buttons: options.buttons || [
  232. {
  233. 'className': 'btn-primary',
  234. 'text': '确定',
  235. 'click': function () {
  236. this.close();
  237. }
  238. }
  239. ]
  240. })
  241. };
  242. Modal.confirm = function (options) {
  243. return Modal.instance.open({
  244. title: options.title,
  245. body: '<div class="modal-confirm-message">' + options.message + '</div>',
  246. showCloseButton: false,
  247. buttons: [
  248. {
  249. 'className': 'btn-default',
  250. 'text': '取消',
  251. 'click': function () {
  252. this.close({ reject: true });
  253. }
  254. },
  255. {
  256. 'className': 'btn-primary',
  257. 'text': '确定',
  258. 'click': function () {
  259. this.close();
  260. }
  261. }
  262. ]
  263. })
  264. };
  265. var DateRangePicker = function (element) {
  266. var self = this;
  267. var $element = $(element);
  268. this.init = function () {
  269. $element.data('DateRangePicker', self);
  270. $element.find('.from-date-picker').datetimepicker({ format: 'YYYY-MM-DD' });
  271. $element.find('.to-date-picker').datetimepicker({ format: 'YYYY-MM-DD' });
  272. };
  273. this.value = function (value) {
  274. if (arguments.length === 0) {
  275. return {
  276. 'from': $element.find('.from-date-picker :text').val(),
  277. 'to': $element.find('.to-date-picker :text').val()
  278. };
  279. } else {
  280. $element.find('.from-date-picker').data('DateTimePicker').date(value.from);
  281. $element.find('.to-date-picker').data('DateTimePicker').date(value.to);
  282. }
  283. };
  284. this.timespan = function () {
  285. var range = self.value();
  286. return new Date(range.to).getTime() + 24 * 60 * 60 * 1000 - new Date(range.from).getTime();
  287. }
  288. };
  289. DateRangePicker.create = function (element) {
  290. var picker = new DateRangePicker(element);
  291. picker.init();
  292. return picker;
  293. };
  294. // UI Component
  295. $(function () {
  296. var UIComponent = window.UIComponent = {
  297. init: function (container) {
  298. var $container = $(container);
  299. var $elements = null;
  300. if ($container.data('ui')) {
  301. $elements = $container;
  302. } else {
  303. $elements = $container.find('[data-ui]');
  304. }
  305. var groups = {};
  306. $elements.each(function () {
  307. var $element = $(this);
  308. var componentName = $element.data('ui');
  309. if (!groups[componentName]) {
  310. groups[componentName] = [];
  311. }
  312. groups[componentName].push($element);
  313. });
  314. _.each(_.keys(groups), function (name) {
  315. var handler = UIComponent.handlers[name];
  316. if (handler) {
  317. handler.init(groups[name]);
  318. }
  319. });
  320. }
  321. };
  322. UIComponent.handlers = {};
  323. UIComponent.handlers['inline-user-info'] = {
  324. init: function ($elements) {
  325. var ids = _.map($elements, function ($element) {
  326. return $element.data('uid');
  327. });
  328. ids = _.filter(_.uniq(ids), function (id) { return !!id; });
  329. if (ids.length === 0) {
  330. return;
  331. }
  332. $.get('/backend/users/api_get_user_infos', {ids: ids.join(',')}, function (result) {
  333. _.each($elements, function ($element) {
  334. var uid = $element.data('uid');
  335. var user = result[uid];
  336. if (!user) {
  337. return;
  338. }
  339. $element.html('<span>' + user.nickname + '</span>');
  340. if ($element[0].tagName === 'A') {
  341. UIComponent.handlers['user-info-popover'].init([$element]);
  342. }
  343. });
  344. });
  345. }
  346. };
  347. UIComponent.handlers['user-info-popover'] = {
  348. init: function ($elements) {
  349. var buildHtmlRow = function (label, content) {
  350. return '<div class="form-group" style="margin-bottom:0">' +
  351. '<label class="control-label col-sm-4">' + label + '</label>' +
  352. '<div class="col-sm-8 no-padding-left"><div class="form-control-static">' + content + '</div></div>' +
  353. '</div>';
  354. };
  355. _.each($elements, function ($element) {
  356. var uid = $element.data('uid');
  357. if (!uid) {
  358. return;
  359. }
  360. $element.css('cursor', 'pointer');
  361. $element.webuiPopover({
  362. title: null,
  363. trigger: 'hover',
  364. delay: {
  365. show: 300
  366. },
  367. width: 350,
  368. type: 'async',
  369. url: '/backend/users/api_get_user_popover_info/' + uid,
  370. content: function (data) {
  371. var html =
  372. '<div class="form-horizontal">' +
  373. buildHtmlRow('用户名', data.username) +
  374. buildHtmlRow('昵称', data.nickname);
  375. var mp = null;
  376. if (data.type === 'agent') {
  377. html += buildHtmlRow('所属渠道', data.channel.nickname);
  378. mp = data.channel.mp;
  379. } else {
  380. mp = data.mp;
  381. }
  382. if (data.type === 'channel' || data.type === 'agent') {
  383. if (mp) {
  384. html += buildHtmlRow('渠道公众号',
  385. '<img style="width:100px;border:#eee 1px solid;" src="//open.weixin.qq.com/qr/code/?username=' + mp.raw_id + '"/>' +
  386. '<div style="margin-top:5px">' + mp.nickname + '</div>');
  387. } else {
  388. html += buildHtmlRow('渠道公众号', '未配置');
  389. }
  390. }
  391. html += '</div>';
  392. return html;
  393. }
  394. });
  395. });
  396. }
  397. };
  398. UIComponent.handlers['inline-member-info'] = {
  399. init: function ($elements) {
  400. var ids = _.map($elements, function ($element) {
  401. return $element.data('member-id');
  402. });
  403. ids = _.filter(_.uniq(ids), function (id) { return !!id; });
  404. if (ids.length === 0) {
  405. return;
  406. }
  407. $.get('/backend/members/api_get_member_infos', { ids: ids.join(',') }, function (result) {
  408. _.each($elements, function ($element) {
  409. var memberId = $element.data('member-id');
  410. var member = result[memberId];
  411. if (member) {
  412. var html = '';
  413. if (member.headimgurl) {
  414. html += '<img style="width:18px;margin-right:5px" src="' + member.headimgurl + '"/>'
  415. }
  416. html += '<span>' + member.nickname + '</span>';
  417. if (member.is_vip) {
  418. var now = Math.round(new Date().getTime() / 1000);
  419. var expiryTimeText = moment(member.vip_expiry_time * 1000).format('YYYY-MM-DD HH:mm:ss') + ' 过期';
  420. if (member.vip_expiry_time > now) {
  421. html += ' <i class="fa fa-diamond" style="color:goldenrod" title="' + expiryTimeText + '"></i>';
  422. } else {
  423. html += ' <i class="fa fa-diamond" style="color:#aaa" title="已于 ' + expiryTimeText + '"></i>';
  424. }
  425. }
  426. $element.html(html);
  427. }
  428. });
  429. });
  430. }
  431. };
  432. UIComponent.handlers['table-sort'] = {
  433. init: function ($elements) {
  434. var qs = parseQueryString();
  435. _.each($elements, function ($element) {
  436. $element.css('cursor', 'pointer');
  437. $element.attr('title', '点击排序');
  438. $element.append('<i class="fa table-sort-icon" style="display:none"></i>');
  439. var $icon = $element.find('.table-sort-icon');
  440. var field = $element.data('field');
  441. var startDir = $element.data('start-dir') || 'asc';
  442. var orderBy = qs.order_by ? parseOrderBy(qs.order_by) : null;
  443. // update icon status from query string
  444. if (orderBy && orderBy.field === field) {
  445. if (orderBy.dir === 'asc') {
  446. $icon.removeClass('fa-caret-down').addClass('fa-caret-up');
  447. } else {
  448. $icon.removeClass('fa-caret-up').addClass('fa-caret-down');
  449. }
  450. $icon.show();
  451. }
  452. $element.click(function () {
  453. var dir = startDir;
  454. if (orderBy && orderBy.field === field) {
  455. dir = orderBy.dir === 'asc' ? 'desc' : 'asc';
  456. }
  457. var newQs = _.assign({}, qs);
  458. delete newQs.page;
  459. newQs.order_by = field + ' ' + dir;
  460. var search = _.chain(newQs)
  461. .map(function (value, key) {
  462. return key + '=' + encodeURIComponent(value);
  463. })
  464. .value()
  465. .join('&');
  466. location.href = location.pathname + '?' + search;
  467. });
  468. });
  469. function parseOrderBy(value) {
  470. if (!value) {
  471. return null;
  472. }
  473. var parts = value.split(' ');
  474. if (parts.length === 1) {
  475. return { field: parts[0], dir: 'asc' };
  476. }
  477. return { field: parts[0], dir: parts[1] };
  478. }
  479. }
  480. };
  481. UIComponent.init(document.body);
  482. });