<template>
  <ElTabs
    v-model="activeTab"
    v-loading="loading"
    class="detail-tabs"
    @tab-click="handleTabClick"
  >
    <ElTabPane name="stockProducts" label="备货商品">
      <div class="detail-table-content">
        <TableView
          :serial-numberable="true"
          :columns="stockProductsColumns"
          :paginated-data="stockProductsData"
        />
      </div>
    </ElTabPane>
    <ElTabPane name="relatedDocuments" label="关联单据">
      <div class="detail-table-content">
        <TableView
          :serial-numberable="true"
          :columns="relatedDocumentsColumns"
          :paginated-data="relatedDocumentsData"
        />
      </div>
    </ElTabPane>
    <ElTabPane name="internalMemo" label="内部便签">
      <div class="detail-table-content memo-content">
        <div class="memo-input-wrapper">
          <ElInput
            v-model="memoInputValue"
            placeholder="请输入内容"
            clearable
            class="memo-input"
          />
          <ElButton type="primary" :loading="addingMemo" @click="handleAddMemo">
            添加
          </ElButton>
        </div>
        <div class="memo-list">
          <template v-if="internalMemoData.length > 0">
            <div
              v-for="item in internalMemoData"
              :key="item.id"
              class="memo-item"
            >
              <span class="memo-user">{{ item.operatorEmployeeName }}：</span>
              <span class="memo-text">{{ item.content }}</span>
              <span class="memo-time">({{ item.operatorTime }})</span>
            </div>
          </template>
          <div v-else class="empty-content">暂无数据</div>
        </div>
      </div>
    </ElTabPane>
    <ElTabPane name="operationLog" label="操作日志">
      <div class="detail-table-content">
        <LogList :log-list="operationLogData" />
        <div class="empty-content">暂无数据</div>
      </div>
    </ElTabPane>
  </ElTabs>
</template>

<script setup lang="tsx">
import { ref } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import TableView from '@/components/TableView.vue'
import {
  InternalMemoList,
  LogListData,
  RelatedDocumentList,
  StockingOrderProduct,
  TableData,
} from '@/types/api/supply/stockingOrder'
import ImageView from '@/components/ImageView.vue'
import {
  addStockingOrderInternalTagApi,
  getStockingOrderDetailListByIdApi,
  getStockingOrderInternalMemoListByIdApi,
  getStockingOrderLogListByIdApi,
  getStockingOrderRelatedDocumentListByIdApi,
} from '@/api/supplier/stockingOrder'
import { ElMessage } from 'element-plus'
import LogList from '@/components/LogList.vue'
const relatedDocumentsColumns = computed(() => {
  return [
    {
      label: '关联单据',
      prop: 'warehouseApplyNo',
      align: 'center',
    },
    {
      label: '关联单号',
      prop: 'manageNo',
      align: 'center',
    },
    {
      label: '制单人',
      width: 120,
      prop: 'createUserName',
      align: 'center',
    },
    {
      label: '制单时间',
      width: 160,
      prop: 'createTime',
      align: 'center',
    },
    {
      label: 'SKU个数',
      width: 120,
      align: 'right',
      prop: 'skuTotal',
    },
    {
      label: '入库数量',
      width: 120,
      align: 'right',
      prop: 'buyStored',
    },
    {
      label: '申请数量',
      width: 120,
      prop: 'total',
      align: 'right',
    },
    {
      label: '预计到货日期',
      width: 160,
      align: 'center',
      prop: 'expectDeliveryTime',
    },
    {
      label: '实际到货日期',
      width: 160,
      align: 'center',
      prop: 'deliveryTime',
    },
  ]
})
const stockProductsColumns = computed(() => {
  return [
    {
      label: 'SKU图片',
      prop: 'skuImage',
      width: 100,
      align: 'center',
      render: (item: StockingOrderProduct) => (
        <ImageView src={item.warehouseSkuImage} width="50px" height="50px" />
      ),
    },
    {
      label: '商品名称',
      prop: 'warehouseSkuName',
      minWidth: 200,
      align: 'left',
    },
    {
      label: '款号',
      prop: 'productNo',
      width: 120,
      align: 'center',
    },
    {
      label: '库存SKU',
      prop: 'warehouseSku',
      width: 180,
      align: 'center',
    },
    {
      label: '备货数量',
      prop: 'buyAmount',
      width: 100,
      align: 'right',
    },
    {
      label: '备货单价',
      prop: 'price',
      width: 100,
      align: 'right',
    },
    {
      label: '备货金额',
      prop: 'totalPrice',
      width: 120,
      align: 'right',
    },
    {
      label: '已发货数量',
      prop: 'shipmentQuantity',
      width: 120,
      align: 'right',
    },
    {
      label: '已入库数量',
      prop: 'buyStored',
      width: 120,
      align: 'right',
    },
    {
      label: '不良品数量',
      prop: 'rejectsAmount',
      width: 120,
      align: 'right',
    },
  ]
})
const props = defineProps<{
  selectedRow: TableData | null
}>()

