<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="158px">
        <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="subProjectName">
          <el-input
            v-model="queryParams.subProjectName" placeholder="子项目名称" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="零件名称" prop="partName">
          <el-input
v-model="queryParams.partName" placeholder="零件名称" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="项目编码" prop="projectNum">
          <el-input
            v-model="queryParams.projectNum" placeholder="项目编码" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="采购状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="下拉选择" clearable class="!w-240px">
            <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.PART_PURCHASE_STATUS)" :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-button type="primary" plain @click="openForm('create')" v-hasPermi="['heli:purchase-order:create']">
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <!-- <el-button type="success" plain @click="handleExportWithTax()" v-hasPermi="['heli:purchase-order:create']">
            <Icon icon="ep:upload" class="mr-5px" /> 乘税率导出
          </el-button>
          <el-button type="success" plain @click="handleExport()" v-hasPermi="['heli:purchase-order:create']">
            <Icon icon="ep:upload" 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 type="selection" fixed width="60" />
        <el-table-column fixed label="序号" type="index" align="center" width="60" />
        <el-table-column label="采购单号" align="center" prop="projectName" fixed min-width="190">
          <template #default="scope">
            <el-button link type="primary" @click="openForm('detail', scope.row.id)">
              {{ scope.row.projectName }}
            </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="partName" 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="contractNo" min-width="180" />
        <el-table-column label="结算币种" align="center" prop="currencyType" min-width="180">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_CURRENCY" :value="scope.row.currencyType" />
          </template>
        </el-table-column>
        <el-table-column label="暂估价金额(元)" align="center" prop="estimatedPrice" min-width="180" />
        <el-table-column label="实际价金额(元)" align="center" prop="actualPrice" min-width="180" />
        <el-table-column label="税率" align="center" prop="taxRatio" />
        <el-table-column label="备注" align="center" prop="description" />
        <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" 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-column label="操作" align="right" fixed="right" min-width="200">
          <template #header>
            <span style="margin-right: 30%">操作</span>
          </template>
          <template #default="scope">
            <el-button
link type="primary" @click="openForm('edit', scope.row.id)"
              v-if="scope.row.status == 1 || scope.row.status == 4">
              编辑
            </el-button>
            <el-button
link type="primary" @click="editReceivingStatus(scope.row.id)"
              v-if="scope.row.status == 3 && scope.row.receivingStatus != 3">
              完成收货
            </el-button>
            <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 { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import * as PurchaseOrderApi from '@/api/heli/purchaseorder'
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 queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  ids: undefined,
  projectName: undefined,
  subProjectName: undefined,
  partName: undefined,
  projectNum: undefined,
  supplierId: undefined,
  contractNo: undefined,
  purchaseType: undefined,
  projectMaterialPlanId: undefined,
  goodsType: undefined,
  currencyType: undefined,
  taxRatio: undefined,
  estimatedPrice: undefined,
  actualPrice: undefined,
  status: 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)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
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 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/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
  }
}

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