// ===================================================================
// 售后统一服务 — 订单售后精细化
// 处理：仅退款(only_refund) / 退货退款(return_refund) 双流程
// 状态机: pending → approved/awaiting_return → returned → completed(退款)
// 退款成功: 回补库存 + 回冲消费积分 + 回冲分销佣金
// ===================================================================
const { get, run, all, transaction } = require('../utils/db');

// 售后类型
const TYPE = { ONLY_REFUND: 'only_refund', RETURN_REFUND: 'refund_and_return' };
// 售后状态
const STATUS = {
  PENDING: 'pending',            // 待审核
  APPROVED: 'approved',          // 审核通过(仅退款→待退款/退货退款→待寄回)
  SHIPPED_BACK: 'shipped_back',  // 用户已寄回(退货退款专用,填物流后)
  COMPLETED: 'completed',        // 退款完成
  REJECTED: 'rejected',          // 审核驳回
  CANCELLED: 'cancelled',        // 用户取消
};

const TYPE_LABEL = {
  only_refund: '仅退款',
  refund_and_return: '退货退款',
};
const STATUS_LABEL = {
  pending: '待审核',
  approved: '审核通过(待寄回/待退款)',
  shipped_back: '已寄回待收货',
  received: '商家已收货',
  completed: '已完成退款',
  rejected: '已驳回',
  cancelled: '已取消',
};

function genRefundNo() { return `TK${Date.now()}${Math.floor(Math.random() * 1000)}`; }

// 可申请售后的主订单状态
const REFUNDABLE_MAIN = ['pending_ship', 'shipped', 'received'];
// 未发货可走仅退款；已发货/已收货 强制走退货退款
const ONLY_REFUND_ALLOWED = ['pending_ship'];
const RETURN_ALLOWED = ['shipped', 'received'];

function cfgVal(key, def) {
  const r = get('SELECT value FROM system_config WHERE key=?', [key]);
  return r ? r.value : def;
}

// ===================================================================
// 1. 用户申请售后
// order_id + 自动判定 type：
//   pending_ship → 仅退款
//   shipped/received → 退货退款
// ===================================================================
function applyRefund({ order_id, userId, reason, images, amount }) {
  if (!order_id || !userId) return { ok: false, reason: '参数缺失' };
  const order = get('SELECT * FROM orders WHERE id=? AND user_id=?', [order_id, userId]);
  if (!order) return { ok: false, reason: '订单不存在' };
  if (!REFUNDABLE_MAIN.includes(order.status)) {
    return { ok: false, reason: '当前订单状态不可申请售后' };
  }
  const paid = toNumC(order.paid_amount || order.pay_amount || 0);
  if (!(paid > 0)) return { ok: false, reason: '订单金额无效，无法申请售后' };

  // 判定售后类型
  let type;
  if (ONLY_REFUND_ALLOWED.includes(order.status)) type = TYPE.ONLY_REFUND;
  else if (RETURN_ALLOWED.includes(order.status)) type = TYPE.RETURN_REFUND;
  else return { ok: false, reason: '当前订单状态不可申请售后' };

  // 幂等：同一订单存在未完结售后则拒绝
  const active = get("SELECT id FROM refunds WHERE order_id=? AND status IN ('pending','approved','shipped_back','received')", [order_id]);
  if (active) return { ok: false, reason: '已有进行中的售后申请' };

  // 金额校验：不能超过支付金额
  let reqAmount = amount ?? paid;
  reqAmount = toNumC(reqAmount);
  if (!(reqAmount > 0) || reqAmount > paid) return { ok: false, reason: '退款金额无效或超出支付金额' };

  const refundNo = genRefundNo();
  let refundId = null;
  let created = false;
  transaction(() => {
    const r = run(
      "INSERT INTO refunds(refund_no,order_id,user_id,type,reason,images,amount,status,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,datetime('now','localtime'),datetime('now','localtime'))",
      [refundNo, order_id, userId, type, reason || '', images || '[]', reqAmount, STATUS.PENDING]
    );
    refundId = r.lastInsertRowid;
    run("UPDATE orders SET refund_status=? WHERE id=?", [STATUS.PENDING, order_id]);
    run('INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)',
      [order_id, 'refund_apply', `用户申请${TYPE_LABEL[type]}，金额:¥${reqAmount.toFixed(2)}，原因:${reason || '无'}`, 'user']);
  });
  return { ok: true, refund_id: refundId, refund_no: refundNo, type };
}

