<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="采购单号" prop="orderSn">
              <el-input v-model="queryParams.orderSn" placeholder="请输入采购单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="店铺名称" prop="customOrderSn">
              <el-input v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!--            <el-form-item label="订单状态" prop="orderStatus">-->
            <!--              <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>-->
            <!--                <el-option v-for="dict in vendor_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="RefreshRight" @click="handleOrderAdd" v-hasPermi="['amz:purchaseOrder:add']">-->
          <!--              同步今天的采购单-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Refresh" @click="handleOrderUpdate()" v-hasPermi="['amz:purchaseOrder:edit']"-->
          <!--              >更新采购单状态-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['amz:purchaseOrder:remove']"-->
          <!--              >删除-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['amz:purchaseOrder:export']">导出 </el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="purchaseOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="expand">
          <template #default="props">
            <el-card shadow="never">
              <!--              <template #header>-->
              <!--                <div class="card-header">-->
              <!--                  <span>产品明细</span>-->
              <!--                </div>-->
              <!--              </template>-->

              <el-table v-loading="loading" :data="props.row.items" :border="true" size="small" :header-cell-style="{ fontSize: '10px' }">
                <!--              <el-table-column label="关联采购单号" align="center" prop="orderSn" />-->
                <!--              <el-table-column label="仓库ID" align="center" prop="wid" />-->
                <el-table-column label="仓库名称" align="center" prop="wareHouseName" />
                <!--              <el-table-column label="采购计划号" align="center" prop="planSn" />-->
                <!--              <el-table-column label="本地产品ID" align="center" prop="productId" />-->
                <el-table-column label="品名" align="center" prop="productName" />
                <el-table-column label="SKU" align="center" prop="sku" width="200px" />
                <!--                <el-table-column label="FNSKU" align="center" prop="fnsku" width="90px" />-->
                <!--                <el-table-column label="店铺ID" align="center" prop="sid" width="70px" />-->
                <!--              <el-table-column label="型号" align="center" prop="model" />-->
                <el-table-column label="含税单价" align="center" prop="price" />
                <!--              <el-table-column label="价税合计" align="center" prop="amount" />-->
                <!--              <el-table-column label="计划采购量" align="center" prop="quantityPlan" />-->
                <el-table-column label="实际采购量" align="center" prop="quantityReal" width="110px" />
                <!--              <el-table-column label="到货入库量" align="center" prop="quantityEntry" />-->
                <!--              <el-table-column label="待到货量" align="center" prop="quantityReceive" />-->
                <!--              <el-table-column label="退货数" align="center" prop="quantityReturn" />-->
                <!--              <el-table-column label="换货量" align="center" prop="quantityExchange" />-->
                <!--              <el-table-column label="质检量" align="center" prop="quantityQc" />-->
                <!--              <el-table-column label="待质检量" align="center" prop="quantityQcPrepare" />-->
                <!--              <el-table-column label="期待到货时间" align="center" prop="expectArriveTime" width="180">-->
                <!--                <template #default="scope">-->
                <!--                  <span>{{ parseTime(scope.row.expectArriveTime, '{y}-{m}-{d}') }}</span>-->
                <!--                </template>-->
                <!--              </el-table-column>-->
                <el-table-column label="备注" align="center" prop="remark" />
                <!--              <el-table-column label="箱数" align="center" prop="casesNum" />-->
                <!--              <el-table-column label="单箱数量" align="center" prop="quantityPerCase" />-->
                <!--              <el-table-column label="是否删除：0 否，1 是" align="center" prop="isDelete" />-->
                <!--              <el-table-column label="税率" align="center" prop="taxRate" />-->
                <!--              <el-table-column label="SPU" align="center" prop="spu" />-->
                <!--              <el-table-column label="款名" align="center" prop="spuName" />-->
              </el-table>
            </el-card>
          </template>
        </el-table-column>
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="采购单号" align="center" prop="orderSn" />
        <!--        <el-table-column label="自定义单号" align="center" prop="customOrderSn" />-->
        <!--        <el-table-column label="供应商ID" align="center" prop="supplierId" />-->
        <el-table-column label="订单类型" align="center" prop="sendStatus">
          <template #default="scope">
            <dict-tag :options="pur_order_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" align="center" prop="supplierName" />
        <el-table-column label="店铺名称" align="center" prop="storeName" />
        <!--        <el-table-column label="采购员ID" align="center" prop="optUid" />-->
        <!--        <el-table-column label="审核人姓名" align="center" prop="auditorRealname" />-->
        <!--        <el-table-column label="操作人姓名" align="center" prop="optRealname" />-->
        <!--        <el-table-column label="最后操作人姓名" align="center" prop="lastRealname" />-->
        <!--        <el-table-column label="创建时间" align="center" prop="createTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="应付货款" align="center" prop="payment" />-->
        <!--        <el-table-column label="审核人员ID" align="center" prop="auditorUid" />-->
        <!--        <el-table-column label="审核时间" align="center" prop="auditorTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.auditorTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="最后操作人员ID" align="center" prop="lastUid" />-->
        <!--        <el-table-column label="最后操作时间" align="center" prop="lastTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.lastTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="作废原因" align="center" prop="reason" />-->
        <!--        <el-table-column label="是否含税" align="center" prop="isTax" />-->
        <el-table-column v-hasRoles="['superadmin', 'gengdan']" label="采购单状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="purchase_order_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="状态说明" align="center" prop="statusText" />-->
        <!--        <el-table-column label="支付状态说明" align="center" prop="payStatusText" />-->
        <!--        <el-table-column label="到货状态" align="center" prop="statusShipped" />-->
        <!--        <el-table-column label="到货状态说明" align="center" prop="statusShippedText" />-->
        <!--        <el-table-column label="货物总价" align="center" prop="amountTotal" />-->
        <el-table-column label="总金额" align="center" prop="totalPrice" />

        <!--        <el-table-column label="币种符号" align="center" prop="icon" />-->
        <!--        <el-table-column label="付款状态" align="center" prop="payStatus" />-->

        <!--        <el-table-column label="其他费用" align="center" prop="otherFee" />-->
        <!--        <el-table-column label="其他费用币种" align="center" prop="otherCurrency" />-->
        <!--        <el-table-column label="费用分摊方式" align="center" prop="feePartType" />-->
        <!--        <el-table-column label="运费" align="center" prop="shippingPrice" />-->
        <!--        <el-table-column label="运费币种" align="center" prop="shippingCurrency" />-->
        <!--        <el-table-column label="采购币种" align="center" prop="purchaseCurrency" />-->
        <!--        <el-table-column label="采购汇率" align="center" prop="purchaseRate" />-->
        <!--        <el-table-column label="采购总量" align="center" prop="quantityTotal" />-->
        <!--        <el-table-column label="仓库ID" align="center" prop="wid" />-->
        <!--        <el-table-column label="仓库名称" align="center" prop="wareHouseName" />-->
        <!--        <el-table-column label="仓库名(备份)" align="center" prop="wareHouseBakName" />-->
        <!--        <el-table-column label="入库量" align="center" prop="quantityEntry" />-->
        <el-table-column label="采购数量" align="center" prop="quantityReal" />
        <!--        <el-table-column label="待到货量" align="center" prop="quantityReceive" />-->
        <!--        <el-table-column label="采购方ID" align="center" prop="purchaserId" />-->
        <!--        <el-table-column label="联系人" align="center" prop="contactPerson" />-->
        <!--        <el-table-column label="联系方式" align="center" prop="contactNumber" />-->
        <!--        <el-table-column label="结算方式" align="center" prop="settlementMethod" />-->
        <!--        <el-table-column label="结算描述" align="center" prop="settlementDescription" />-->
        <!--        <el-table-column label="支付方式" align="center" prop="paymentMethod" />-->
        <!--        <el-table-column label="预计交货天数" align="center" prop="estDlvDays" />-->
        <el-table-column label="订单状态" align="center" prop="orderStatus">
          <template #default="scope">
            <dict-tag :options="vendor_order_status" :value="scope.row.orderStatus" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="预计交货时间" align="center" prop="deliveryTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="订单交付变动天数" align="center" prop="dlvTimeVar" />-->
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!--            <el-tooltip content="修改" placement="top">-->
            <!--              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['amz:purchaseOrder:edit']"></el-button>-->
            <!--            </el-tooltip>-->

            <el-button
              size="small"
              link
              type="primary"
              @click="handleConfirm(scope.row)"
              v-hasRoles="['gongying']"
              v-hasPermi="['amz:purchaseOrder:remove']"
            >
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改采购单主对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="purchaseOrderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购单号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入采购单号" disabled />
        </el-form-item>
        <!--        <el-form-item label="自定义单号" prop="customOrderSn">-->
        <!--          <el-input v-model="form.customOrderSn" placeholder="请输入自定义单号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="供应商ID" prop="supplierId">-->
        <!--          <el-input v-model="form.supplierId" placeholder="请输入供应商ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="供应商名称" prop="supplierName">-->
        <!--          <el-input v-model="form.supplierName" placeholder="请输入供应商名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="采购员ID" prop="optUid">-->
        <!--          <el-input v-model="form.optUid" placeholder="请输入采购员ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="审核人姓名" prop="auditorRealname">-->
        <!--          <el-input v-model="form.auditorRealname" placeholder="请输入审核人姓名" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="操作人姓名" prop="optRealname">-->
        <!--          <el-input v-model="form.optRealname" placeholder="请输入操作人姓名" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="最后操作人姓名" prop="lastRealname">-->
        <!--          <el-input v-model="form.lastRealname" placeholder="请输入最后操作人姓名" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="下单时间" prop="orderTime">-->
        <!--          <el-date-picker clearable v-model="form.orderTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择下单时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="应付货款" prop="payment">-->
        <!--          <el-input v-model="form.payment" placeholder="请输入应付货款" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="审核人员ID" prop="auditorUid">-->
        <!--          <el-input v-model="form.auditorUid" placeholder="请输入审核人员ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="审核时间" prop="auditorTime">-->
        <!--          <el-date-picker clearable v-model="form.auditorTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择审核时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="最后操作人员ID" prop="lastUid">-->
        <!--          <el-input v-model="form.lastUid" placeholder="请输入最后操作人员ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="最后操作时间" prop="lastTime">-->
        <!--          <el-date-picker clearable v-model="form.lastTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择最后操作时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="作废原因" prop="reason">-->
        <!--          <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="是否含税" prop="isTax">-->
        <!--          <el-input v-model="form.isTax" placeholder="请输入是否含税：0 否，1 是" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="状态说明" prop="statusText">-->
        <!--          <el-input v-model="form.statusText" placeholder="请输入状态说明" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="支付状态说明" prop="payStatusText">-->
        <!--          <el-input v-model="form.payStatusText" placeholder="请输入支付状态说明" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="到货状态" prop="statusShipped">-->
        <!--          <el-input v-model="form.statusShipped" placeholder="请输入到货状态：1 未到货, 2 部分到货, 3 全部到货" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="到货状态说明" prop="statusShippedText">-->
        <!--          <el-input v-model="form.statusShippedText" placeholder="请输入到货状态说明" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="货物总价" prop="amountTotal">-->
        <!--          <el-input v-model="form.amountTotal" placeholder="请输入货物总价" />-->
        <!--        </el-form-item>-->
        <el-form-item label="总金额" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入总金额" suffix="元" disabled>
            <template #prefix>
              <span class="suffix-text">{{ form.icon }}</span>
              <!-- 可自定义样式 -->
            </template>
          </el-input>
        </el-form-item>
        <!--        <el-form-item label="币种符号" prop="icon">-->
        <!--          <el-input v-model="form.icon" placeholder="请输入币种符号" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备注" prop="remark">-->
        <!--          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="其他费用" prop="otherFee">-->
        <!--          <el-input v-model="form.otherFee" placeholder="请输入其他费用" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="其他费用币种" prop="otherCurrency">-->
        <!--          <el-input v-model="form.otherCurrency" placeholder="请输入其他费用币种" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="运费" prop="shippingPrice">-->
        <!--          <el-input v-model="form.shippingPrice" placeholder="请输入运费" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="运费币种" prop="shippingCurrency">-->
        <!--          <el-input v-model="form.shippingCurrency" placeholder="请输入运费币种" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="采购币种" prop="purchaseCurrency">-->
        <!--          <el-input v-model="form.purchaseCurrency" placeholder="请输入采购币种" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="采购汇率" prop="purchaseRate">-->
        <!--          <el-input v-model="form.purchaseRate" placeholder="请输入采购汇率" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="采购总量" prop="quantityTotal">-->
        <!--          <el-input v-model="form.quantityTotal" placeholder="请输入采购总量" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="仓库ID" prop="wid">-->
        <!--          <el-input v-model="form.wid" placeholder="请输入仓库ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="仓库名称" prop="wareHouseName">-->
        <!--          <el-input v-model="form.wareHouseName" placeholder="请输入仓库名称" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="仓库名(备份)" prop="wareHouseBakName">-->
        <!--          <el-input v-model="form.wareHouseBakName" placeholder="请输入仓库名(备份)" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="入库量" prop="quantityEntry">-->
        <!--          <el-input v-model="form.quantityEntry" placeholder="请输入入库量" />-->
        <!--        </el-form-item>-->

        <el-form-item label="采购数量" prop="quantityReal">
          <el-tag type="warning">实际的订单数量以跟单扫描的纸制订单为准！</el-tag>
          <el-input v-model="form.quantityReal" placeholder="请输入实际采购数量" disabled />
        </el-form-item>
        <!--        <el-form-item label="待到货量" prop="quantityReceive">-->
        <!--          <el-input v-model="form.quantityReceive" placeholder="请输入待到货量" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="采购方ID" prop="purchaserId">-->
        <!--          <el-input v-model="form.purchaserId" placeholder="请输入采购方ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="联系人" prop="contactPerson">-->
        <!--          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="联系方式" prop="contactNumber">-->
        <!--          <el-input v-model="form.contactNumber" placeholder="请输入联系方式" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="结算方式" prop="settlementMethod">-->
        <!--          <el-input v-model="form.settlementMethod" placeholder="请输入结算方式：7 现结, 8 月结" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="结算描述" prop="settlementDescription">-->
        <!--          <el-input v-model="form.settlementDescription" type="textarea" placeholder="请输入内容" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="支付方式" prop="paymentMethod">-->
        <!--          <el-input v-model="form.paymentMethod" placeholder="请输入支付方式" />-->
        <!--        </el-form-item>-->

        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态" disabled>
            <el-option v-for="dict in vendor_order_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交货时间" prop="deliveryTime">
          <el-date-picker
            clearable
            v-model="form.deliveryTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择交货时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交货天数" prop="estDlvDays">
          <!--          <el-input v-model="form.estDlvDays" placeholder="请输入交货天数" />-->
          <el-input-number v-model="form.estDlvDays" :min="0" :max="10000" @change="delevAction()">
            <template #suffix>
              <span>天</span>
            </template>
          </el-input-number>
        </el-form-item>
        <!--        <el-form-item label="订单交付变动天数" prop="dlvTimeVar">-->
        <!--          <el-input v-model="form.dlvTimeVar" placeholder="请输入订单交付变动天数" />-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确认订单</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PurchaseOrder" lang="ts">
