<template>
  <el-card class="hl-card">
    <template #header>
      <span>采购订单管理</span>
    </template>
    <ContentWrap class="borderxx">
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
        <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="projectName">
          <el-input
            v-model="queryParams.projectName" placeholder="项目名称" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="子项目名称" prop="projectSubName">
          <el-input
            v-model="queryParams.projectSubName" 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 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
v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" class="hl-table"
        @selection-change="handleSelectionChange" @row-click="clickRow" selection>
        <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" @click="openForm('detail', scope.row.id)">
              {{ scope.row.purchaseNo }}
            </el-button>
          </template>
        </el-table-column>
        <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" min-width="180" prop="supplierName"  />
        <el-table-column label="是否打印" align="center" min-width="180" prop="isPrint"  >
          <template #default="scope">
          <dict-tag :type="DICT_TYPE.HELI_IS_PRINT" :value="scope.row.isPrint" />
        </template>
        </el-table-column>
        <el-table-column label="收货状态" align="center" prop="receivingStatus" 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" fixed="right" min-width="200">
          <template #header>
            <span style="margin-right: 30%">操作</span>
          </template>
          <template #default="scope">
            <el-button link type="primary" @click="openForm('detail', scope.row.id)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
    </ContentWrap>

  </el-card>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import * as PurchaseOrderApi from '@/api/heli/purchaseorder'
import * as PurchaseOrderNoApi from '@/api/heli/purchaseorderno'
import { ElTable } from 'element-plus'
import dayjs from "dayjs";
import {useUserStore} from "@/store/modules/user";

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

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

const handleSelectionChange = (val: PurchaseOrderApi.PurchaseOrderVO[]) => {
  multipleSelection.value = val

}

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) {
//     multipleTable.value!.toggleRowSelection(row, undefined)
//   } else {
//     multipleTable.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/purchaseordernomanagementdetail', 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
  }
}
/** 初始化 **/
onMounted( () => {
   getList()
})
</script>
