<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card shadow="never">
      <el-form :model="queryParams" inline>
        <TenantSelect v-model="queryParams.tenantIds" placeholder="请选择机构名称" prop="tenantIds" />

        <el-form-item label="入库状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择入库状态" clearable class="!w-160px">
            <el-option
              v-for="(item, index) in getStrDictOptions(DICT_TYPE.MATERIALS_TYPE_NANSHA)"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库日期" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :unlink-panels="true"
          />
        </el-form-item>
        <el-form-item label="入库单号" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入入库单号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮和表格 -->
    <el-card shadow="never" class="mt-4">
      <div class="mb-4">
        <el-button v-hasPermi="['warehouses:materialsIn:add']" type="primary" plain @click="handleAdd"><Icon icon="ep:plus" class="mr-5px" />新增</el-button>
        <el-button v-hasPermi="['warehouses:materialsIn:import']" type="success" @click="openImport"><Icon icon="ep:download" class="mr-5px" />导入</el-button>
      </div>

      <el-table :data="tableData" v-loading="loading" :header-cell-style="tableHeaderColor">
        <el-table-column prop="orderNo" label="入库单号" align="center" width="280" />
        <el-table-column prop="orderDate" label="入库日期" align="center" max-width="120" />
        <el-table-column prop="status" label="入库状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStrDictOptions(DICT_TYPE.MATERIALS_TYPE_NANSHA)?.find(item => item.value == row.status)?.colorType || 'info'">{{ getStrDictOptions(DICT_TYPE.MATERIALS_TYPE_NANSHA)?.find(item => item.value == row.status)?.label || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="detailSummary" label="入库明细" align="center" width="400" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="260">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button v-hasPermi="['warehouses:materialsIn:edit']" link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button v-hasPermi="['warehouses:materialsIn:export']" link type="success" @click="handleExport(row.id)" :loading="exportLoading">导出</el-button>
            <el-button v-hasPermi="['warehouses:materialsIn:print']" link type="primary" @click="handlePrint(row)">打印</el-button>
            <el-button v-hasPermi="['warehouses:materialsIn:delete']" link type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button v-hasPermi="['warehouses:materialsIn:generateOutbound']" link type="primary" @click="handleGenerateOutbound(row)">生成出库单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="mt-4"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑/查看弹窗 (抽成组件) -->
    <MaterialsInDialog
      v-model="dialogVisible"
      :mode="dialogMode"
      :form-data="form"
      :material-options="materialOptions"
      :warehouse-options="warehouseOptions"
      @refresh="getTableData"
    />
    <GenerateOutboundDialog
      v-model="generateOutboundVisible"
      :inbound-order-id="generateInboundOrderId"
      :tenant-id="generateTenantId"
      :department-options="departmentOptions"
      @success="getTableData"
    />
    <Print ref="printRef" />
    <!-- 导入弹窗（复用 system/user 的 ImportFile 组件） -->
    <Import ref="importRef" :config="importConfig" @success="handleImportSuccess" />
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeList } from '@/api/material/storeManage'
import { useUserStore } from '@/store/modules/user'
import { materialIoPage,getMaterialIoInboundDetail,materialIoDelete, exportMaterialInbound } from '@/api/material/stockInAndOut'
import { materialList } from '@/api/material/basicMessage'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import Import from '@/components/ImportFile/index.vue'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'

const message = useMessage()

const MaterialsInDialog = defineAsyncComponent(() => import('./components/MaterialsInDialog.vue'))
const GenerateOutboundDialog = defineAsyncComponent(() => import('./components/GenerateOutboundDialog.vue'))
const Print = defineAsyncComponent(() => import('./components/Print.vue'))

const userStore = useUserStore()  
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: '',
  dateRange: [new Date(new Date().setMonth(new Date().getMonth() - 1)).toISOString().split('T')[0], new Date().toISOString().split('T')[0]],
  orderNo: '',
  tenantIds: userStore.orgTenantId,
})
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const printRef = ref(null)
const exportLoading = ref(false)

