SET @return_keep_id := (
  SELECT id
  FROM wh_warehouse
  WHERE warehouse_code = 'WH-RETURN-01'
  ORDER BY id
  LIMIT 1
);

SET @return_keep_id := COALESCE(
  @return_keep_id,
  (
    SELECT id
    FROM wh_warehouse
    WHERE warehouse_type = 'RETURN'
    ORDER BY id
    LIMIT 1
  )
);

INSERT INTO wh_warehouse (warehouse_code, warehouse_name, warehouse_type, manager_employee_id, status, remark)
SELECT 'WH-RETURN-01', '退货库', 'RETURN', NULL, 'ACTIVE', '客户退回且可返工产品的待处理库存'
WHERE @return_keep_id IS NULL;

SET @return_keep_id := COALESCE(
  @return_keep_id,
  (
    SELECT id
    FROM wh_warehouse
    WHERE warehouse_code = 'WH-RETURN-01'
    ORDER BY id
    LIMIT 1
  )
);

UPDATE wh_warehouse
SET warehouse_name = '退货库',
    warehouse_code = 'WH-RETURN-01',
    warehouse_type = 'RETURN',
    status = 'ACTIVE',
    remark = '客户退回且可返工产品的待处理库存'
WHERE id = @return_keep_id;

INSERT INTO wh_location (
  warehouse_id,
  location_code,
  location_name,
  zone_name,
  is_default,
  is_locked,
  status,
  remark
)
SELECT
  @return_keep_id,
  'RTN-F-01',
  '退货暂存位',
  'F区',
  1,
  0,
  'ACTIVE',
  '退货库默认库位'
WHERE NOT EXISTS (
  SELECT 1
  FROM wh_location
  WHERE warehouse_id = @return_keep_id
    AND location_code = 'RTN-F-01'
);

UPDATE wh_location
SET location_name = '退货暂存位',
    zone_name = 'F区',
    is_default = 1,
    is_locked = 0,
    status = 'ACTIVE',
    remark = '退货库默认库位'
WHERE warehouse_id = @return_keep_id
  AND location_code = 'RTN-F-01';

SET @return_default_location_id := (
  SELECT id
  FROM wh_location
  WHERE warehouse_id = @return_keep_id
    AND location_code = 'RTN-F-01'
  ORDER BY id
  LIMIT 1
);

UPDATE wh_location duplicate_location
JOIN wh_warehouse duplicate_warehouse ON duplicate_warehouse.id = duplicate_location.warehouse_id
SET duplicate_location.location_code = CONCAT('RTN-M', duplicate_warehouse.id, '-', duplicate_location.id),
    duplicate_location.location_name = CONCAT(LEFT(duplicate_location.location_name, 80), '（合并）'),
    duplicate_location.remark = LEFT(CONCAT(COALESCE(duplicate_location.remark, ''), '；重复退货库合并时重命名库位编码'), 255)
WHERE duplicate_warehouse.warehouse_type = 'RETURN'
  AND duplicate_warehouse.id <> @return_keep_id;

UPDATE wh_location
SET warehouse_id = @return_keep_id
WHERE warehouse_id IN (
  SELECT duplicate_return_warehouse.id
  FROM (
    SELECT id
    FROM wh_warehouse
    WHERE warehouse_type = 'RETURN'
      AND id <> @return_keep_id
  ) AS duplicate_return_warehouse
);

UPDATE wh_location
SET is_default = CASE WHEN id = @return_default_location_id THEN 1 ELSE 0 END
WHERE warehouse_id = @return_keep_id;

UPDATE wh_stock_lot
SET warehouse_id = @return_keep_id,
    location_id = COALESCE(location_id, @return_default_location_id)
WHERE warehouse_id IN (
  SELECT duplicate_return_warehouse.id
  FROM (
    SELECT id
    FROM wh_warehouse
    WHERE warehouse_type = 'RETURN'
      AND id <> @return_keep_id
  ) AS duplicate_return_warehouse
);

DROP TEMPORARY TABLE IF EXISTS tmp_return_balance_merge;

CREATE TEMPORARY TABLE tmp_return_balance_merge AS
SELECT
  sb.id AS old_balance_id,
  sb.item_id AS item_id,
  @return_keep_id AS target_warehouse_id,
  COALESCE(sb.location_id, @return_default_location_id) AS target_location_id,
  sb.qty_on_hand AS qty_on_hand,
  sb.weight_on_hand_kg AS weight_on_hand_kg,
  sb.qty_available AS qty_available,
  sb.weight_available_kg AS weight_available_kg,
  sb.qty_allocated AS qty_allocated,
  sb.weight_allocated_kg AS weight_allocated_kg,
  sb.avg_unit_cost AS avg_unit_cost
FROM wh_stock_balance sb
JOIN wh_warehouse duplicate_warehouse ON duplicate_warehouse.id = sb.warehouse_id
WHERE duplicate_warehouse.warehouse_type = 'RETURN'
  AND duplicate_warehouse.id <> @return_keep_id;

