<template>
  <div class="batch-order-container">
    <div class="page-title">
      <i class="title-bar"></i>
      <span>批量下单</span>
    </div>

    <div class="action-bar">
      <el-button @click="handleDownloadTemplate">标准导入文件下载</el-button>
      <el-button type="danger" @click="handleImportProducts" :loading="importing">导入订单商品</el-button>
      <!-- 隐藏的文件输入框 -->
      <input ref="fileInputRef" type="file" accept=".xlsx,.xls" style="display: none" @change="handleFileChange" />
    </div>

    <div class="section-title">商品信息</div>
    <div class="product-list">
      <div v-for="(item, index) in productList" :key="index" class="product-item">
        <div class="product-image">
          <el-image :src="item.image" fit="contain">
            <template #error
              ><div class="image-placeholder">
                <el-icon :size="30" color="#ccc"><Picture /></el-icon></div
            ></template>
          </el-image>
        </div>
        <div class="product-info">
          <div class="product-name">{{ item.name }}</div>
        </div>
        <div class="product-spec-text">
          <div>{{ item.spec1 }}</div>
          <div>{{ item.spec2 }}</div>
        </div>
        <div class="product-price">¥{{ item.price }}</div>
        <div class="product-quantity">{{ item.quantity }}</div>
        <div class="product-subtotal">¥{{ item.subtotal }}</div>
      </div>
    </div>

    <div class="summary-info">
      共导入<em>{{ totalProducts }}</em
      >件商品
    </div>

    <div class="address-section">
      <div class="section-header">
        <span class="section-title">收货地址</span>
        <div class="section-actions">
          <el-button type="primary" link @click="handleConfirmAddress"
            ><el-icon><Location /></el-icon> 确认收货地址</el-button
          >
          <el-button type="primary" link @click="handleManageAddress"
            ><el-icon><Setting /></el-icon> 管理地址</el-button
          >
        </div>
      </div>
      <div class="address-list">
        <div
          v-for="(addr, index) in addressList"
          :key="index"
          :class="['address-card', { active: selectedAddress === index }]"
          @click="selectedAddress = index"
        >
          <div class="address-detail">{{ addr.province }} {{ addr.city }} {{ addr.district }}{{ addr.detail }}</div>
          <div class="address-company">{{ addr.company }}</div>
          <div class="address-phone">{{ addr.phone }}</div>
        </div>
      </div>
      <el-button type="primary" link class="expand-btn" @click="showAllAddress = !showAllAddress">
        {{ showAllAddress ? '收起地址' : '展开全部地址' }} <el-icon><ArrowDown /></el-icon>
      </el-button>
    </div>

    <div class="delivery-section">
      <span class="label">配送时间</span>
      <el-date-picker v-model="deliveryDate" type="date" placeholder="请选择日期" style="width: 200px" />
    </div>

    <div class="remark-section">
      <span class="label">订单备注</span>
      <el-input
        v-model="orderRemark"
        type="textarea"
        :rows="3"
        placeholder="请输入详细地址，省市区无需重复输入"
        maxlength="50"
        show-word-limit
        style="flex: 1"
      />
    </div>

    <div class="submit-bar">
      <div class="total-info">
        共<em>{{ availableProducts }}</em
        >件商品
      </div>
      <div class="total-amount">
        合计: <span class="amount">¥{{ totalAmount }}</span>
      </div>
      <el-button type="danger" size="large" @click="handleSubmitOrder">去下单</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Picture, Location, Setting, ArrowDown } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';
import { getPcProductPage } from '@/api/search/index';
import { getAddressList } from '@/api/pc/enterprise/index';
import { pcOrdersubmit } from '@/api/goods/index';
import templateFile from './商品导入模版.xlsx?url';

const router = useRouter();
const selectedAddress = ref(0);
const showAllAddress = ref(false);
const deliveryDate = ref('');
const orderRemark = ref('');
const importing = ref(false);
const fileInputRef = ref<HTMLInputElement | null>(null);

const productList = ref<any[]>([]);

const addressList = ref<any[]>([]);

const loadAddressList = async () => {
  try {
    const res: any = await getAddressList();
    const list: any[] = res?.rows || res?.data || [];
    addressList.value = list.map((item: any) => ({
      ...item,
      province: item.province || '',
      city: item.city || '',
      district: item.district || '',
      detail: item.detailAddress || '',
      company: item.consignee || '',
      phone: item.phone || ''
    }));
    if (addressList.value.length > 0) {
      selectedAddress.value = 0;
    }
  } catch (e) {
    ElMessage.error('收货地址加载失败');
  }
};