import {
  listPurchaseOrder,
  getPurchaseOrder,
  delPurchaseOrder,
  addPurchaseOrder,
  updatePurchaseOrder,
  confirmPurchaseOrder,
  takeTodayPurchaseOrder,
  updateTodayPurchaseOrder
} from '@/api/amz/purchaseOrder';
import { PurchaseOrderVO, PurchaseOrderQuery, PurchaseOrderForm } from '@/api/amz/purchaseOrder/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { vendor_order_status } = toRefs<any>(proxy?.useDict('vendor_order_status'));

const { purchase_order_status } = toRefs<any>(proxy?.useDict('purchase_order_status'));

const { pur_order_type } = toRefs<any>(proxy?.useDict('pur_order_type'));

const purchaseOrderList = ref<PurchaseOrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const purchaseOrderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PurchaseOrderForm = {
  orderSn: undefined,
  customOrderSn: undefined,
  supplierId: undefined,
  supplierName: undefined,
  optUid: undefined,
  auditorRealname: undefined,
  optRealname: undefined,
  lastRealname: undefined,
  orderTime: undefined,
  payment: undefined,
  auditorUid: undefined,
  auditorTime: undefined,
  lastUid: undefined,
  lastTime: undefined,
  reason: undefined,
  isTax: undefined,
  status: undefined,
  statusText: undefined,
  payStatusText: undefined,
  statusShipped: undefined,
  statusShippedText: undefined,
  amountTotal: undefined,
  totalPrice: undefined,
  icon: undefined,
  payStatus: undefined,
  remark: undefined,
  otherFee: undefined,
  otherCurrency: undefined,
  feePartType: undefined,
  shippingPrice: undefined,
  shippingCurrency: undefined,
  purchaseCurrency: undefined,
  purchaseRate: undefined,
  quantityTotal: undefined,
  wid: undefined,
  wareHouseName: undefined,
  wareHouseBakName: undefined,
  quantityEntry: undefined,
  quantityReal: undefined,
  quantityReceive: undefined,
  purchaserId: undefined,
  contactPerson: undefined,
  contactNumber: undefined,
  settlementMethod: undefined,
  settlementDescription: undefined,
  paymentMethod: undefined,
  estDlvDays: undefined,
  orderStatus: undefined,
  deliveryTime: undefined,
  dlvTimeVar: undefined
};
const data = reactive<PageData<PurchaseOrderForm, PurchaseOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderSn: undefined,
    customOrderSn: undefined,
    supplierId: undefined,
    supplierName: undefined,
    optUid: undefined,
    auditorRealname: undefined,
    optRealname: undefined,
    lastRealname: undefined,
    orderTime: undefined,
    payment: undefined,
    auditorUid: undefined,
    auditorTime: undefined,
    lastUid: undefined,
    lastTime: undefined,
    reason: undefined,
    isTax: undefined,
    status: undefined,
    statusText: undefined,
    payStatusText: undefined,
    statusShipped: undefined,
    statusShippedText: undefined,
    amountTotal: undefined,
    totalPrice: undefined,
    icon: undefined,
    payStatus: undefined,
    otherFee: undefined,
    otherCurrency: undefined,
    feePartType: undefined,
    shippingPrice: undefined,
    shippingCurrency: undefined,
    purchaseCurrency: undefined,
    purchaseRate: undefined,
    quantityTotal: undefined,
    wid: undefined,
    wareHouseName: undefined,
    wareHouseBakName: undefined,
    quantityEntry: undefined,
    quantityReal: undefined,
    quantityReceive: undefined,
    purchaserId: undefined,
    contactPerson: undefined,
    contactNumber: undefined,
    settlementMethod: undefined,
    settlementDescription: undefined,
    paymentMethod: undefined,
    estDlvDays: undefined,
    orderStatus: ['ord_unconfirmed'],
    deliveryTime: undefined,
    dlvTimeVar: undefined,
    storeName: undefined,
    params: {}
  },
  rules: {
    // orderSn: [{ required: true, message: '采购单号不能为空', trigger: 'blur' }],
    // customOrderSn: [{ required: true, message: '自定义单号不能为空', trigger: 'blur' }],
    // supplierId: [{ required: true, message: '供应商ID不能为空', trigger: 'blur' }],
    // supplierName: [{ required: true, message: '供应商名称不能为空', trigger: 'blur' }],
    // optUid: [{ required: true, message: '采购员ID不能为空', trigger: 'blur' }],
    // auditorRealname: [{ required: true, message: '审核人姓名不能为空', trigger: 'blur' }],
    // optRealname: [{ required: true, message: '操作人姓名不能为空', trigger: 'blur' }],
    // lastRealname: [{ required: true, message: '最后操作人姓名不能为空', trigger: 'blur' }],
    // orderTime: [{ required: true, message: '下单时间不能为空', trigger: 'blur' }],
    // payment: [{ required: true, message: '应付货款不能为空', trigger: 'blur' }],
    // auditorUid: [{ required: true, message: '审核人员ID不能为空', trigger: 'blur' }],
    // auditorTime: [{ required: true, message: '审核时间不能为空', trigger: 'blur' }],
    // lastUid: [{ required: true, message: '最后操作人员ID不能为空', trigger: 'blur' }],
    // lastTime: [{ required: true, message: '最后操作时间不能为空', trigger: 'blur' }],
    // reason: [{ required: true, message: '作废原因不能为空', trigger: 'blur' }],
    // isTax: [{ required: true, message: '是否含税：0 否，1 是不能为空', trigger: 'blur' }],
    // status: [
    //   {
    //     required: true,
    //     message: '采购单状态：-1 作废, 3 待提交, 1 待下单, 2 待签收, 9 完成, 121 待审核, 122 驳回, 124 作废不能为空',
    //     trigger: 'change'
    //   }
    // ],
    // statusText: [{ required: true, message: '状态说明不能为空', trigger: 'blur' }],
    // payStatusText: [{ required: true, message: '支付状态说明不能为空', trigger: 'blur' }],
    // statusShipped: [{ required: true, message: '到货状态：1 未到货, 2 部分到货, 3 全部到货不能为空', trigger: 'blur' }],
    // statusShippedText: [{ required: true, message: '到货状态说明不能为空', trigger: 'blur' }],
    // amountTotal: [{ required: true, message: '货物总价不能为空', trigger: 'blur' }],
    // totalPrice: [{ required: true, message: '总金额不能为空', trigger: 'blur' }],
    // icon: [{ required: true, message: '币种符号不能为空', trigger: 'blur' }],
    // payStatus: [
    //   {
    //     required: true,
    //     message: '付款状态：0 未申请, 1 已申请, 2 部分付款, 3 已付款不能为空',
    //     trigger: 'change'
    //   }
    // ],
    // remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    // otherFee: [{ required: true, message: '其他费用不能为空', trigger: 'blur' }],
    // otherCurrency: [{ required: true, message: '其他费用币种不能为空', trigger: 'blur' }],
    // feePartType: [{ required: true, message: '费用分摊方式：0 不分摊, 1 按金额, 2 按数量不能为空', trigger: 'change' }],
    // shippingPrice: [{ required: true, message: '运费不能为空', trigger: 'blur' }],
    // shippingCurrency: [{ required: true, message: '运费币种不能为空', trigger: 'blur' }],
    // purchaseCurrency: [{ required: true, message: '采购币种不能为空', trigger: 'blur' }],
    // purchaseRate: [{ required: true, message: '采购汇率不能为空', trigger: 'blur' }],
    // quantityTotal: [{ required: true, message: '采购总量不能为空', trigger: 'blur' }],
    // wid: [{ required: true, message: '仓库ID不能为空', trigger: 'blur' }],
    // wareHouseName: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
    // wareHouseBakName: [{ required: true, message: '仓库名(备份)不能为空', trigger: 'blur' }],
    // quantityEntry: [{ required: true, message: '入库量不能为空', trigger: 'blur' }],
    // quantityReal: [{ required: true, message: '实际采购量不能为空', trigger: 'blur' }],
    // quantityReceive: [{ required: true, message: '待到货量不能为空', trigger: 'blur' }],
    // purchaserId: [{ required: true, message: '采购方ID不能为空', trigger: 'blur' }],
    // contactPerson: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
    // contactNumber: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
    // settlementMethod: [{ required: true, message: '结算方式：7 现结, 8 月结不能为空', trigger: 'blur' }],
    // settlementDescription: [{ required: true, message: '结算描述不能为空', trigger: 'blur' }],
    // paymentMethod: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
    // dlvTimeVar: [{ required: true, message: '订单交付变动天数不能为空', trigger: 'blur' }]
    // deliveryTime: [{ required: true, message: '交货时间不能为空', trigger: 'blur' }],
    estDlvDays: [{ required: true, message: '交货天数不能为空', trigger: 'blur' }],
    orderStatus: [{ required: true, message: '订单状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询采购单主列表 */
const getList = async () => {
  loading.value = true;
  const copyParams = JSON.parse(JSON.stringify(queryParams.value)); // 仅适用简单数据类型[1,2](@ref)
  if (Array.isArray(copyParams.orderStatus)) {
    copyParams.orderStatus = copyParams.orderStatus.join(','); // 数组转字符串[6,7](@ref)
  }
  const res = await listPurchaseOrder(copyParams);
  purchaseOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  purchaseOrderFormRef.value?.resetFields();
};

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

const delevAction = () => {
  form.value.deliveryTime = getDateAfterTwoDays(form.value.estDlvDays);
  console.log('form.value', form.value.deliveryTime);
};

const getDateAfterTwoDays = (dayNum: number): string => {
  const date = new Date(); // 获取当前时间
  date.setDate(date.getDate() + dayNum); // 增加 2 天

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需加 1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PurchaseOrderVO[]) => {
  ids.value = selection.map((item) => item.orderSn);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleOrderAdd = async () => {
  //获取领星采购单
  const res = await takeTodayPurchaseOrder();
  console.log(res);
};

const handleOrderUpdate = async () => {
  //更新领星采购单
  //获取领星采购单
  const res = await updateTodayPurchaseOrder();
  console.log(res);
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加采购单主';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PurchaseOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getPurchaseOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改采购单主';
};

const handleConfirm = async (row?: PurchaseOrderVO) => {
  // reset();
  // const _orderSn = row?.orderSn || ids.value[0];
  // const res = await getPurchaseOrder(_orderSn);
  // Object.assign(form.value, res.data);
  // dialog.visible = true;
  // dialog.title = '修改采购单主';
  console.log('row', row);
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getPurchaseOrder(_id);
  Object.assign(form.value, res.data);
  form.value.orderStatus = 'ord_confirmed';
  dialog.visible = true;
  dialog.title = '确认订单';
};

/** 提交按钮 */
const submitForm = () => {
  form.value.deliveryTime = getDateAfterTwoDays(form.value.estDlvDays);
  purchaseOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orderSn) {
        await confirmPurchaseOrder(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPurchaseOrder(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PurchaseOrderVO) => {
  const _orderSns = row?.orderSn || ids.value;
  await proxy?.$modal.confirm('是否确认删除采购单主编号为"' + _orderSns + '"的数据项？').finally(() => (loading.value = false));
  await delPurchaseOrder(_orderSns);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'amz/purchaseOrder/export',
    {
      ...queryParams.value
    },
    `purchaseOrder_${new Date().getTime()}.xlsx`
  );
};

const route = useRoute();

watch(
  () => route.query.orderSn,
  (newOrderSn) => {
    if (typeof newOrderSn === 'string' && newOrderSn) {
      queryParams.value.orderSn = newOrderSn;
      getList();
    }
  },
  { immediate: true } // 立即执行一次
);

// onMounted(() => {
//   getList();
// });
onActivated(() => {
  getList();
});
</script>
<style scoped></style>