INSERT INTO wh_stock_balance (
  item_id,
  warehouse_id,
  location_id,
  qty_on_hand,
  weight_on_hand_kg,
  qty_available,
  weight_available_kg,
  qty_allocated,
  weight_allocated_kg,
  avg_unit_cost
)
SELECT
  item_id,
  target_warehouse_id,
  target_location_id,
  SUM(qty_on_hand),
  SUM(weight_on_hand_kg),
  SUM(qty_available),
  SUM(weight_available_kg),
  SUM(qty_allocated),
  SUM(weight_allocated_kg),
  CASE
    WHEN SUM(weight_on_hand_kg) > 0 THEN SUM(avg_unit_cost * weight_on_hand_kg) / SUM(weight_on_hand_kg)
    ELSE MAX(avg_unit_cost)
  END
FROM tmp_return_balance_merge
GROUP BY item_id, target_warehouse_id, target_location_id
ON DUPLICATE KEY UPDATE
  qty_on_hand = wh_stock_balance.qty_on_hand + VALUES(qty_on_hand),
  weight_on_hand_kg = wh_stock_balance.weight_on_hand_kg + VALUES(weight_on_hand_kg),
  qty_available = wh_stock_balance.qty_available + VALUES(qty_available),
  weight_available_kg = wh_stock_balance.weight_available_kg + VALUES(weight_available_kg),
  qty_allocated = wh_stock_balance.qty_allocated + VALUES(qty_allocated),
  weight_allocated_kg = wh_stock_balance.weight_allocated_kg + VALUES(weight_allocated_kg),
  avg_unit_cost = CASE
    WHEN wh_stock_balance.weight_on_hand_kg + VALUES(weight_on_hand_kg) > 0
      THEN (
        wh_stock_balance.avg_unit_cost * wh_stock_balance.weight_on_hand_kg
        + VALUES(avg_unit_cost) * VALUES(weight_on_hand_kg)
      ) / (wh_stock_balance.weight_on_hand_kg + VALUES(weight_on_hand_kg))
    ELSE VALUES(avg_unit_cost)
  END;

DELETE FROM wh_stock_balance
WHERE id IN (SELECT old_balance_id FROM tmp_return_balance_merge);

DROP TEMPORARY TABLE IF EXISTS tmp_return_balance_merge;

UPDATE wh_inventory_txn
SET warehouse_id = @return_keep_id,
    location_id = COALESCE(location_id, @return_default_location_id)
WHERE warehouse_id IN (
  SELECT duplicate_return_warehouse.id
  FROM (
    SELECT id
    FROM wh_warehouse
    WHERE warehouse_type = 'RETURN'
      AND id <> @return_keep_id
  ) AS duplicate_return_warehouse
);

UPDATE wh_warehouse
SET warehouse_type = 'RETURN_MERGED',
    status = 'INACTIVE',
    remark = LEFT(CONCAT(COALESCE(remark, ''), '；已由退货库补丁合并到WH-RETURN-01'), 255)
WHERE warehouse_type = 'RETURN'
  AND id <> @return_keep_id;

UPDATE wh_location
SET location_name = '退货暂存位',
    zone_name = 'F区',
    is_default = 1,
    is_locked = 0,
    status = 'ACTIVE',
    remark = '退货库默认库位'
WHERE warehouse_id = (SELECT id FROM wh_warehouse WHERE warehouse_code = 'WH-RETURN-01')
  AND location_code = 'RTN-F-01';

UPDATE wh_location
SET is_default = CASE WHEN location_code = 'RTN-F-01' THEN 1 ELSE 0 END
WHERE warehouse_id = @return_keep_id;

SET @has_delivery_item_id := (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'rt_return_item'
    AND COLUMN_NAME = 'delivery_item_id'
);

SET @add_delivery_item_id_sql := IF(
  @has_delivery_item_id = 0,
  'ALTER TABLE rt_return_item ADD COLUMN delivery_item_id BIGINT NULL AFTER sales_order_item_id',
  'SELECT 1'
);
PREPARE add_delivery_item_id_stmt FROM @add_delivery_item_id_sql;
EXECUTE add_delivery_item_id_stmt;
DEALLOCATE PREPARE add_delivery_item_id_stmt;

SET @has_return_delivery_item_idx := (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.STATISTICS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'rt_return_item'
    AND INDEX_NAME = 'idx_rt_return_item_delivery_item'
);

SET @add_return_delivery_item_idx_sql := IF(
  @has_return_delivery_item_idx = 0,
  'ALTER TABLE rt_return_item ADD KEY idx_rt_return_item_delivery_item (delivery_item_id)',
  'SELECT 1'
);
PREPARE add_return_delivery_item_idx_stmt FROM @add_return_delivery_item_idx_sql;
EXECUTE add_return_delivery_item_idx_stmt;
DEALLOCATE PREPARE add_return_delivery_item_idx_stmt;