onMounted(() => {
  loadAddressList();
});

const totalProducts = computed(() => productList.value.length);
const unavailableProducts = computed(() => productList.value.filter((p) => p.offShelf).length);
const availableProducts = computed(() => productList.value.filter((p) => !p.offShelf).length);
const totalAmount = computed(() =>
  productList.value
    .filter((p) => !p.offShelf)
    .reduce((sum, p) => sum + parseFloat(p.subtotal || '0'), 0)
    .toFixed(2)
);
const freight = ref('12.00');

/** 下载标准导入模板 */
const handleDownloadTemplate = () => {
  const link = document.createElement('a');
  link.href = templateFile;
  link.download = '商品导入模版.xlsx';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success('开始下载模板文件');
};

/** 点击按钮触发文件选择 */
const handleImportProducts = () => {
  fileInputRef.value?.click();
};

/** 解析 Excel 文件，提取商品编号和数量，调用接口查询商品信息 */
const handleFileChange = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (!file) return;

  // 重置 input，允许再次选择同一文件
  (event.target as HTMLInputElement).value = '';

  importing.value = true;
  try {
    const arrayBuffer = await file.arrayBuffer();
    const workbook = XLSX.read(arrayBuffer, { type: 'array' });
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    // 从第1行（索引0）读取数据，转为对象数组（第一行为表头）
    const rows: any[] = XLSX.utils.sheet_to_json(worksheet, { defval: '' });

    if (rows.length === 0) {
      ElMessage.warning('Excel 文件中没有数据');
      return;
    }

    // 找到商品编号和商品数量对应的列名（兼容中英文列名）
    const firstRow = rows[0];
    const keys = Object.keys(firstRow);
    const productNoKey = keys.find((k) => k.includes('商品编号') || k.toLowerCase().includes('productno') || k.toLowerCase() === 'no');
    const quantityKey = keys.find(
      (k) => k.includes('商品数量') || k.includes('数量') || k.toLowerCase().includes('quantity') || k.toLowerCase() === 'qty'
    );

    if (!productNoKey) {
      ElMessage.error('未找到"商品编号"列，请检查模板格式');
      return;
    }
    if (!quantityKey) {
      ElMessage.error('未找到"商品数量"列，请检查模板格式');
      return;
    }

    // 提取有效行（商品编号不为空）
    const validRows = rows.filter((row) => row[productNoKey] !== '' && row[productNoKey] != null);
    if (validRows.length === 0) {
      ElMessage.warning('Excel 中没有有效的商品编号');
      return;
    }

    // 逐个查询商品信息
    const results: any[] = [];
    for (const row of validRows) {
      const productNo = String(row[productNoKey]).trim();
      const quantity = Number(row[quantityKey]) || 1;
      try {
        const res = await getPcProductPage({ productNo, pageNum: 1, pageSize: 1 });
        if (res.code === 200 && res.rows && res.rows.length > 0) {
          const product = res.rows[0];
          const price = String(product.price || product.memberPrice || product.minSellingPrice || '0');
          const subtotal = (parseFloat(price) * quantity).toFixed(2);
          results.push({
            id: product.id,
            image: product.productImage || '',
            name: product.itemName || productNo,
            spec1: product.productNo || productNo,
            spec2: product.unitName || '',
            price,
            quantity,
            subtotal,
            offShelf: product.productStatus === '0'
          });
        } else {
          // 接口未找到商品，提示下架但不加入列表
          ElMessage.warning(`商品 ${productNo} 已下架或不存在，未加入当前订单`);
        }
      } catch {
        ElMessage.warning(`商品 ${productNo} 查询失败，可能已下架，未加入当前订单`);
      }
    }

    productList.value = results;
    ElMessage.success(`成功导入 ${results.length} 件商品`);
  } catch (e) {
    ElMessage.error('文件解析失败，请检查文件格式');
  } finally {
    importing.value = false;
  }
};