const stockProductsData = ref<StockingOrderProduct[]>([])
const relatedDocumentsData = ref<RelatedDocumentList[]>([])
const internalMemoData = ref<InternalMemoList[]>([])
const operationLogData = ref<LogListData[]>([])
const activeTab = ref('stockProducts')
const loading = ref(false)
const memoInputValue = ref('')
const addingMemo = ref(false)

const handleAddMemo = async () => {
  if (!memoInputValue.value.trim()) {
    ElMessage.warning('请输入内容')
    return
  }
  if (!props.selectedRow) return

  addingMemo.value = true
  try {
    const res = await addStockingOrderInternalTagApi(
      memoInputValue.value.trim(),
      [props.selectedRow.id],
    )
    if (res.code === 200) {
      ElMessage.success('添加成功')
      memoInputValue.value = ''
      loadInternalMemo(props.selectedRow)
    }
  } catch (e) {
    console.error(e)
  } finally {
    addingMemo.value = false
  }
}
watch(
  () => props.selectedRow,
  (newVal) => {
    if (newVal) {
      if (activeTab.value === 'stockProducts') {
        loadStockProducts(newVal)
      } else if (activeTab.value === 'relatedDocuments') {
        loadRelatedDocuments(newVal)
      } else if (activeTab.value === 'internalMemo') {
        loadInternalMemo(newVal)
      } else if (activeTab.value === 'operationLog') {
        loadOperationLog(newVal)
      }
    } else {
      stockProductsData.value = []
      relatedDocumentsData.value = []
      internalMemoData.value = []
      operationLogData.value = []
    }
  },
)
const loadStockProducts = async (row: TableData) => {
  loading.value = true
  try {
    const res = await getStockingOrderDetailListByIdApi(row.id)
    if (res.code !== 200) return
    stockProductsData.value = res.data || []
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const loadRelatedDocuments = async (row: TableData) => {
  loading.value = true
  try {
    const res = await getStockingOrderRelatedDocumentListByIdApi(row.id)
    if (res.code !== 200) return
    relatedDocumentsData.value = res.data || []
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const loadInternalMemo = async (row: TableData) => {
  loading.value = true
  try {
    const res = await getStockingOrderInternalMemoListByIdApi(row.id)
    if (res.code !== 200) return
    internalMemoData.value = res.data || []
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const loadOperationLog = async (row: TableData) => {
  loading.value = true
  try {
    const res = await getStockingOrderLogListByIdApi(row.id)
    if (res.code !== 200) return
    operationLogData.value = res.data || []
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const handleTabClick = (tab: TabsPaneContext) => {
  activeTab.value = tab.paneName as string
  if (!props.selectedRow) return
  if (activeTab.value === 'stockProducts') {
    loadStockProducts(props.selectedRow as TableData)
  } else if (activeTab.value === 'relatedDocuments') {
    loadRelatedDocuments(props.selectedRow as TableData)
  } else if (activeTab.value === 'internalMemo') {
    loadInternalMemo(props.selectedRow as TableData)
  } else if (activeTab.value === 'operationLog') {
    loadOperationLog(props.selectedRow as TableData)
  }
}
</script>

<style lang="scss" scoped>
.detail-tabs {
  height: 100%;
  display: flex;
  :deep(.el-tab-pane) {
    height: 100%;
    overflow: hidden;
  }
}

.detail-table-content {
  height: 100%;
  overflow: hidden;
}

.empty-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.memo-content {
  display: flex;
  flex-direction: column;
}

.memo-input-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;

  .memo-input {
    flex: 1;
    max-width: 300px;
  }
}

.memo-list {
  flex: 1;
  overflow-y: auto;
}

.memo-item {
  padding: 8px 0;
  font-size: 14px;
  line-height: 1.5;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .memo-user {
    color: #409eff;
  }

  .memo-text {
    color: #303133;
  }

  .memo-time {
    color: #909399;
    margin-left: 8px;
  }
}
</style>
