<template>
  <view class="page">
    <scroll-view scroll-y class="content" v-if="!loading">
      <!-- 基本信息 -->
      <view class="section">
        <view class="section-title">
          <text>基本信息</text>
        </view>
        <view class="form-card">
          <view class="form-item">
            <text class="form-label required">申请人姓名</text>
            <input class="form-input" v-model="formData.applicantName" placeholder="请输入申请人姓名" />
          </view>
          <view class="form-item">
            <text class="form-label required">联系电话</text>
            <input class="form-input" v-model="formData.applicantPhone" type="number" placeholder="请输入联系电话" />
          </view>
          <view class="form-item">
            <text class="form-label">部门</text>
            <input class="form-input" v-model="formData.department" placeholder="请输入部门" />
          </view>
          <view class="form-item">
            <text class="form-label">需要时间</text>
            <picker mode="date" :value="formData.neededAt" @change="onDateChange">
              <view class="form-picker">
                <text>{{ formData.neededAt || '请选择需要时间' }}</text>
              </view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">申请原因</text>
            <textarea class="form-textarea" v-model="formData.reason" placeholder="请输入申请原因" maxlength="200" />
          </view>
        </view>
      </view>

      <!-- 物料明细 -->
      <view class="section">
        <view class="section-title">
          <text>物料明细</text>
          <button class="btn-add" @tap="showGoodsModal">+ 添加物料</button>
        </view>
        
        <view v-if="formData.items.length === 0" class="empty-items">
          <text>暂无物料，请点击上方按钮添加</text>
        </view>

        <view v-for="(item, index) in formData.items" :key="index" class="item-card">
          <view class="item-header">
            <text class="item-number">#{{ index + 1 }}</text>
            <button class="btn-delete" @tap="deleteItem(index)">删除</button>
          </view>
          
          <view class="info-row">
            <text class="info-label">物料名称：</text>
            <text class="info-value">{{ item.name }}</text>
          </view>
          
          <view class="info-row" v-if="item.spec">
            <text class="info-label">规格：</text>
            <text class="info-value">{{ item.spec }}</text>
          </view>
          
          <view class="info-row" v-if="item.unit">
            <text class="info-label">单位：</text>
            <text class="info-value">{{ item.unit }}</text>
          </view>
          
          <view class="info-row" v-if="item.estimatedUnitCost">
            <text class="info-label">单价：</text>
            <text class="info-value price">¥{{ item.estimatedUnitCost }}</text>
          </view>
          
          <view class="form-item">
            <text class="form-label required">数量</text>
            <input class="form-input" v-model.number="item.quantity" type="digit" placeholder="请输入数量" />
          </view>
          
          <view class="form-item">
            <text class="form-label">备注</text>
            <textarea class="form-textarea" v-model="item.remark" placeholder="请输入备注" maxlength="100" />
          </view>
        </view>
      </view>
    </scroll-view>

    <view v-if="loading" class="loading-container">
      <text>加载中...</text>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions" v-if="!loading">
      <button class="btn-secondary" @tap="goBack">取消</button>
      <button class="btn-primary" @tap="submitForm" :disabled="submitting">
        {{ submitting ? '保存中...' : '保存修改' }}
      </button>
    </view>

    <!-- 商品选择弹窗 -->
    <view v-if="showModal" class="modal-mask" @tap="closeGoodsModal">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">选择物料</text>
          <text class="modal-close" @tap="closeGoodsModal">✕</text>
        </view>
        <view class="modal-search">
          <input class="search-input" v-model="goodsSearch" placeholder="搜索物料名称" @confirm="searchGoods" />
          <button class="search-btn" @tap="searchGoods">搜索</button>
        </view>
        <scroll-view scroll-y class="modal-list" @scrolltolower="loadMoreGoods">
          <view v-for="goods in goodsList" :key="goods.id" class="goods-item">
            <view class="goods-name">{{ goods.goodsName }}</view>
            <view v-if="goods.brand" class="goods-brand">品牌：{{ goods.brand }}</view>
            
            <!-- SKU列表 -->
            <view class="sku-list">
              <view v-for="sku in goods.skus" :key="sku.id" 
                    class="sku-item" 
                    @tap="selectSKU(goods, sku)">
                <view class="sku-info">
                  <text v-if="sku.specification" class="sku-spec">{{ sku.specification }}</text>
                  <text v-if="sku.unit" class="sku-unit">{{ sku.unit }}</text>
                </view>
                <view class="sku-price" v-if="sku.purchasePrice">
                  ¥{{ sku.purchasePrice }}
                </view>
              </view>
            </view>
          </view>
          
          <view v-if="goodsLoading" class="loading">
            <text>加载中...</text>
          </view>
          
          <view v-if="!hasMoreGoods && goodsList.length > 0" class="no-more">
            <text>没有更多了</text>
          </view>
          
          <view v-if="goodsList.length === 0 && !goodsLoading" class="empty">
            <text>暂无数据，请尝试搜索</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import consumableTempAPI, { type RequestItem, type GoodsWithSKU, type SKUResponse } from '@/pages/api/consumable-temp'