const handleConfirmAddress = () => {
  ElMessage.success('已确认收货地址');
};
const handleManageAddress = () => {
  router.push('/easybuv');
};
const handleSubmitOrder = async () => {
  if (availableProducts.value === 0) {
    ElMessage.warning('没有可下单的商品');
    return;
  }

  if (selectedAddress.value === null || selectedAddress.value === undefined) {
    ElMessage.warning('请选择收货地址');
    return;
  }

  const address = addressList.value[selectedAddress.value];
  if (!address || !address.id) {
    ElMessage.warning('收货地址信息不完整');
    return;
  }

  // 构建商品信息
  const productInfo = productList.value
    .filter((p) => !p.offShelf)
    .map((p) => ({
      productId: p.id,
      productNum: p.quantity
    }));

  if (productInfo.length === 0) {
    ElMessage.warning('没有可下单的商品');
    return;
  }

  // 格式化配送时间
  let deliveryDateStr = '';
  if (deliveryDate.value) {
    const date = new Date(deliveryDate.value);
    deliveryDateStr = date.toISOString().split('T')[0]; // yyyy-MM-dd
  }

  const submitData = {
    shippingAddressId: address.id,
    deliveryDate: deliveryDateStr,
    payType: '', // 支付方式，根据业务需求填写
    expenseType: '', // 费用类型，根据业务需求填写
    purchaseReason: '', // 采购事由，根据业务需求填写
    remark: orderRemark.value,
    shippingFee: parseFloat(freight.value) || 0,
    placeOrderType: 2, // 2为直接下单
    productShoppingCartId: [], // 批量下单不走购物车
    productInfo: productInfo
  };

  try {
    const res: any = await pcOrdersubmit(submitData);
    if (res.code === 200) {
      ElMessage.success('订单提交成功');
      // 清空商品列表
      productList.value = [];
      // 可以跳转到订单列表页
      // router.push('/order/list');
    } else {
      ElMessage.error(res.msg || '订单提交失败');
    }
  } catch (error: any) {
    ElMessage.error(error?.message || '订单提交失败，请稍后重试');
  }
};
</script>

<style scoped lang="scss">
.batch-order-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  flex: 1;
}
.page-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}
.title-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background: #e60012;
  border-radius: 2px;
}
.action-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}
.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
}
.product-list {
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 15px;
  .product-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f5f5f5;
    &:last-child {
      border-bottom: none;
    }
    .product-image {
      width: 60px;
      height: 60px;
      background: #f5f5f5;
      border-radius: 4px;
      overflow: hidden;
      flex-shrink: 0;
      margin-right: 15px;
      .el-image {
        width: 100%;
        height: 100%;
      }
      .image-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .product-info {
      flex: 1;
      min-width: 0;
      .product-name {
        font-size: 13px;
        color: #333;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }
    .product-spec-text {
      width: 80px;
      text-align: center;
      font-size: 12px;
      color: #666;
    }
    .product-price {
      width: 80px;
      text-align: center;
      font-size: 14px;
      color: #e60012;
    }
    .product-quantity {
      width: 60px;
      text-align: center;
      font-size: 14px;
      color: #333;
    }
    .product-subtotal {
      width: 80px;
      text-align: center;
      font-size: 14px;
      color: #e60012;
    }
    .product-action {
      width: 80px;
      text-align: center;
      .off-shelf {
        color: #e60012;
        font-size: 13px;
      }
    }
  }
}
.summary-info {
  text-align: right;
  font-size: 13px;
  color: #666;
  margin-bottom: 25px;
  em {
    color: #e60012;
    font-style: normal;
    font-weight: bold;
  }
}
.address-section {
  margin-bottom: 25px;
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    .section-actions {
      display: flex;
      gap: 15px;
    }
  }
  .address-list {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    margin-bottom: 10px;
    .address-card {
      width: 200px;
      padding: 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s;
      &:hover {
        border-color: #e60012;
      }
      &.active {
        border-color: #e60012;
        background: #fff5f5;
      }
      .address-detail {
        font-size: 13px;
        color: #333;
        line-height: 1.4;
        margin-bottom: 5px;
      }
      .address-company {
        font-size: 12px;
        color: #666;
        margin-bottom: 3px;
      }
      .address-phone {
        font-size: 12px;
        color: #999;
      }
    }
  }
  .expand-btn {
    font-size: 13px;
  }
}
.delivery-section {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
  .label {
    font-size: 14px;
    color: #333;
    width: 70px;
  }
}
.remark-section {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  margin-bottom: 30px;
  .label {
    font-size: 14px;
    color: #333;
    width: 70px;
    padding-top: 8px;
  }
}
.submit-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
  border-top: 1px solid #eee;
  margin-top: 20px;
  .total-info {
    font-size: 14px;
    color: #666;
    em {
      color: #e60012;
      font-style: normal;
      font-weight: bold;
    }
  }
  .total-amount {
    font-size: 14px;
    color: #333;
    .amount {
      font-size: 20px;
      font-weight: bold;
      color: #e60012;
    }
    .freight {
      font-size: 12px;
      color: #999;
      margin-left: 5px;
    }
  }
}
</style>
