<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>
            <textarea class="form-textarea" v-model="formData.reason" placeholder="请输入申请原因" maxlength="200" />
          </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>
      </view>

      <!-- 物料明细 -->
      <view class="section">
        <view class="section-title">
          <text>物料明细</text>
          <button class="btn-add" @tap="addItem">+ 添加物料</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="form-item">
            <text class="form-label required">物料名称</text>
            <view class="form-row">
              <input class="form-input flex-1" v-model="item.name" placeholder="请输入物料名称" />
              <button class="btn-catalog" @tap="selectFromCatalog(index)">从目录选择</button>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">规格</text>
            <input class="form-input" v-model="item.spec" placeholder="请输入规格" />
          </view>
          
          <view class="form-row-group">
            <view class="form-item flex-1">
              <text class="form-label required">数量</text>
              <input class="form-input" v-model.number="item.quantity" type="digit" placeholder="数量" />
            </view>
            <view class="form-item flex-1">
              <text class="form-label">单位</text>
              <input class="form-input" v-model="item.unit" placeholder="单位" />
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">预估单价</text>
            <input class="form-input" v-model.number="item.estimatedUnitCost" 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="showCatalogModal" class="modal-mask" @tap="closeCatalog">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">选择物料</text>
          <text class="modal-close" @tap="closeCatalog">✕</text>
        </view>
        <view class="modal-search">
          <input class="search-input" v-model="catalogSearch" placeholder="搜索物料名称" />
        </view>
        <scroll-view scroll-y class="modal-list">
          <view v-for="catalog in filteredCatalog" :key="catalog.id" 
                class="catalog-item" 
                @tap="selectCatalog(catalog)">
            <view class="catalog-name">{{ catalog.name }}</view>
            <view class="catalog-info">
              <text v-if="catalog.spec">{{ catalog.spec }}</text>
              <text v-if="catalog.unit">{{ catalog.unit }}</text>
            </view>
          </view>
          <view v-if="filteredCatalog.length === 0" class="empty">
            <text>暂无数据</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import consumableTempAPI, { type RequestItem, type CatalogItem } 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 currentItemIndex = ref(-1)
const showCatalogModal = ref(false)
const catalogList = ref<CatalogItem[]>([])
const catalogSearch = ref('')

// 过滤后的目录
const filteredCatalog = computed(() => {
  if (!catalogSearch.value) return catalogList.value
  const keyword = catalogSearch.value.toLowerCase()
  return catalogList.value.filter(item => 
    item.name.toLowerCase().includes(keyword) ||
    item.spec?.toLowerCase().includes(keyword)
  )
})

// 加载详情
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 || '',
        catalogId: item.catalogId
      })) || []
    } 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
  }
}

// 加载目录
async function loadCatalog() {
  try {
    const res = await consumableTempAPI.getCatalogList({ 
      isActive: true,
      pageSize: 99
    })
    if (res.statusCode === 200 && (res.data as any)?.data) {
      catalogList.value = (res.data as any).data
    }
  } catch (err) {
    console.error('加载目录失败：', err)
  }
}

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

// 添加物料
function addItem() {
  formData.value.items.push({
    name: '',
    spec: '',
    quantity: 1,
    unit: '',
    estimatedUnitCost: 0,
    remark: ''
  })
}

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

// 从目录选择
function selectFromCatalog(index: number) {
  currentItemIndex.value = index
  showCatalogModal.value = true
}

// 选择目录项
function selectCatalog(catalog: CatalogItem) {
  if (currentItemIndex.value >= 0) {
    const item = formData.value.items[currentItemIndex.value]
    item.name = catalog.name
    item.spec = catalog.spec || ''
    item.unit = catalog.unit || ''
    item.catalogId = catalog.id
  }
  closeCatalog()
}

// 关闭目录弹窗
function closeCatalog() {
  showCatalogModal.value = false
  catalogSearch.value = ''
  currentItemIndex.value = -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.name) {
      uni.showToast({ title: `第${i + 1}项物料名称不能为空`, icon: 'none' })
      return false
    }
    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()
    loadCatalog()
  } 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: #007aff;
  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: #007aff;
}

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

.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;
}

.form-row {
  display: flex;
  gap: 12rpx;
  align-items: center;
}

.form-row .flex-1 {
  flex: 1;
}

.btn-catalog {
  padding: 0 20rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: #e3f2fd;
  color: #1976d2;
  border-radius: 12rpx;
  font-size: 24rpx;
  white-space: nowrap;
}

.form-row-group {
  display: flex;
  gap: 16rpx;
}

.form-row-group .form-item {
  flex: 1;
}

.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: #007aff;
  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;
}

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

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

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

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

.catalog-info {
  font-size: 24rpx;
  color: #999;
  display: flex;
  gap: 16rpx;
}

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