// ===================================================================
// 2. 用户取消售后（仅待审核状态可取消）
// ===================================================================
function cancelRefund(refund_id, userId) {
  const refund = get('SELECT * FROM refunds WHERE id=? AND user_id=?', [refund_id, userId]);
  if (!refund) return { ok: false, reason: '售后单不存在' };
  if (refund.status !== STATUS.PENDING) return { ok: false, reason: '当前状态不可取消' };
  transaction(() => {
    run("UPDATE refunds SET status=?, updated_at=datetime('now','localtime') WHERE id=?", [STATUS.CANCELLED, refund_id]);
    run("UPDATE orders SET refund_status='' WHERE id=?", [refund.order_id]);
    run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)', [refund.order_id, 'refund_cancel', '用户取消售后申请']);
  });
  return { ok: true };
}

// ===================================================================
// 3. 退货退款：用户填写退货物流
// ===================================================================
function submitReturn(refund_id, userId, { shipping_company, shipping_no }) {
  if (!shipping_company || !shipping_no) return { ok: false, reason: '请填写退货物流信息' };
  const refund = get('SELECT * FROM refunds WHERE id=? AND user_id=?', [refund_id, userId]);
  if (!refund) return { ok: false, reason: '售后单不存在' };
  if (refund.type !== TYPE.RETURN_REFUND) return { ok: false, reason: '该售后无需寄回' };
  if (refund.status !== STATUS.APPROVED) return { ok: false, reason: '当前状态不可填写退货物流' };
  transaction(() => {
    run("UPDATE refunds SET status=?, shipping_company=?, shipping_no=?, updated_at=datetime('now','localtime') WHERE id=?",
      [STATUS.SHIPPED_BACK, shipping_company, shipping_no, refund_id]);
    run("UPDATE orders SET refund_status=? WHERE id=?", [STATUS.SHIPPED_BACK, refund.order_id]);
    run('INSERT INTO order_logs(order_id,action,content) VALUES(?,?,?)',
      [refund.order_id, 'refund_return', `用户已寄回，物流:${shipping_company} ${shipping_no}`]);
  });
  return { ok: true };
}

// ===================================================================
// 4. 退款回冲：积分 + 佣金（退款成功后调用，事务内）
// ===================================================================
function clawbackRewards(orderId, refundAmount, refund_no) {
  // 回冲消费送积分（按实付金额对应的赠送积分扣回）
  try {
    const rewardRatio = parseInt(cfgVal('order_reward_ratio', '1'), 10) || 1;
    const order = get('SELECT user_id, pay_amount FROM orders WHERE id=?', [orderId]);
    if (order) {
      const refundYuan = toNumC(refundAmount); // 单位元
      const ptsToDeduct = Math.max(0, Math.floor(refundYuan * rewardRatio));
      if (ptsToDeduct > 0) {
        try {
          const pts = require('./points');
          const bal = pts.getBalance(order.user_id);
          const cur = bal.points || 0;
          const actual = Math.min(ptsToDeduct, cur);
          if (actual > 0) {
            pts.deductPoints(order.user_id, actual, 'refund', refund_no || String(orderId), `退款回冲消费送积分-${refund_no || orderId}`);
          }
        } catch (e) { console.error('[售后] 积分回冲失败:', e.message); }
      }
    }
  } catch (e) { console.error('[售后] 积分回冲异常:', e.message); }

  // 回冲分销佣金：该订单未结算(pending)的佣金作废
  try {
    run("UPDATE distribution_records SET status='cancelled' WHERE order_id=? AND status='pending'", [orderId]);
  } catch (e) { console.error('[售后] 佣金回冲失败:', e.message); }
}

function refundNo() { return genRefundNo(); }

function toNumC(v) {
  const n = parseFloat(v);
  return isNaN(n) ? 0 : n;
}

