'use strict'; /** * * * @author Mai * @date 2018/10/15 * @version */ module.exports = app => { class CategoryValue extends app.BaseService { /** * 构造函数 * * @param {Object} ctx - egg全局变量 * @return {void} */ constructor(ctx) { super(ctx); this.tableName = 'category_value'; } /** * 新增分类值 * * @param categoryId - 分类Id * @param value - 值 * @returns {Promise} * @private */ async _addValue(categoryId, value) { const count = await this.count({cid: categoryId, value: value}); if (count > 0) { throw '该分类下存在相同的值'; } const newValue = { cid: categoryId, value: value, }; const result = await this.transaction.insert(this.tableName, newValue); if (result.affectedRows !== 1) { throw '提交数据失败'; } else { category.id = result.insertId; } category.value = category.value && category.value !== '' ? JSON.parse(category.value) : []; return category; } async _deleteAndUpdateValue(orgValue, newValue) { if (!orgValue || orgValue.length === 0) { return } for (const ov of orgValue) { const nv = _.find(newValue, function (v) { return v.id === orgValue.id; }); if (!nv) { await this.transaction.delete(this.tableName, {id: orgValue.id}); } else if (nv.value !== ov.value) { await this.transaction.update(this.tableName, {id: orgValue.id, value: nv.value}); } } } async setCategoryValue(cid, value) { const orgValue = await this.getAllDataByCondition({ where: {cid: cid} }); const tenders = await this.ctx.service.tender.getList(); this.transaction = await this.db.beginTransaction(); try { // 删除值 & 更新值 await this._deleteAndUpdateValue(orgValue, value); // 新增值 const newValue = value.filter(function (v) { return !v.id; }); for (const nv of newValue) { nv.cid = cid; nv.pid = this.ctx.session.sessionProject.id; const result = await this.transaction.insert(this.tableName, nv); nv.id = result.insertId; } // 更新标段属性 for (const t of tenders) { const category = t.category ? t.category : []; const cate = _.find(t.category, function (c) { return c.cid === cid; }); const tenderValue = cate ? _.find(value, function (v) {return v.id === cate.value;}) : null; if (!tenderValue) { category.push({cid: cid, value: newValue[0].id}); await this.transaction.update(this.service.tender.tableName, { id: t.id, category: JSON.stringify(category), }); } } await this.transaction.commit(); } catch(error) { await this.transaction.rollback(); throw error; } } } return CategoryValue; };