const logger = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/logger.js`)
const { createAppError } = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/utils/appError.js`)
const env = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/config/env.js`)
const userService = require(`${__hooks}/bai_api_pb_hooks/bai_api_shared/services/userService.js`)

function buildBusinessId(prefix) {
    return prefix + '-' + new Date().getTime() + '-' + $security.randomString(6)
}

function parseJsonResponse(response, actionName) {
    if (!response) {
        throw createAppError(500, actionName + ' 失败：PocketBase 响应为空')
    }

    if (response.json && typeof response.json === 'object') {
        return response.json
    }

    if (typeof response.body === 'string' && response.body) {
        return JSON.parse(response.body)
    }

    if (response.body && typeof response.body === 'object') {
        return response.body
    }

    if (typeof response.data === 'string' && response.data) {
        return JSON.parse(response.data)
    }

    if (response.data && typeof response.data === 'object') {
        return response.data
    }

    return {}
}

function getPocketBaseApiBaseUrl() {
    const base = String(env.pocketbaseApiUrl || '').replace(/\/+$/, '')
    if (!base) {
        throw createAppError(500, '缺少 POCKETBASE_API_URL 配置')
    }
    return base
}

function getPocketBaseAuthToken() {
    const token = String(env.pocketbaseAuthToken || '').trim()
    if (!token) {
        throw createAppError(500, '缺少 POCKETBASE_AUTH_TOKEN 配置')
    }
    return token
}

function requestPocketBase(method, path, body, actionName) {
    const response = $http.send({
        url: getPocketBaseApiBaseUrl() + path,
        method: method,
        headers: body ? {
            Authorization: 'Bearer ' + getPocketBaseAuthToken(),
            'Content-Type': 'application/json',
        } : {
            Authorization: 'Bearer ' + getPocketBaseAuthToken(),
        },
        body: body ? JSON.stringify(body) : '',
    })

    if (!response || response.statusCode < 200 || response.statusCode >= 300) {
        throw createAppError(500, actionName + ' 失败', {
            statusCode: response ? response.statusCode : 0,
            body: response ? String(response.body || '') : '',
        })
    }

    return parseJsonResponse(response, actionName)
}

function normalizeText(value) {
    return String(value || '').replace(/^\s+|\s+$/g, '')
}

function formatDateNumberSegment(date) {
    const current = date || new Date()
    const yyyy = String(current.getFullYear())
    const mm = String(current.getMonth() + 1).padStart(2, '0')
    const dd = String(current.getDate()).padStart(2, '0')
    const hh = String(current.getHours()).padStart(2, '0')
    const mi = String(current.getMinutes()).padStart(2, '0')
    const ss = String(current.getSeconds()).padStart(2, '0')
    return yyyy + mm + dd + hh + mi + ss
}

function buildDisplayNumber(prefix, authRecord, openid) {
    const baseName = normalizeText(authRecord && typeof authRecord.getString === 'function' ? authRecord.getString('users_name') : '') || normalizeText(openid) || prefix
    return baseName + '-' + formatDateNumberSegment(new Date())
}

function normalizeNumberValue(value, fieldName) {
    if (value === '' || value === null || typeof value === 'undefined') {
        throw createAppError(400, fieldName + ' 为必填项')
    }

    const num = Number(value)
    if (!Number.isFinite(num)) {
        throw createAppError(400, fieldName + ' 必须为数字')
    }

    return num
}

function normalizePositiveIntegerValue(value, fieldName) {
    const num = normalizeNumberValue(value, fieldName)
    if (num <= 0 || Math.floor(num) !== num) {
        throw createAppError(400, fieldName + ' 必须为正整数')
    }
    return num
}

function normalizeOptionalNumberValue(value, fieldName) {
    if (value === '' || value === null || typeof value === 'undefined') {
        return undefined
    }

    const num = Number(value)
    if (!Number.isFinite(num)) {
        throw createAppError(400, fieldName + ' 必须为数字')
    }

    return num
}

function normalizeCartStatus(value) {
    return normalizeText(value) || '有效'
}

function normalizeOrderStatus(value) {
    return normalizeText(value) || '订单已生成'
}

function normalizeOrderSource(value) {
    return normalizeText(value)
}

function normalizeJsonField(value, fieldName) {
    if (value === null || typeof value === 'undefined' || value === '') {
        throw createAppError(400, fieldName + ' 为必填项')
    }

    if (Array.isArray(value)) {
        try {
            return JSON.parse(JSON.stringify(value))
        } catch (_err) {
            throw createAppError(400, fieldName + ' 必须可序列化为 JSON')
        }
    }

    if (typeof value === 'object') {
        try {
            return JSON.parse(JSON.stringify(value))
        } catch (_err) {
            throw createAppError(400, fieldName + ' 必须可序列化为 JSON')
        }
    }

    if (typeof value === 'string') {
        try {
            return JSON.parse(value)
        } catch (_err) {
            throw createAppError(400, fieldName + ' 必须是 JSON 对象、数组或合法 JSON 字符串')
        }
    }

    throw createAppError(400, fieldName + ' 必须是 JSON 对象、数组或合法 JSON 字符串')
}

function parseJsonFieldForOutput(value) {
    if (value === null || typeof value === 'undefined' || value === '') {
        return {}
    }

    if (Array.isArray(value)) {
        return value
    }

    if (typeof value === 'object') {
        try {
            return JSON.parse(JSON.stringify(value))
        } catch (_err) {
            return {}
        }
    }

    if (typeof value === 'string') {
        try {
            return JSON.parse(value)
        } catch (_err) {
            return {}
        }
    }

    return {}
}

function findProductRecordByBusinessId(productId) {
    const records = $app.findRecordsByFilter('tbl_product_list', 'prod_list_id = {:productId}', '', 1, 0, {
        productId: productId,
    })

    return records.length ? records[0] : null
}

function findProductRecordByRecordId(recordId) {
    const targetId = normalizeText(recordId)
    if (!targetId) {
        return null
    }

    try {
        return $app.findRecordById('tbl_product_list', targetId)
    } catch (_error) {
        return null
    }
}

function buildProductInfo(record) {
    if (!record) {
        return {
            prod_list_id: '',
            prod_list_name: '',
            prod_list_modelnumber: '',
            prod_list_barcode: '',
            prod_list_basic_price: null,
        }
    }

    return {
        prod_list_id: record.getString('prod_list_id'),
        prod_list_name: record.getString('prod_list_name'),
        prod_list_modelnumber: record.getString('prod_list_modelnumber'),
        prod_list_barcode: record.getString('prod_list_barcode'),
        prod_list_basic_price: record.get('prod_list_basic_price'),
    }
}

function ensureProductExists(productId) {
    const targetId = normalizeText(productId)
    if (!targetId) {
        throw createAppError(400, 'cart_product_id 为必填项')
    }

    const record = findProductRecordByRecordId(targetId)
    if (!record) {
        throw createAppError(400, 'cart_product_id 必须为 tbl_product_list 的 recordId，且对应产品必须存在：' + targetId)
    }

    return record
}

function findCartRecordByBusinessId(cartId) {
    const records = $app.findRecordsByFilter('tbl_cart', 'cart_id = {:cartId}', '', 1, 0, {
        cartId: cartId,
    })

    return records.length ? records[0] : null
}

function findOrderRecordByBusinessId(orderId) {
    const records = $app.findRecordsByFilter('tbl_order', 'order_id = {:orderId}', '', 1, 0, {
        orderId: orderId,
    })

    return records.length ? records[0] : null
}

function ensureRecordOwner(record, fieldName, authOpenid, resourceLabel) {
    const owner = normalizeText(record && typeof record.getString === 'function' ? record.getString(fieldName) : '')
    if (!owner || owner !== normalizeText(authOpenid)) {
        throw createAppError(403, '无权访问该' + resourceLabel)
    }
}

function exportCartRecord(record, productRecord) {
    const relationValue = record.getString('cart_product_id')
    const productSource = productRecord || findProductRecordByRecordId(relationValue)
    const productInfo = buildProductInfo(productSource)

    return {
        pb_id: record.id,
        cart_id: record.getString('cart_id'),
        cart_number: record.getString('cart_number'),
        cart_create: String(record.get('cart_create') || ''),
        cart_owner: record.getString('cart_owner'),
        cart_product_id: productSource ? productSource.id : relationValue,
        cart_product_business_id: productInfo.prod_list_id,
        cart_product_quantity: Number(record.get('cart_product_quantity') || 0),
        cart_status: record.getString('cart_status'),
        cart_at_price: Number(record.get('cart_at_price') || 0),
        cart_remark: record.getString('cart_remark'),
        product_name: productInfo.prod_list_name,
        product_modelnumber: productInfo.prod_list_modelnumber,
        product_barcode: productInfo.prod_list_barcode,
        product_basic_price: productInfo.prod_list_basic_price,
        created: String(record.created || ''),
        updated: String(record.updated || ''),
    }
}

function exportOrderRecord(record) {
    return {
        pb_id: record.id,
        order_id: record.getString('order_id'),
        order_number: record.getString('order_number'),
        order_create: String(record.get('order_create') || ''),
        order_owner: record.getString('order_owner'),
        order_source: record.getString('order_source'),
        order_status: record.getString('order_status'),
        order_source_id: record.getString('order_source_id'),
        order_snap: parseJsonFieldForOutput(record.get('order_snap')),
        order_amount: Number(record.get('order_amount') || 0),
        order_remark: record.getString('order_remark'),
        created: String(record.created || ''),
        updated: String(record.updated || ''),
    }
}

function exportAdminCartRecord(record) {
    const productId = record && typeof record.getString === 'function'
        ? record.getString('cart_product_id')
        : String(record && record.cart_product_id || '')
    const productSource = findProductRecordByRecordId(productId)
    const productInfo = buildProductInfo(productSource)

    return {
        pb_id: String(record && record.id || ''),
        cart_id: record && typeof record.getString === 'function' ? record.getString('cart_id') : String(record && record.cart_id || ''),
        cart_number: record && typeof record.getString === 'function' ? record.getString('cart_number') : String(record && record.cart_number || ''),
        cart_create: record && typeof record.get === 'function' ? String(record.get('cart_create') || '') : String(record && record.cart_create || ''),
        cart_owner: record && typeof record.getString === 'function' ? record.getString('cart_owner') : String(record && record.cart_owner || ''),
        cart_product_id: productSource ? productSource.id : productId,
        cart_product_business_id: productInfo.prod_list_id,
        cart_product_quantity: record && typeof record.get === 'function' ? Number(record.get('cart_product_quantity') || 0) : Number(record && record.cart_product_quantity || 0),
        cart_status: record && typeof record.getString === 'function' ? record.getString('cart_status') : String(record && record.cart_status || ''),
        cart_at_price: record && typeof record.get === 'function' ? Number(record.get('cart_at_price') || 0) : Number(record && record.cart_at_price || 0),
        cart_remark: record && typeof record.getString === 'function' ? record.getString('cart_remark') : String(record && record.cart_remark || ''),
        product_name: productInfo.prod_list_name,
        product_modelnumber: productInfo.prod_list_modelnumber,
        product_barcode: productInfo.prod_list_barcode,
        product_basic_price: productInfo.prod_list_basic_price,
        created: String(record && record.created || ''),
        updated: String(record && record.updated || ''),
    }
}

function exportAdminOrderRecord(record) {
    return {
        pb_id: String(record && record.id || ''),
        order_id: record && typeof record.getString === 'function' ? record.getString('order_id') : String(record && record.order_id || ''),
        order_number: record && typeof record.getString === 'function' ? record.getString('order_number') : String(record && record.order_number || ''),
        order_create: record && typeof record.get === 'function' ? String(record.get('order_create') || '') : String(record && record.order_create || ''),
        order_owner: record && typeof record.getString === 'function' ? record.getString('order_owner') : String(record && record.order_owner || ''),
        order_source: record && typeof record.getString === 'function' ? record.getString('order_source') : String(record && record.order_source || ''),
        order_status: record && typeof record.getString === 'function' ? record.getString('order_status') : String(record && record.order_status || ''),
        order_source_id: record && typeof record.getString === 'function' ? record.getString('order_source_id') : String(record && record.order_source_id || ''),
        order_snap: record && typeof record.get === 'function' ? parseJsonFieldForOutput(record.get('order_snap')) : parseJsonFieldForOutput(record && record.order_snap),
        order_amount: record && typeof record.get === 'function' ? Number(record.get('order_amount') || 0) : Number(record && record.order_amount || 0),
        order_remark: record && typeof record.getString === 'function' ? record.getString('order_remark') : String(record && record.order_remark || ''),
        created: String(record && record.created || ''),
        updated: String(record && record.updated || ''),
    }
}

function exportAdminManageUser(userRecord, groupedCarts, groupedOrders) {
    const openid = userRecord && typeof userRecord.getString === 'function'
        ? userRecord.getString('openid')
        : String(userRecord && userRecord.openid || '')
    const carts = groupedCarts[openid] || []
    const orders = groupedOrders[openid] || []
    let cartTotalQuantity = 0
    let orderTotalAmount = 0

    for (let i = 0; i < carts.length; i += 1) {
        cartTotalQuantity += Number(carts[i].cart_product_quantity || 0)
    }
    for (let i = 0; i < orders.length; i += 1) {
        orderTotalAmount += Number(orders[i].order_amount || 0)
    }

    return {
        pb_id: String(userRecord && userRecord.id || ''),
        openid: openid,
        users_id: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_id') : String(userRecord && userRecord.users_id || ''),
        users_name: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_name') : String(userRecord && userRecord.users_name || ''),
        users_phone: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_phone') : String(userRecord && userRecord.users_phone || ''),
        users_level: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_level') : String(userRecord && userRecord.users_level || ''),
        users_level_name: userService.resolveUserLevelName(userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_level') : String(userRecord && userRecord.users_level || '')),
        users_type: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_type') : String(userRecord && userRecord.users_type || ''),
        users_idtype: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_idtype') : String(userRecord && userRecord.users_idtype || ''),
        users_id_number: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_id_number') : String(userRecord && userRecord.users_id_number || ''),
        users_status: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_status') : String(userRecord && userRecord.users_status || ''),
        users_rank_level: !userRecord || typeof userRecord.get !== 'function'
            ? (userRecord && (userRecord.users_rank_level === null || typeof userRecord.users_rank_level === 'undefined') ? null : Number(userRecord && userRecord.users_rank_level))
            : (userRecord.get('users_rank_level') === null || typeof userRecord.get('users_rank_level') === 'undefined')
            ? null
            : Number(userRecord.get('users_rank_level')),
        users_auth_type: !userRecord || typeof userRecord.get !== 'function'
            ? (userRecord && (userRecord.users_auth_type === null || typeof userRecord.users_auth_type === 'undefined') ? null : Number(userRecord && userRecord.users_auth_type))
            : (userRecord.get('users_auth_type') === null || typeof userRecord.get('users_auth_type') === 'undefined')
            ? null
            : Number(userRecord.get('users_auth_type')),
        users_tag: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_tag') : String(userRecord && userRecord.users_tag || ''),
        company_id: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('company_id') : String(userRecord && userRecord.company_id || ''),
        users_parent_id: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_parent_id') : String(userRecord && userRecord.users_parent_id || ''),
        users_promo_code: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_promo_code') : String(userRecord && userRecord.users_promo_code || ''),
        usergroups_id: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('usergroups_id') : String(userRecord && userRecord.usergroups_id || ''),
        users_picture: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_picture') : String(userRecord && userRecord.users_picture || ''),
        users_id_pic_a: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_id_pic_a') : String(userRecord && userRecord.users_id_pic_a || ''),
        users_id_pic_b: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_id_pic_b') : String(userRecord && userRecord.users_id_pic_b || ''),
        users_title_picture: userRecord && typeof userRecord.getString === 'function' ? userRecord.getString('users_title_picture') : String(userRecord && userRecord.users_title_picture || ''),
        cart_count: carts.length,
        cart_total_quantity: cartTotalQuantity,
        order_count: orders.length,
        order_total_amount: orderTotalAmount,
        carts: carts,
        orders: orders,
        created: String(userRecord && userRecord.created || ''),
        updated: String(userRecord && userRecord.updated || ''),
    }
}

function listCarts(authOpenid, payload) {
    const records = $app.findRecordsByFilter('tbl_cart', 'cart_owner = {:owner}', '-cart_create', 500, 0, {
        owner: authOpenid,
    })
    const keyword = normalizeText(payload.keyword).toLowerCase()
    const cartStatus = normalizeText(payload.cart_status)
    const cartNumber = normalizeText(payload.cart_number)
    const result = []

    for (let i = 0; i < records.length; i += 1) {
        const item = exportCartRecord(records[i])
        const matchedKeyword = !keyword
            || item.cart_id.toLowerCase().indexOf(keyword) !== -1
            || item.cart_number.toLowerCase().indexOf(keyword) !== -1
            || item.cart_product_id.toLowerCase().indexOf(keyword) !== -1
            || normalizeText(item.cart_product_business_id).toLowerCase().indexOf(keyword) !== -1
            || normalizeText(item.product_name).toLowerCase().indexOf(keyword) !== -1
        const matchedStatus = !cartStatus || item.cart_status === cartStatus
        const matchedNumber = !cartNumber || item.cart_number === cartNumber

        if (matchedKeyword && matchedStatus && matchedNumber) {
            result.push(item)
        }
    }

    return result
}

function getCartDetail(authOpenid, cartId) {
    const record = findCartRecordByBusinessId(normalizeText(cartId))
    if (!record) {
        throw createAppError(404, '未找到对应购物车记录')
    }

    ensureRecordOwner(record, 'cart_owner', authOpenid, '购物车记录')
    return exportCartRecord(record)
}

function createCart(authState, payload) {
    const productRecord = ensureProductExists(payload.cart_product_id)
    const collection = $app.findCollectionByNameOrId('tbl_cart')
    const record = new Record(collection)

    record.set('cart_id', buildBusinessId('CART'))
    record.set('cart_number', normalizeText(payload.cart_number) || buildDisplayNumber('CART', authState.authRecord, authState.openid))
    record.set('cart_owner', authState.openid)
    record.set('cart_product_id', productRecord.id)
    record.set('cart_product_quantity', normalizePositiveIntegerValue(payload.cart_product_quantity, 'cart_product_quantity'))
    record.set('cart_status', normalizeCartStatus(payload.cart_status))
    record.set('cart_at_price', normalizeNumberValue(payload.cart_at_price, 'cart_at_price'))
    record.set('cart_remark', normalizeText(payload.cart_remark))

    try {
        $app.save(record)
    } catch (err) {
        throw createAppError(400, '创建购物车记录失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('购物车记录创建成功', {
        cart_id: record.getString('cart_id'),
        cart_owner: authState.openid,
    })

    return exportCartRecord(record, productRecord)
}

function updateCart(authOpenid, payload) {
    const record = findCartRecordByBusinessId(normalizeText(payload.cart_id))
    if (!record) {
        throw createAppError(404, '未找到待修改的购物车记录')
    }

    ensureRecordOwner(record, 'cart_owner', authOpenid, '购物车记录')

    let productRecord = null
    if (typeof payload.cart_number !== 'undefined') {
        record.set('cart_number', normalizeText(payload.cart_number) || record.getString('cart_number'))
    }
    if (typeof payload.cart_product_id !== 'undefined') {
        productRecord = ensureProductExists(payload.cart_product_id)
        record.set('cart_product_id', productRecord.id)
    }
    if (typeof payload.cart_product_quantity !== 'undefined') {
        record.set('cart_product_quantity', normalizePositiveIntegerValue(payload.cart_product_quantity, 'cart_product_quantity'))
    }
    if (typeof payload.cart_status !== 'undefined') {
        record.set('cart_status', normalizeCartStatus(payload.cart_status))
    }
    if (typeof payload.cart_at_price !== 'undefined') {
        record.set('cart_at_price', normalizeNumberValue(payload.cart_at_price, 'cart_at_price'))
    }
    if (typeof payload.cart_remark !== 'undefined') {
        record.set('cart_remark', normalizeText(payload.cart_remark))
    }

    try {
        $app.save(record)
    } catch (err) {
        throw createAppError(400, '更新购物车记录失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('购物车记录更新成功', {
        cart_id: record.getString('cart_id'),
        cart_owner: authOpenid,
    })

    return exportCartRecord(record, productRecord)
}

function deleteCart(authOpenid, cartId) {
    const record = findCartRecordByBusinessId(normalizeText(cartId))
    if (!record) {
        throw createAppError(404, '未找到待删除的购物车记录')
    }

    ensureRecordOwner(record, 'cart_owner', authOpenid, '购物车记录')

    try {
        $app.delete(record)
    } catch (err) {
        throw createAppError(400, '删除购物车记录失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('购物车记录删除成功', {
        cart_id: record.getString('cart_id'),
        cart_owner: authOpenid,
    })

    return {
        cart_id: normalizeText(cartId),
    }
}

function listOrders(authOpenid, payload) {
    const records = $app.findRecordsByFilter('tbl_order', 'order_owner = {:owner}', '-order_create', 500, 0, {
        owner: authOpenid,
    })
    const keyword = normalizeText(payload.keyword).toLowerCase()
    const orderStatus = normalizeText(payload.order_status)
    const orderSource = normalizeText(payload.order_source)
    const result = []

    for (let i = 0; i < records.length; i += 1) {
        const item = exportOrderRecord(records[i])
        const matchedKeyword = !keyword
            || item.order_id.toLowerCase().indexOf(keyword) !== -1
            || item.order_number.toLowerCase().indexOf(keyword) !== -1
            || item.order_source_id.toLowerCase().indexOf(keyword) !== -1
        const matchedStatus = !orderStatus || item.order_status === orderStatus
        const matchedSource = !orderSource || item.order_source === orderSource

        if (matchedKeyword && matchedStatus && matchedSource) {
            result.push(item)
        }
    }

    return result
}

function getOrderDetail(authOpenid, orderId) {
    const record = findOrderRecordByBusinessId(normalizeText(orderId))
    if (!record) {
        throw createAppError(404, '未找到对应订单记录')
    }

    ensureRecordOwner(record, 'order_owner', authOpenid, '订单记录')
    return exportOrderRecord(record)
}

function createOrder(authState, payload) {
    const collection = $app.findCollectionByNameOrId('tbl_order')
    const record = new Record(collection)

    // order_id / order_number are generated by PocketBase native field rules.
    record.set('order_owner', authState.openid)
    record.set('order_source', normalizeOrderSource(payload.order_source))
    record.set('order_status', normalizeOrderStatus(payload.order_status))
    record.set('order_source_id', normalizeText(payload.order_source_id))
    record.set('order_snap', normalizeJsonField(payload.order_snap, 'order_snap'))
    record.set('order_amount', normalizeNumberValue(payload.order_amount, 'order_amount'))
    record.set('order_remark', normalizeText(payload.order_remark))

    try {
        $app.save(record)
    } catch (err) {
        throw createAppError(400, '创建订单失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('订单创建成功', {
        order_id: record.getString('order_id'),
        order_owner: authState.openid,
    })

    return exportOrderRecord(record)
}

function updateOrder(authOpenid, payload) {
    const record = findOrderRecordByBusinessId(normalizeText(payload.order_id))
    if (!record) {
        throw createAppError(404, '未找到待修改的订单')
    }

    ensureRecordOwner(record, 'order_owner', authOpenid, '订单记录')

    if (typeof payload.order_number !== 'undefined') {
        record.set('order_number', normalizeText(payload.order_number) || record.getString('order_number'))
    }
    if (typeof payload.order_source !== 'undefined') {
        const nextSource = normalizeOrderSource(payload.order_source)
        if (!nextSource) {
            throw createAppError(400, 'order_source 为必填项')
        }
        record.set('order_source', nextSource)
    }
    if (typeof payload.order_status !== 'undefined') {
        record.set('order_status', normalizeOrderStatus(payload.order_status))
    }
    if (typeof payload.order_source_id !== 'undefined') {
        const nextSourceId = normalizeText(payload.order_source_id)
        if (!nextSourceId) {
            throw createAppError(400, 'order_source_id 为必填项')
        }
        record.set('order_source_id', nextSourceId)
    }
    if (typeof payload.order_snap !== 'undefined') {
        record.set('order_snap', normalizeJsonField(payload.order_snap, 'order_snap'))
    }
    if (typeof payload.order_amount !== 'undefined') {
        record.set('order_amount', normalizeNumberValue(payload.order_amount, 'order_amount'))
    }
    if (typeof payload.order_remark !== 'undefined') {
        record.set('order_remark', normalizeText(payload.order_remark))
    }

    try {
        $app.save(record)
    } catch (err) {
        throw createAppError(400, '更新订单失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('订单更新成功', {
        order_id: record.getString('order_id'),
        order_owner: authOpenid,
    })

    return exportOrderRecord(record)
}

function deleteOrder(authOpenid, orderId) {
    const record = findOrderRecordByBusinessId(normalizeText(orderId))
    if (!record) {
        throw createAppError(404, '未找到待删除的订单')
    }

    ensureRecordOwner(record, 'order_owner', authOpenid, '订单记录')

    try {
        $app.delete(record)
    } catch (err) {
        throw createAppError(400, '删除订单失败', {
            originalMessage: (err && err.message) || '未知错误',
            originalData: (err && err.data) || {},
        })
    }

    logger.info('订单删除成功', {
        order_id: record.getString('order_id'),
        order_owner: authOpenid,
    })

    return {
        order_id: normalizeText(orderId),
    }
}

function exportManageUser(userRecord, groupedCarts, groupedOrders) {
    const openid = userRecord.getString('openid')
    const carts = groupedCarts[openid] || []
    const orders = groupedOrders[openid] || []
    let cartTotalQuantity = 0
    let orderTotalAmount = 0

    for (let i = 0; i < carts.length; i += 1) {
        cartTotalQuantity += Number(carts[i].cart_product_quantity || 0)
    }
    for (let i = 0; i < orders.length; i += 1) {
        orderTotalAmount += Number(orders[i].order_amount || 0)
    }

    return {
        pb_id: userRecord.id,
        openid: openid,
        users_id: userRecord.getString('users_id'),
        users_name: userRecord.getString('users_name'),
        users_phone: userRecord.getString('users_phone'),
        users_type: userRecord.getString('users_type'),
        users_idtype: userRecord.getString('users_idtype'),
        company_id: userRecord.getString('company_id'),
        cart_count: carts.length,
        cart_total_quantity: cartTotalQuantity,
        order_count: orders.length,
        order_total_amount: orderTotalAmount,
        carts: carts,
        orders: orders,
        created: String(userRecord.created || ''),
        updated: String(userRecord.updated || ''),
    }
}

function listManageUsersCartOrders(payload) {
    const keyword = normalizeText(payload.keyword).toLowerCase()
    const userRecords = $app.findRecordsByFilter('tbl_auth_users', '', '-users_id', 500, 0)
    const cartRecords = $app.findRecordsByFilter('tbl_cart', '', '-cart_create', 1000, 0)
    const orderRecords = $app.findRecordsByFilter('tbl_order', '', '-order_create', 1000, 0)
    const groupedCarts = {}
    const groupedOrders = {}

    for (let i = 0; i < cartRecords.length; i += 1) {
        const owner = cartRecords[i] && typeof cartRecords[i].getString === 'function'
            ? cartRecords[i].getString('cart_owner')
            : String(cartRecords[i] && cartRecords[i].cart_owner || '')
        if (!groupedCarts[owner]) {
            groupedCarts[owner] = []
        }
        groupedCarts[owner].push(exportAdminCartRecord(cartRecords[i]))
    }

    for (let i = 0; i < orderRecords.length; i += 1) {
        const owner = orderRecords[i] && typeof orderRecords[i].getString === 'function'
            ? orderRecords[i].getString('order_owner')
            : String(orderRecords[i] && orderRecords[i].order_owner || '')
        if (!groupedOrders[owner]) {
            groupedOrders[owner] = []
        }
        groupedOrders[owner].push(exportAdminOrderRecord(orderRecords[i]))
    }

    const result = []
    for (let i = 0; i < userRecords.length; i += 1) {
        const item = exportAdminManageUser(userRecords[i], groupedCarts, groupedOrders)
        const matchedKeyword = !keyword
            || normalizeText(item.openid).toLowerCase().indexOf(keyword) !== -1
            || normalizeText(item.users_id).toLowerCase().indexOf(keyword) !== -1
            || normalizeText(item.users_name).toLowerCase().indexOf(keyword) !== -1
            || normalizeText(item.users_phone).toLowerCase().indexOf(keyword) !== -1

        if (matchedKeyword) {
            result.push(item)
        }
    }

    return {
        items: result,
        user_level_options: userService.getUserLevelOptions(),
    }
}

function updateManageUser(payload) {
    return userService.updateManagedUserProfile(payload).user
}

module.exports = {
    listCarts,
    getCartDetail,
    createCart,
    updateCart,
    deleteCart,
    listOrders,
    getOrderDetail,
    createOrder,
    updateOrder,
    deleteOrder,
    listManageUsersCartOrders,
    updateManageUser,
}