// ===================================================================
// 5. 管理员处理售后
// action: approve(同意) / reject(驳回) / confirm_return(确认收货并退款)
// ===================================================================
async function processRefund(refund_id, action, adminId, { reject_reason } = {}) {
  const refund = get('SELECT * FROM refunds WHERE id=?', [refund_id]);
  if (!refund) return { ok: false, reason: '售后单不存在' };
  const order = get('SELECT * FROM orders WHERE id=?', [refund.order_id]);
  if (!order) return { ok: false, reason: '订单不存在' };

  if (action === 'approve') {
    if (refund.status !== STATUS.PENDING) return { ok: false, reason: '该申请已处理' };
    // 仅退款 → 直接完成退款；退货退款 → 进入待寄回
    if (refund.type === TYPE.RETURN_REFUND) {
      transaction(() => {
        run("UPDATE refunds SET status=?, updated_at=datetime('now','localtime') WHERE id=?", [STATUS.APPROVED, refund_id]);
        run("UPDATE orders SET refund_status=? WHERE id=?", [STATUS.APPROVED, order.id]);
        run('INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)',
          [order.id, 'refund_approve', '管理员同意退货退款，等待用户寄回', adminId || 'admin']);
      });
      return { ok: true, status: STATUS.APPROVED };
    }
    // 仅退款 → 直接退款
    return await completeRefund(refund_id, adminId);
  }

  if (action === 'confirm_return') {
    // 商家确认收到退货 → 退款（仅 shipped_back 可确认）
    if (refund.status !== STATUS.SHIPPED_BACK) return { ok: false, reason: '当前状态不可确认收货' };
    return await completeRefund(refund_id, adminId);
  }

  if (action === 'reject') {
    if (refund.status !== STATUS.PENDING) return { ok: false, reason: '该申请已处理' };
    transaction(() => {
      run("UPDATE refunds SET status=?, reject_reason=?, updated_at=datetime('now','localtime') WHERE id=?",
        [STATUS.REJECTED, reject_reason || '', refund_id]);
      run("UPDATE orders SET refund_status='' WHERE id=?", [order.id]);
      run('INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)',
        [order.id, 'refund_reject', `管理员驳回售后:${reject_reason || '无'}`, adminId || 'admin']);
    });
    return { ok: true, status: STATUS.REJECTED };
  }

  return { ok: false, reason: '操作类型无效' };
}

// ===================================================================
// 6. 完成退款（最终节点）：状态置 completed + 回补库存 + 回冲积分佣金 + 原路退款
// ===================================================================
function completeRefund(refund_id, adminId) {
  let refund = null;
  return new Promise((resolve, reject) => {
    try {
      refund = get('SELECT * FROM refunds WHERE id=?', [refund_id]);
      if (!refund) return resolve({ ok: false, reason: '售后单不存在' });
      if (!['approved', 'received', 'shipped_back', 'pending'].includes(refund.status)) {
        return resolve({ ok: false, reason: '当前状态不可退款' });
      }
      const order = get('SELECT * FROM orders WHERE id=?', [refund.order_id]);
      if (!order) return resolve({ ok: false, reason: '订单不存在' });

      transaction(() => {
        run("UPDATE refunds SET status=?, updated_at=datetime('now','localtime') WHERE id=?", [STATUS.COMPLETED, refund_id]);
        run("UPDATE orders SET status='refunded', refund_status='completed', updated_at=datetime('now','localtime') WHERE id=?", [order.id]);
        // 回补库存
        const items = all('SELECT * FROM order_items WHERE order_id=?', [order.id]);
        for (const item of items) {
          if (item.sku_id) {
            run('UPDATE product_skus SET stock=stock+?, sales=sales-? WHERE id=?', [item.quantity, item.quantity, item.sku_id]);
          } else {
            run('UPDATE products SET stock=stock+?, sales=sales-? WHERE id=?', [item.quantity, item.quantity, item.product_id]);
          }
        }
        run('INSERT INTO order_logs(order_id,action,content,operator) VALUES(?,?,?,?)',
          [order.id, 'refund_complete', `退款完成，金额:¥${toNumC(refund.amount).toFixed(2)}`, adminId || 'system']);
      });

      // 回冲积分+佣金（事务外，独立容错）
      clawbackRewards(order.id, refund.amount, refund.refund_no);
      resolve({ ok: true, status: STATUS.COMPLETED });
    } catch (e) {
      reject(e);
    }
  });
}

module.exports = {
  TYPE, STATUS, TYPE_LABEL, STATUS_LABEL,
  applyRefund, cancelRefund, submitReturn, processRefund, completeRefund,
};
