<template>
  <Dialog :title="dialogTitle" width="85%" v-model="dialogVisible" center>
    <ContentWrap class="borderxx">
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="110px">
        <el-form-item label="采购单号" prop="purchaseNo">
          <el-input
v-model="queryParams.purchaseNo" placeholder="采购单号" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>

        <el-form-item label="供应商" prop="supplierName">
          <el-input
v-model="queryParams.supplierName" placeholder="供应商" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>

<!--        <el-form-item label="采购物类型" prop="goodsType">-->
<!--          <el-select v-model="queryParams.goodsType" placeholder="下拉选择" clearable class="!w-240px">-->
<!--            <el-option-->
<!--v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PURCHASE_GOODS_TYPE)" :key="dict.value"-->
<!--              :label="dict.label" :value="dict.value" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item style="margin-left:50px">
          <el-button @click="handleQuery" type="primary">
            <Icon icon="ep:search" class="mr-5px" /> 查询
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" /> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table
ref="purchaseOrderTable" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" class="hl-table"
        @selection-change="handleSelectionChange" @row-click="clickRow" selection>
        <el-table-column type="selection" fixed width="60" />
        <el-table-column fixed label="序号" type="index" align="center" width="60" />
        <el-table-column label="采购单号" align="center" prop="purchaseNo" fixed min-width="190">
          <template #default="scope">
            <el-button link type="primary" >
              {{ scope.row.purchaseNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
label="单据日期" align="center" prop="createTime" :formatter="dateFormatter" min-width="180px"
          fixed>
          <template #default="scope">
            {{
              formatDate(scope.row.createTime, 'YYYY-MM-DD')
            }}
          </template>
        </el-table-column>
        <el-table-column label="供应商" align="center" min-width="180" prop="supplierName" fixed />
        <el-table-column label="采购单类型" align="center" prop="purchaseType" min-width="210">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_PROJECT_PURCHASE_ORDER_TYPE" :value="scope.row.purchaseType" />
          </template>
        </el-table-column>
        <el-table-column label="物料需求计划单号" align="center" prop="materialPlanNo" min-width="220" />
        <el-table-column label="采购物类型" align="center" prop="goodsType" min-width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_PROJECT_PURCHASE_GOODS_TYPE" :value="scope.row.goodsType" />
          </template>
        </el-table-column>

        <el-table-column label="备注" align="center" prop="description" />
        <el-table-column label="收货状态" align="center" prop="status" fixed="right" min-width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_PURCHASE_RECEIVING_STATUS" :value="scope.row.receivingStatus" />
          </template>
        </el-table-column>
<!--        <el-table-column label="单据状态" align="center" prop="status" fixed="right" min-width="180">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :type="DICT_TYPE.HELI_PURCHASE_ORDER_STATUS" :value="scope.row.status" />-->
<!--          </template>-->
<!--        </el-table-column>-->

      </el-table>
      <!-- 分页 -->
      <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </ContentWrap>
    <template #footer>
      <el-button @click="dialogVisible = false" size="large">取 消</el-button>
      <el-button @click="submitForm" type="success" size="large">保 存</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import * as PurchaseOrderApi from '@/api/heli/purchaseorder'
import * as PurchaseOrderNoApi from '@/api/heli/purchaseorderno'
import PurchaseOrderForm from './PurchaseOrderForm.vue'
import { ElTable } from 'element-plus'

defineOptions({ name: 'PurchaseOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  ids: undefined,
  purchaseNo: undefined,
  supplierId: undefined,
  contractNo: undefined,
  purchaseType: 2,
  projectMaterialPlanId: undefined,
  goodsType: 1,
  currencyType: undefined,
  taxRatio: undefined,
  estimatedPrice: undefined,
  actualPrice: undefined,
  status: undefined,
  receivingStatus: undefined,
  submitUserId: undefined,
  submitTime: [],
  auditor: undefined,
  auditTime: [],
  description: undefined,
  creator: undefined,
  createTime: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.ids = undefined
    // const data = await PurchaseOrderApi.getPurchaseOrderPage(queryParams)
    const data = await PurchaseOrderNoApi.getPurchaseOrderNoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = () => {
  if (!purchaseOrderSelection.value || purchaseOrderSelection.value.length <= 0) {
    message.warning(t('common.selectText'))
    return
  }
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success', purchaseOrderSelection.value)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  if (queryParams.createTime !== "Invalid Date" && queryParams.createTime !== "") {
    queryParams.createTime = formatDate(queryParams.createTime, 'YYYY-MM-DD')
  }
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const purchaseOrderTable: any = ref<InstanceType<typeof ElTable>>()
const purchaseOrderSelection: any = ref([])

const handleSelectionChange = (val) => {
  if (val.length > 1) {
    purchaseOrderTable.value.clearSelection()
    purchaseOrderTable.value.toggleRowSelection(val.pop())
  } else {
    purchaseOrderSelection.value = val.pop()
  }

}

// const clickRow = (row: any) => {
//   if (multipleTable.value) { // 检查 multipleTable 是否已初始化
//     if (row) {
//       multipleTable.value.toggleRowSelection(row, undefined);
//     } else {
//       multipleTable.value.clearSelection();
//     }
//   } else {
//     console.error("multipleTable is not initialized."); // 添加错误日志
//   }
// }
const clickRow = (row: any) => {
  if (row) {
    purchaseOrderTable.value!.toggleRowSelection(row, undefined)
  } else {
    purchaseOrderTable.value!.clearSelection()
  }
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  switch (type) {
    case 'create':
      router.push({ path: '/purchase/purchaseorderadd', query: { id: id } })
      break
    case 'edit':
      router.push({ path: '/purchase/purchaseorderedit', query: { id: id } })
      break
    case 'detail':
      router.push({ path: '/purchase/purchaseorderdetail', query: { id: id } })
      break
    default:
      break
  }
}

/** 修改收货状态按钮操作 */
const editReceivingStatus = async (id: number) => {
  try {
    // 提示用户是否保存入库信息
    await message.confirm('确认完成收货?')
    // 发起修改
    await PurchaseOrderApi.updateReceivingStatus(id)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PurchaseOrderApi.deletePurchaseOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

const getIds = async () => {
  queryParams.ids = []
  multipleSelection.value.forEach(item => {
    queryParams.ids.push(item.id)
  })
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    await getIds()
    const data = await PurchaseOrderApi.exportPurchaseOrder(queryParams)
    download.excel(data, '采购订单(直接导出).xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const handleExportWithTax = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    await getIds()
    const data = await PurchaseOrderApi.exportPurchaseOrderWithTax(queryParams)
    download.excel(data, '采购订单(乘税率导出).xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true

  handleQuery()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 初始化 **/
onMounted(async () => {
  await getList()
})
</script>
