118 lines
3.0 KiB
JavaScript
118 lines
3.0 KiB
JavaScript
import {Router} from 'express'
|
|
import data from '../../../config/china_area'
|
|
import ChinaRegion from '../../models/snoopy/ChinaRegion'
|
|
import ChinaArea from '../../models/snoopy/ChinaArea'
|
|
import getGameShareImage from '../../models/snoopy/GameShareImage'
|
|
import logger from '../../utils/logger'
|
|
|
|
const GameShareImage = getGameShareImage()
|
|
|
|
const router = new Router()
|
|
|
|
/* 获取省市列表, id为地区英文名*/
|
|
router.get('/china_region', async (req, res, next) => {
|
|
try {
|
|
const provinces = await ChinaRegion.find({level: 1})
|
|
const citys = await ChinaRegion.find({level: 2, pinyin: {$ne: null}})
|
|
const result = []
|
|
const map = new Map()
|
|
const pIdx = {}
|
|
for (let i = 0; i < provinces.length; i++) {
|
|
result.push({
|
|
id: provinces[i].pinyin,
|
|
parent: '#',
|
|
text: provinces[i].name,
|
|
children: [],
|
|
})
|
|
map.set(provinces[i]._id, provinces[i])
|
|
|
|
if (!pIdx[provinces[i]._id]) {
|
|
pIdx[provinces[i]._id] = i
|
|
}
|
|
}
|
|
for (const c of citys) {
|
|
if (map.has(c.parent_id)) {
|
|
const pIndex = pIdx[c.parent_id]
|
|
result[pIndex].children.push({
|
|
id: `${map.get(c.parent_id).pinyin}_${c.pinyin}`,
|
|
parent: map.get(c.parent_id).pinyin,
|
|
text: c.name,
|
|
})
|
|
}
|
|
}
|
|
res.json({
|
|
errcode: 0,
|
|
records: result,
|
|
})
|
|
} catch (err) {
|
|
next(err)
|
|
}
|
|
})
|
|
|
|
/* 获取所有定义好的地域列表*/
|
|
router.get('/china_area', async (req, res, next) => {
|
|
try {
|
|
const records = await ChinaArea.find({deleted: false})
|
|
res.json({errcode: 0, records: records})
|
|
} catch (err) {
|
|
next(err)
|
|
}
|
|
})
|
|
|
|
/* 更新*/
|
|
router.post('/china_area', async (req, res, next) => {
|
|
logger.db(req, '公共', '地域', '保存地域')
|
|
const body = req.body
|
|
const id = body.id
|
|
const name = body.name
|
|
const locations = body.locations
|
|
let record
|
|
try {
|
|
if (id) {
|
|
record = await ChinaArea.findById(id)
|
|
} else {
|
|
record = new ChinaArea({})
|
|
}
|
|
record.name = name
|
|
record.locations = locations
|
|
await record.save()
|
|
res.json({errcode: 0, record: record})
|
|
} catch (err) {
|
|
next(err)
|
|
}
|
|
})
|
|
|
|
/* 删除*/
|
|
router.delete('/china_area', async (req, res, next) => {
|
|
logger.db(req, '公共', '地域', '删除地域')
|
|
const body = req.body
|
|
const id = body.id
|
|
try {
|
|
if (!id) {
|
|
return res.json({errcode: 101, errmsg: '未定义要删除的地域id'})
|
|
}
|
|
const record = await ChinaArea.findById(id)
|
|
if (!record) {
|
|
return res.json({errcode: 102, errmsg: '未找到要删除的地域'})
|
|
}
|
|
const usedRecord = await GameShareImage.findOne({
|
|
area: id,
|
|
deleted: false,
|
|
})
|
|
if (usedRecord) {
|
|
return res.json({
|
|
errcode: 103,
|
|
errmsg: '要删除的记录已被使用,不能删除!',
|
|
})
|
|
}
|
|
record.deleted = true
|
|
record.delete_time = new Date()
|
|
await record.save()
|
|
res.json({errcode: 0, record: record})
|
|
} catch (err) {
|
|
next(err)
|
|
}
|
|
})
|
|
|
|
export default router
|