// 表单数据
const formData = ref({
  applicantName: '',
  applicantPhone: '',
  department: '',
  reason: '',
  neededAt: '',
  items: [] as RequestItem[]
})

const loading = ref(true)
const submitting = ref(false)
const requestId = ref('')
const showModal = ref(false)
const goodsList = ref<GoodsWithSKU[]>([])
const goodsSearch = ref('')
const goodsLoading = ref(false)
const goodsPage = ref(1)
const goodsPageSize = ref(10)
const hasMoreGoods = ref(true)

// 加载详情
async function loadDetail() {
  if (!requestId.value) return
  
  loading.value = true
  
  try {
    const res = await consumableTempAPI.getRequestDetail(requestId.value)
    
    if (res.statusCode === 200 && (res.data as any)?.data) {
      const detail = (res.data as any).data
      
      // 填充表单数据
      formData.value.applicantName = detail.applicantName || ''
      formData.value.applicantPhone = detail.applicantPhone || ''
      formData.value.department = detail.department || ''
      formData.value.reason = detail.reason || ''
      formData.value.neededAt = detail.neededAt ? detail.neededAt.split('T')[0] : ''
      
      // 填充物料明细
      formData.value.items = detail.items?.map((item: any) => ({
        name: item.name || '',
        spec: item.spec || '',
        quantity: item.quantity || 1,
        unit: item.unit || '',
        estimatedUnitCost: item.estimatedUnitCost || 0,
        remark: item.remark || ''
      })) || []
    } else {
      uni.showToast({ title: '加载失败', icon: 'none' })
      setTimeout(() => uni.navigateBack(), 1500)
    }
  } catch (err) {
    console.error('加载详情失败：', err)
    uni.showToast({ title: '加载失败', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 1500)
  } finally {
    loading.value = false
  }
}

// 显示商品选择弹窗
function showGoodsModal() {
  showModal.value = true
  goodsPage.value = 1
  hasMoreGoods.value = true
  goodsList.value = []
  goodsSearch.value = ''
  loadGoods()
}

// 关闭商品选择弹窗
function closeGoodsModal() {
  showModal.value = false
  goodsList.value = []
  goodsSearch.value = ''
}

// 加载商品列表
async function loadGoods(reset = false) {
  if (goodsLoading.value) return
  
  if (reset) {
    goodsPage.value = 1
    hasMoreGoods.value = true
    goodsList.value = []
  }
  
  if (!hasMoreGoods.value) return
  
  goodsLoading.value = true
  
  try {
    const res = await consumableTempAPI.getConsumableGoods({
      page: goodsPage.value,
      pageSize: goodsPageSize.value,
      q: goodsSearch.value || undefined,
      status: 0 // 只查询正常状态的商品
    })
    
    if (res.statusCode === 200 && (res.data as any)?.data) {
      const newData = (res.data as any).data
      goodsList.value = reset ? newData : [...goodsList.value, ...newData]
      hasMoreGoods.value = newData.length >= goodsPageSize.value
    }
  } catch (err) {
    console.error('加载商品列表失败：', err)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    goodsLoading.value = false
  }
}

// 搜索商品
function searchGoods() {
  loadGoods(true)
}

// 加载更多商品
function loadMoreGoods() {
  if (!goodsLoading.value && hasMoreGoods.value) {
    goodsPage.value++
    loadGoods()
  }
}

// 选择SKU
function selectSKU(goods: GoodsWithSKU, sku: SKUResponse) {
  const newItem: RequestItem = {
    name: goods.goodsName,
    spec: sku.specification || '',
    quantity: 1,
    unit: sku.unit || '',
    estimatedUnitCost: sku.purchasePrice || 0,
    remark: ''
  }
  
  formData.value.items.push(newItem)
  closeGoodsModal()
  
  uni.showToast({ 
    title: '已添加', 
    icon: 'success',
    duration: 1000
  })
}

// 日期改变
function onDateChange(e: any) {
  formData.value.neededAt = e.detail.value
}

// 删除物料
function deleteItem(index: number) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个物料吗？',
    success: (res) => {
      if (res.confirm) {
        formData.value.items.splice(index, 1)
      }
    }
  })
}