// 弹窗
const dialogVisible = ref(false)
const dialogMode = ref('add') // 'add', 'edit', 'view'
const generateOutboundVisible = ref(false)
const generateInboundOrderId = ref(undefined)
const generateTenantId = ref(undefined)

const initialForm = {
  id: null,
  orderDate: new Date().toISOString().split('T')[0],
  bizType: 'IN',
  inSource: '',
  inReason: '',
  remark: '',
  items: [],
  // 查看模式下的字段
  auditResult: '',
  auditor: '',
  auditTime: '',
  auditRemark: '',
}

const form = reactive({ ...initialForm })

// 模拟的物资选项 (用于 el-select-v2)
const materialOptions = ref([])

// 模拟的仓库选项
const warehouseOptions = ref([])

// 部门下拉
const departmentOptions = ref([])

// 导入（复用 ImportFile 组件）
const importRef = ref()
const importConfig = reactive({
  title: '物资入库导入',
  // TODO: 替换成你的真实导入接口
  importUrl: '/material-io/inbound/import',
  excelTempName: '物资入库导入模板',
  // TODO: 替换成你的真实模板下载接口
  downloadUrl: '/material-io/inbound/import-template',
  desc: '物资入库',
  // TODO: 如果后端支持失败信息导出，填真实接口；不支持可留空
  failExportUrl: '',
})

const openImport = () => {
  importRef.value?.open?.()
}

const handleImportSuccess = () => {
  // 导入成功后刷新列表
  getTableData()
}

const getMaterialOptions = async () => {
  try {
    const res = await materialList({ 
      tenantId: queryParams.tenantIds && queryParams.tenantIds.length ? queryParams.tenantIds[0] : undefined
    })
    const data = res ?? []
    materialOptions.value = Array.isArray(data) ? data : []
  } catch (e) {
    ElMessage.error(e?.message || '获取物资列表失败')
    materialOptions.value = []
  }
}

const handleExport = async (id) => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportMaterialInbound(id)
    download.excel(data, '入库单据明细.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const tableHeaderColor = ({ rowIndex }) => {
  if (rowIndex === 0) {
    return {
      backgroundColor: '#f8f8f9',
      color: '#666666',
      fontWeight: 'bold'
    }
  }
}

const fetchStoreOptions = async () => {
  try {
    const res = await storeList({ 
      tenantIds: queryParams.tenantIds && queryParams.tenantIds.length ? queryParams.tenantIds : undefined
    })
    const data = res ?? []
    warehouseOptions.value = Array.isArray(data) ? data : []
  } catch (e) {
    ElMessage.error(e?.message || '获取仓库列表失败')
    warehouseOptions.value = []
  }
}

const fetchDepartmentOptions = async () => {
  departmentOptions.value = handleTree(await DeptApi.getSimpleDeptList())
}

// 获取表格数据（分页接口）
const getTableData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      tenantIds: queryParams.tenantIds?.length ? queryParams.tenantIds : undefined,
      bizType: 'IN',
      status: queryParams.status === '' ? undefined : queryParams.status,
      orderNo: queryParams.orderNo || undefined,
      orderDate: queryParams.dateRange || [],
    }
    const res = await materialIoPage(params)
    tableData.value = res.list || []
    total.value = res.total || 0
  } catch (e) {
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getTableData()
})

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  getTableData()
}

// 重置搜索
const handleReset = () => {
  queryParams.status = ''
  queryParams.dateRange = [new Date(new Date().setMonth(new Date().getMonth() - 1)).toISOString().split('T')[0], new Date().toISOString().split('T')[0]]
  queryParams.orderNo = ''
  queryParams.tenantIds = userStore.orgTenantId
  queryParams.pageNo = 1
  getTableData()
}

