<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="退库单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入退库单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原出库单号" prop="outboundOrderNo">
        <el-input
          v-model="queryParams.outboundOrderNo"
          placeholder="请输入原出库单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库ID" prop="warehouseId">
        <el-input
          v-model="queryParams.warehouseId"
          placeholder="请输入仓库ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退库原因" prop="returnReason">
        <el-input
          v-model="queryParams.returnReason"
          placeholder="请输入退库原因"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总数量" prop="totalQuantity">
        <el-input
          v-model="queryParams.totalQuantity"
          placeholder="请输入总数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入总金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="质检员" prop="qualityCheckerId">
        <el-input
          v-model="queryParams.qualityCheckerId"
          placeholder="请输入质检员"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="质检时间" prop="qualityCheckTime">
        <el-date-picker clearable
          v-model="queryParams.qualityCheckTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择质检时间">
        </el-date-picker>
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ware:wmsReturnOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ware:wmsReturnOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ware:wmsReturnOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ware:wmsReturnOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wmsReturnOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退库单号" align="center" prop="orderNo" width="150" />
      <el-table-column label="原出库单号" align="center" prop="outboundOrderNo" width="150" />
      <el-table-column label="仓库ID" align="center" prop="warehouseId" />
      <el-table-column label="退库原因" align="center" prop="returnReason" />
      <el-table-column label="退库类型" align="center" prop="returnType" />
      <el-table-column label="总数量" align="center" prop="totalQuantity" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="单据状态" align="center" prop="orderStatus" />
      <el-table-column label="质检员" align="center" prop="qualityCheckerId" />
      <el-table-column label="质检时间" align="center" prop="qualityCheckTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.qualityCheckTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质检状态" align="center" prop="qualityStatus" />
      <el-table-column label="审批状态" align="center" prop="approvalStatus" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ware:wmsReturnOrder:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ware:wmsReturnOrder: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-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="wmsReturnOrderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="退库单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入退库单号" />
        </el-form-item>
        <el-form-item label="原出库单号" prop="outboundOrderNo">
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input v-model="form.outboundOrderNo" placeholder="请选择原出库单号" readonly />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="openOutboundOrderSelect">选择出库单</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="仓库ID" prop="warehouseId">
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input v-model="form.warehouseId" placeholder="请选择仓库" readonly />
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="openWarehouseSelect">选择仓库</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="退库原因" prop="returnReason">
          <el-input type="textarea" v-model="form.returnReason" placeholder="请输入退库原因" />
        </el-form-item>
        <el-form-item label="总数量" prop="totalQuantity">
          <el-input v-model="form.totalQuantity" placeholder="请输入总数量" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="质检员" prop="qualityCheckerId">
          <el-input v-model="form.qualityCheckerId" placeholder="请输入质检员" />
        </el-form-item>
        <el-form-item label="质检时间" prop="qualityCheckTime">
          <el-date-picker clearable
            v-model="form.qualityCheckTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择质检时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 仓库选择对话框组件 -->
    <WarehouseSelectDialog
      ref="warehouseSelectDialogRef"
      v-model:visible="warehouseDialogVisible"
      title="选择仓库"
      @confirm="handleWarehouseConfirm"
    />
    
    <!-- 出库单选择对话框组件 -->
    <OutboundOrderSelectDialog
      ref="outboundOrderSelectDialogRef"
      v-model:visible="outboundOrderDialogVisible"
      title="选择出库单"
      @confirm="handleOutboundOrderConfirm"
    />
  </div>
</template>

<script setup name="WmsReturnOrder">
import { listWmsReturnOrder, getWmsReturnOrder, delWmsReturnOrder, addWmsReturnOrder, updateWmsReturnOrder } from "@/api/ware/wmsReturnOrder"
import WarehouseSelectDialog from "@/components/WarehouseSelectDialog.vue"
import OutboundOrderSelectDialog from "@/components/OutboundOrderSelectDialog.vue"

const { proxy } = getCurrentInstance()

const wmsReturnOrderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 仓库选择对话框状态
const warehouseDialogVisible = ref(false)
// 仓库选择对话框实例引用
const warehouseSelectDialogRef = ref(null)

// 出库单选择对话框状态
const outboundOrderDialogVisible = ref(false)
// 出库单选择对话框实例引用
const outboundOrderSelectDialogRef = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    outboundOrderNo: null,
    warehouseId: null,
    returnReason: null,
    returnType: null,
    totalQuantity: null,
    totalAmount: null,
    orderStatus: null,
    qualityCheckerId: null,
    qualityCheckTime: null,
    qualityStatus: null,
    approvalStatus: null,
  },
  rules: {
    orderNo: [
      { required: true, message: "退库单号不能为空", trigger: "blur" }
    ],
    outboundOrderNo: [
      { required: true, message: "原出库单号不能为空", trigger: "change" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "change" }
    ],
    returnReason: [
      { required: true, message: "退库原因不能为空", trigger: "blur" }
    ],
  }
})

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

/** 查询退库管理列表 */
function getList() {
  loading.value = true
  listWmsReturnOrder(queryParams.value).then(response => {
    wmsReturnOrderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNo: null,
    outboundOrderNo: null,
    warehouseId: null,
    returnReason: null,
    returnType: null,
    totalQuantity: null,
    totalAmount: null,
    orderStatus: null,
    qualityCheckerId: null,
    qualityCheckTime: null,
    qualityStatus: null,
    approvalStatus: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("wmsReturnOrderRef")
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加退库管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _orderId = row.orderId || ids.value
  getWmsReturnOrder(_orderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改退库管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["wmsReturnOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateWmsReturnOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWmsReturnOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal.confirm('是否确认删除退库管理编号为"' + _orderIds + '"的数据项？').then(function() {
    return delWmsReturnOrder(_orderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('ware/wmsReturnOrder/export', {
    ...queryParams.value
  }, `wmsReturnOrder_${new Date().getTime()}.xlsx`)
}

/** 打开仓库选择对话框 */
function openWarehouseSelect() {
  warehouseDialogVisible.value = true
  if (warehouseSelectDialogRef.value) {
    warehouseSelectDialogRef.value.handleQuery()
  }
}

/** 处理仓库选择结果 */
function handleWarehouseConfirm(selectedWarehouses) {
  if (selectedWarehouses.length > 0) {
    const warehouse = selectedWarehouses[0]
    form.value.warehouseId = warehouse.warehouseId
    // 可以根据需要添加更多仓库信息字段
  }
}

/** 打开出库单选择对话框 */
function openOutboundOrderSelect() {
  outboundOrderDialogVisible.value = true
  if (outboundOrderSelectDialogRef.value) {
    outboundOrderSelectDialogRef.value.handleQuery()
  }
}

/** 处理出库单选择结果 */
function handleOutboundOrderConfirm(selectedOrders) {
  if (selectedOrders.length > 0) {
    const order = selectedOrders[0]
    form.value.outboundOrderNo = order.orderNo
    // 可以根据需要添加更多出库单信息字段，比如自动填充仓库ID
    form.value.warehouseId = order.warehouseId
  }
}

getList()
</script>