// 表单验证
function validateForm() {
  if (!formData.value.applicantPhone) {
    uni.showToast({ title: '请输入联系电话', icon: 'none' })
    return false
  }
  
  if (formData.value.applicantPhone.length < 3) {
    uni.showToast({ title: '联系电话格式不正确', icon: 'none' })
    return false
  }
  
  if (formData.value.items.length === 0) {
    uni.showToast({ title: '请至少添加一项物料', icon: 'none' })
    return false
  }
  
  for (let i = 0; i < formData.value.items.length; i++) {
    const item = formData.value.items[i]
    if (!item.quantity || item.quantity <= 0) {
      uni.showToast({ title: `第${i + 1}项物料数量必须大于0`, icon: 'none' })
      return false
    }
  }
  
  return true
}

// 提交表单
async function submitForm() {
  if (!validateForm()) return
  
  if (submitting.value) return
  
  submitting.value = true
  
  try {
    const res = await consumableTempAPI.updateRequest(requestId.value, formData.value)
    
    if (res.statusCode === 200) {
      uni.showToast({ 
        title: '保存成功', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            // 通知列表页需要刷新
            uni.$emit('tempRequest:changed')
            uni.navigateBack()
          }, 1500)
        }
      })
    } else {
      uni.showToast({ title: '保存失败', icon: 'none' })
    }
  } catch (err) {
    console.error('保存失败：', err)
    uni.showToast({ title: '保存失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

// 返回
function goBack() {
  uni.showModal({
    title: '提示',
    content: '确定要放弃当前修改吗？',
    success: (res) => {
      if (res.confirm) {
        uni.navigateBack()
      }
    }
  })
}

onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  const options = currentPage.options || {}
  
  if (options.id) {
    requestId.value = options.id
    loadDetail()
  } else {
    uni.showToast({ title: '参数错误', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 1500)
  }
})
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f7fb;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.content {
  flex: 1;
  padding: 24rpx 32rpx 140rpx;
  box-sizing: border-box;
}

.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
}

.section {
  margin-bottom: 32rpx;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12rpx 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  color: #111;
}

.btn-add {
  padding: 8rpx 20rpx;
  margin: 0;
  height: 56rpx;
  line-height: 40rpx;
  background: #3a5ddd;
  color: #fff;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.form-card,
.item-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
}

.item-card {
  margin-bottom: 24rpx;
  position: relative;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.item-number {
  font-size: 28rpx;
  font-weight: 600;
  color: #4b7aff;
}

.btn-delete {
  padding: 8rpx 16rpx;
  height: 48rpx;
  line-height: 32rpx;
  background: #ffebee;
  color: #c62828;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.info-row {
  display: flex;
  margin-bottom: 12rpx;
  font-size: 28rpx;
}

.info-label {
  color: #666;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  color: #333;
  flex: 1;
}

.info-value.price {
  color: #f57c00;
  font-weight: 600;
}

.form-item {
  margin-bottom: 24rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-label.required::before {
  content: '*';
  color: #ff4d4f;
  margin-right: 4rpx;
}

.form-input,
.form-picker {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  background: #f5f7fb;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 16rpx 24rpx;
  background: #f5f7fb;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333;
}

.form-picker {
  display: flex;
  align-items: center;
}

.empty-items {
  padding: 80rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #999;
  background: #fff;
  border-radius: 20rpx;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.06);
  display: flex;
  gap: 16rpx;
}

.btn-secondary,
.btn-primary {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
}

.btn-secondary {
  background: #f5f5f5;
  color: #666;
}

.btn-primary {
  background: #3a5ddd;
  color: #fff;
}

.btn-primary[disabled] {
  opacity: 0.6;
}

/* 弹窗样式 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.modal-content {
  width: 100%;
  max-height: 80vh;
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #111;
}

.modal-close {
  font-size: 40rpx;
  color: #999;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-search {
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  gap: 12rpx;
}

.search-input {
  flex: 1;
  height: 72rpx;
  line-height: 72rpx;
  padding: 0 24rpx;
  background: #f5f7fb;
  border-radius: 12rpx;
  font-size: 28rpx;
}

.search-btn {
  padding: 0 32rpx;
  height: 72rpx;
  line-height: 72rpx;
  background: #3a5ddd;
  color: #fff;
  border-radius: 12rpx;
  font-size: 28rpx;
  white-space: nowrap;
}

.modal-list {
  flex: 1;
  padding: 12rpx 0;
}

.goods-item {
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.goods-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.goods-brand {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 12rpx;
}

.sku-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.sku-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 16rpx;
  background: #f5f7fb;
  border-radius: 8rpx;
}

.sku-info {
  display: flex;
  gap: 12rpx;
  font-size: 26rpx;
  color: #666;
}

.sku-spec {
  color: #333;
}

.sku-unit {
  color: #999;
}

.sku-price {
  font-size: 28rpx;
  font-weight: 600;
  color: #f57c00;
}

.loading,
.no-more {
  padding: 32rpx;
  text-align: center;
  font-size: 26rpx;
  color: #999;
}

.empty {
  padding: 80rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}
</style>