// 分页
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getTableData()
}
const handleCurrentChange = (page) => {
  queryParams.pageNo = page
  getTableData()
}

// 新增
const handleAdd = () => {
  // 只能选择一个机构
  if(queryParams.tenantIds.length == 0 || queryParams.tenantIds.length > 1){
    ElMessage.error('新增只能选择一个机构')
    return
  }
  getMaterialOptions()
  fetchStoreOptions()
  dialogMode.value = 'add'
  Object.assign(form, { ...initialForm, entryNumber: `RKDH${new Date().getTime()}`, items: [], tenantId:queryParams.tenantIds ? queryParams.tenantIds[0] : undefined })
  dialogVisible.value = true
}

// 查看
const handleView = async (row) => {
  dialogMode.value = 'view'
  try {
    const res = await getMaterialIoInboundDetail(row.id)
    const data = res || {}
    const params = {
      id: data.id || undefined,
      bizType: 'IN',
      orderDate: data.orderDate,
      inSource: data.inSource || undefined,
      inReason: data.inReason || undefined,
      remark: data.remark || undefined,
      tenantId: data.tenantId,
      orderNo: data.orderNo,
      auditResult: data.auditResult || undefined,
      auditor: data.auditor || undefined,
      auditTime: data.auditTime || undefined,
      auditRemark: data.auditRemark || undefined,
      items: (data.items || []).map(item => {
        return {
          ...item,
          quantity: item.inQty || 0,
        }
      }),
    }
    Object.assign(form, JSON.parse(JSON.stringify(params || {})))
    dialogVisible.value = true
  } catch (e) {
    console.error(e)
    ElMessage.error(e?.message || '获取详情失败')
  }
}

// 编辑
const handleEdit = async (row) => {
  // 只能选择一个机构
  if(queryParams.tenantIds.length == 0 || queryParams.tenantIds.length > 1){
    ElMessage.error('编辑只能选择一个机构')
    return
  }
  getMaterialOptions()
  fetchStoreOptions()
  dialogMode.value = 'edit'
  try {
    const res = await getMaterialIoInboundDetail(row.id)
    const data = res || {}
    const params = {
      id: data.id || undefined,
      bizType: 'IN',
      orderDate: data.orderDate,
      inSource: data.inSource || undefined,
      inReason: data.inReason || undefined,
      remark: data.remark || undefined,
      tenantId: data.tenantId,
      orderNo: data.orderNo,
      items: (data.items || []).map(item => {
        return {
          ...item,
          inUnitPrice: item.inUnitPrice || 0,
          saleUnitPrice: item.saleUnitPrice || 0,
          quantity: item.inQty || 0,
        }
      }),
      auditResult: data.auditResult || undefined,
      auditor: data.auditor || undefined,
      auditTime: data.auditTime || undefined,
      auditRemark: data.auditRemark || undefined,
    }
    Object.assign(form, JSON.parse(JSON.stringify(params || {})))
    dialogVisible.value = true
  } catch (e) {
    console.error(e)
    ElMessage.error(e?.message || '获取详情失败')
  }
}

// 打印
const handlePrint = (row) => {
  printRef.value.open(row.id)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除入库单号为 "${row.orderNo}" 的入库单吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async() => {
      // 使用materialIoDelete
      await materialIoDelete(row.id)
      ElMessage.success('删除成功')
      getTableData()
    })
    .catch(() => {})
}

// 生成出库单
const handleGenerateOutbound = async (row) => {
  if(queryParams.tenantIds.length == 0 || queryParams.tenantIds.length > 1){
    ElMessage.error('生成出库单只能选择一个机构')
    return
  }
  await fetchDepartmentOptions()
  generateInboundOrderId.value = row.id
  generateTenantId.value = row.tenantId || (queryParams.tenantIds ? queryParams.tenantIds[0] : undefined)
  generateOutboundVisible.value = true
}
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}
.mb-4 {
  margin-bottom: 16px;
}
</style>
