<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:return_orders:add']"
        >新增</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['inventory:return_orders:edit']"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:return_orders:remove']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:return_orders:export']"
        >导出</el-button>
      </template>
    </PageTitle>

    <!-- 页面容器 -->
    <div class="page-container">
      <!-- 查询表单 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="退库单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入退库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退库日期" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="退库类型" prop="returnType">
        <el-select v-model="queryParams.returnType" placeholder="请选择退库类型" clearable>
          <el-option
            v-for="item in returnTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="货主" prop="ownerId">
        <el-input
          v-model="queryOwnerName"
          placeholder="请选择货主"
          readonly
          @focus="openOwnerSelector('query')"
          :suffix-icon="''"
        >
          <template v-if="queryOwnerName" #suffix>
            <i
              class="el-icon-circle-close el-input__icon"
              style="cursor: pointer;"
              @click.stop="clearQueryOwner"
            ></i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="退库原因" prop="returnReason">
        <el-input
          v-model="queryParams.returnReason"
          placeholder="请输入退库原因"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退库单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择退库单状态" clearable class="w20">
          <el-option
            v-for="item in orderStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      </el-form>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table v-loading="loading" :data="returnOrderList" height="100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退库单号" align="center" prop="orderId" width="150" />
      <el-table-column label="退库日期" align="center" prop="returnDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退库类型" align="center" prop="returnType" width="120">
        <template slot-scope="scope">
          <el-tag type="info" size="small">
            {{ getReturnTypeName(scope.row.returnType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="货主" align="center" prop="ownerName" width="120" />
      <!-- <el-table-column label="原出库单号" align="center" prop="originalOrderId" width="150" /> -->
      <el-table-column label="退库原因" align="center" prop="returnReason" show-overflow-tooltip />
      <el-table-column label="退库单状态" align="center" prop="orderStatus" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.orderStatus)"
            size="small"
          >
            {{ getStatusName(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划量" align="center" prop="totalPlannedQuantity" width="100" />
      <el-table-column label="实际量" align="center" prop="totalActualQuantity" width="100" />
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:return_orders:edit']"
            v-show="!(scope.row.orderStatus === 2)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:return_orders:remove']"
            v-show="!(scope.row.orderStatus === 2)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['inventory:return_orders:confirm']"
            v-show="!(scope.row.orderStatus === 2)"
          >确认退库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-more"
            @click="handleDetail(scope.row)"
            v-show="(scope.row.orderStatus === 2)"
          >详情</el-button>
        </template>
      </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改退库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body class="scrollable-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-divider content-position="center">退库单基础信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="退库单号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入退库单号" :readonly="isDetailMode || form.orderStatus === 2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退库日期" prop="returnDate">
              <el-date-picker
                v-model="form.returnDate"
                type="datetime"
                value-format="yyyy-MM-dd"
                placeholder="请选择退库日期"
                style="width: 100%"
                :disabled="isDetailMode || form.orderStatus === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="退库类型" prop="returnType">
              <el-select v-model="form.returnType" placeholder="请选择退库类型" clearable style="width: 100%" :disabled="isDetailMode || form.orderStatus === 2">
                <el-option
                  v-for="item in returnTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="货主" prop="ownerId">
              <el-input
                v-model="form.ownerName"
                placeholder="请选择货主"
                readonly
                @focus="!isDetailMode && form.orderStatus !== 2 && openOwnerSelector('form')"
                @click="!isDetailMode && form.orderStatus !== 2 && openOwnerSelector('form')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="原出库单号" prop="originalOrderId">
              <el-input v-model="form.originalOrderId" placeholder="请输入原出库单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="form.orderStatus" placeholder="请选择订单状态" clearable style="width: 100%">
                <el-option
                  v-for="item in orderStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-form-item label="退库原因" prop="returnReason">
          <el-input v-model="form.returnReason" type="textarea" :rows="3" placeholder="请输入退库原因" :readonly="isDetailMode || form.orderStatus === 2" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" :readonly="isDetailMode || form.orderStatus === 2" />
        </el-form-item>

        <el-divider content-position="center">退库物料明细</el-divider>
        <!-- 明细表操作按钮 -->
        <el-row :gutter="10" class="mb8" v-if="!isDetailMode && form.orderStatus !== 2">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddItem"
            >添加明细</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multipleItems"
              @click="handleDeleteItems"
            >删除明细</el-button>
          </el-col>
        </el-row>

        <!-- 明细表格 -->
        <el-table
          :data="form.returnOrderItemsList"
          border
          @selection-change="handleItemsSelectionChange"
          style="margin-top: 10px"
        >
          <el-table-column type="selection" width="55" align="center" v-if="!isDetailMode && form.orderStatus !== 2" />
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="货物" prop="materialName" width="150" align="center" />
          <el-table-column label="批次号" prop="batchCode" min-width="160" align="center">
            <template slot-scope="scope">
              <el-input
                v-if="!isDetailMode && form.orderStatus !== 2"
                v-model="scope.row.batchCode"
                size="small"
                placeholder="请输入批次"
              />
              <span v-else>{{ scope.row.batchCode || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库" prop="warehouseName" width="160" align="center">
            <template slot-scope="scope">
              <span v-if="isDetailMode || form.orderStatus === 2" class="text-content">
                {{ scope.row.warehouseName || scope.row.warehouseId || '-' }}
              </span>
              <el-input
                v-else
                v-model="scope.row.warehouseName"
                placeholder="请选择仓库"
                readonly
                size="small"
                @focus="openWarehouseSelector(scope.row)"
                @click="openWarehouseSelector(scope.row)"
                :suffix-icon="''"
              >
                <template v-if="scope.row.warehouseName" #suffix>
                  <i
                    class="el-icon-circle-close el-input__icon"
                    style="cursor: pointer;"
                    @click.stop="clearWarehouse(scope.row)"
                  ></i>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="库位" prop="locationName" width="180" align="center">
            <template slot-scope="scope">
              <span v-if="isDetailMode || form.orderStatus === 2" class="text-content">
                {{ scope.row.locationName || scope.row.locationId || '-' }}
              </span>
              <el-input
                v-else
                v-model="scope.row.locationName"
                placeholder="请选择库位"
                readonly
                size="small"
                @focus="openLocationSelector(scope.row)"
                @click="openLocationSelector(scope.row)"
                :suffix-icon="''"
                :disabled="!scope.row.warehouseId"
              >
                <template v-if="scope.row.locationName" #suffix>
                  <i
                    class="el-icon-circle-close el-input__icon"
                    style="cursor: pointer;"
                    @click.stop="clearLocation(scope.row)"
                  ></i>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="计划数量" prop="plannedQuantity" width="140" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-if="!isDetailMode && form.orderStatus !== 2"
                v-model="scope.row.plannedQuantity"
                :min="0"
                size="small"
                style="width: 100%"
              />
              <span v-else>{{ scope.row.plannedQuantity || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际数量" prop="actualQuantity" width="140" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-if="!isDetailMode && form.orderStatus !== 2"
                v-model="scope.row.actualQuantity"
                :min="0"
                size="small"
                style="width: 100%"
                @change="handleQuantityChange(scope.row)"
              />
              <span v-else>{{ scope.row.actualQuantity || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="140" align="center">
            <template slot-scope="scope">
              <el-input-number
                v-if="!isDetailMode && form.orderStatus !== 2"
                v-model="scope.row.unitPrice"
                :min="0"
                :precision="2"
                size="small"
                style="width: 100%"
                @change="handleAmountChange(scope.row)"
              />
              <span v-else>{{ formatAmount(scope.row.unitPrice || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="totalAmount" width="120" align="center">
            <template slot-scope="scope">
              {{ formatAmount(scope.row.totalAmount || (scope.row.actualQuantity || 0) * (scope.row.unitPrice || 0)) }}
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" min-width="200">
            <template slot-scope="scope">
              <el-input
                v-if="!isDetailMode && form.orderStatus !== 2"
                v-model="scope.row.remark"
                size="small"
                placeholder="请输入备注"
              />
              <span v-else>{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isDetailMode" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物料选择弹窗 -->
    <el-dialog
      title="选择物料"
      :visible.sync="materialSelectOpen"
      width="1200px"
      append-to-body
    >
      <MaterialSelector
        v-model="selectedMaterialIds"
        :multiple="true"
        @change="handleMaterialChange"
        ref="materialSelector"
      />
      <div slot="footer">
        <el-button @click="materialSelectOpen = false">取消</el-button>
        <el-button type="primary" @click="confirmMaterialSelect">确定</el-button>
      </div>
    </el-dialog>

    <OwnerSelector
      v-model="ownerSelectorVisible"
      @selected="handleOwnerSelected"
    />
    <!-- 仓库选择组件 -->
    <WarehouseSelector
      v-model="warehouseSelectorVisible"
      @selected="handleWarehouseSelected"
    />
    <!-- 库位选择组件 -->
    <LocationSelector
      v-model="locationSelectorVisible"
      :warehousesId="currentEditRowWarehousesId"
      @selected="handleLocationSelected"
    />
  </div>
</template>

<script>
import { listReturnOrders, getReturnOrder, delReturnOrder, addReturnOrder, updateReturnOrder, confirmReturnOrder } from "@/api/inventory/return_orders"
import { listData } from "@/api/system/dict/data"
import RightToolbar from "@/components/RightToolbar"
import PageTitle from "@/components/PageTitle"
import MaterialSelector from "@/views/inventory/materials/materialsSeletor.vue"
import OwnerSelector from "@/views/compononents/OwnerSelector.vue"
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"

export default {
  name: "ReturnOp",
  components: {
    RightToolbar,
    PageTitle,
    MaterialSelector,
    OwnerSelector,
    WarehouseSelector,
    LocationSelector
  },
  data() {
    return {
      // 退库类型选项（字典：1-TRDC退料 2-质量退料 3-多出退料 4-其他，默认1）
      returnTypeOptions: [
        // { value: '1', label: 'TRDC退料' },
        // { value: '2', label: '质量退料' },
        // { value: '3', label: '多出退料' },
        // { value: '4', label: '其他' }
      ],
      // 订单状态选项（字典：1-草稿 2-已完成）
      orderStatusOptions: [
        { value: 1, label: '草稿' },
        { value: 2, label: '已完成' }
      ],
      // 物料选择相关
      materialSelectOpen: false,
      selectedMaterialIds: [],
      selectedMaterials: [],
      ownerSelectorVisible: false,
      ownerSelectTarget: 'form',
      queryOwnerName: null,
      // 仓库和库位选择相关
      warehouseSelectorVisible: false,
      locationSelectorVisible: false,
      currentEditRow: null,
      currentEditRowWarehousesId: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退库单表格数据
      returnOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为详情模式
      isDetailMode: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        dateRange: null,//时间段
        returnType: null,
        ownerId: null,
        ownerName: null,
        ownerCode: null,
        originalOrderId: null,
        returnReason: null,
        orderStatus: null
      },
      // 表单参数
      form: {
        id: null,
        orderId: null,
        returnDate: null,
        returnType: '1',
        ownerId: null,
        ownerName: null,
        originalOrderId: null,
        returnReason: null,
        orderStatus: 1,
        totalPlannedQuantity: 0,
        totalActualQuantity: 0,
        remark: null,
        returnOrderItemsList: []
      },
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "退库单号不能为空", trigger: "blur" }
        ],
        returnDate: [
          { required: true, message: "退库日期不能为空", trigger: "change" }
        ],
        returnType: [
          { required: true, message: "退库类型不能为空", trigger: "change" }
        ]
      },
      // 明细选中项
      selectedItems: [],
      multipleItems: true,
      returnRows: [] //入库单选择
    }
  },
  created() {
    this.getDictData()
    this.getList()
  },
  methods: {
    /** 查询退库单列表 */
    getList() {
      this.loading = true
      listReturnOrders(this.queryParams).then(response => {
        this.returnOrderList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 获取状态样式类型 */
    getStatusType(status) {
      const item = this.orderStatusOptions.find(item => item.value === status)
      return item ? (status === 1 ? 'info' : 'success') : 'info'
    },
    /** 获取状态名称 */
    getStatusName(status) {
      const item = this.orderStatusOptions.find(item => item.value === status)
      return item ? item.label : '未知'
    },
    /** 获取退库类型名称 */
    getReturnTypeName(type) {
      if (!type) return '未知类型'
      const item = this.returnTypeOptions.find(item => item.value === type)
      return item ? item.label : '未知类型'
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryOwnerName = null
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.returnRows = selection
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isDetailMode = false
      this.open = true
      this.title = "新建退库单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(!row) {
        if(this.returnRows.length === 1) {
          row = this.returnRows[0]
        }else{
          this.$message.warning("请选择一个退库单进行修改！")
        }
      }
      this.reset()
      const id = row.id || this.ids[0]
      getReturnOrder(id).then(response => {
        this.form = response.data
        // 如果后端返回的明细数据为空，初始化为空数组
        if (!this.form.returnOrderItemsList) {
          this.form.returnOrderItemsList = []
        }
        this.form.returnOrderItemsList = this.form.returnOrderItemsList.map(item => ({
          ...item,
          ownerName: item.ownerName || item.ownerId,
          warehouseName: item.warehouseName || item.warehouseId,
          locationName: item.locationName || item.locationCode || item.locationId
        }))
        this.form.ownerName = response.data.ownerName || response.data.ownerCode || response.data.ownerId
        this.isDetailMode = false
        this.open = true
        this.title = "修改退库单"
      })
    },

    /** 详情按钮操作 */
    handleDetail(row) {
      if(!row) {
        this.$message.warning("请选择一个退库单！")
        return
      }
      this.reset()
      this.isDetailMode = true
      const id = row.id
      getReturnOrder(id).then(response => {
        this.form = response.data
        // 如果后端返回的明细数据为空，初始化为空数组
        if (!this.form.returnOrderItemsList) {
          this.form.returnOrderItemsList = []
        }
        this.form.returnOrderItemsList = this.form.returnOrderItemsList.map(item => ({
          ...item,
          ownerName: item.ownerName || item.ownerId,
          warehouseName: item.warehouseName || item.warehouseId,
          locationName: item.locationName || item.locationCode || item.locationId
        }))
        this.form.ownerName = response.data.ownerName || response.data.ownerCode || response.data.ownerId
        this.open = true
        this.title = "退库单详情"
      })
    },
    /** 确认按钮操作 */
    handleConfirm(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认退库的数据项？', '提示', {
        type: 'warning'
      }).then(() => {
        return confirmReturnOrder(ids)
      }).then(() => {
        this.getList()
        this.$message.success("确认退库成功")
      }).catch(() => {})
    },
    openOwnerSelector(target = 'form') {
      this.ownerSelectTarget = target
      this.ownerSelectorVisible = true
    },
    handleOwnerSelected(owner) {
      if (!owner) return
      if (this.ownerSelectTarget === 'query') {
        this.queryParams.ownerId = owner.ownerId || owner.ownerCode
        this.queryOwnerName = owner.ownerName || owner.ownerCode
        this.handleQuery()
      } else {
        this.form.ownerId = owner.ownerId || owner.ownerCode
        this.form.ownerCode = owner.ownerCode
        this.form.ownerName = owner.ownerName
      }
    },
    /** 打开仓库选择器 */
    openWarehouseSelector(row) {
      if (this.isDetailMode || this.form.orderStatus === 2) return
      this.currentEditRow = row
      this.warehouseSelectorVisible = true
    },
    /** 仓库选择回调 */
    handleWarehouseSelected(warehouse) {
      if (!warehouse || !this.currentEditRow) return
      this.currentEditRow.warehouseId = warehouse.warehouseId || warehouse.id
      this.currentEditRow.warehouseId = warehouse.warehouseId
      this.currentEditRow.warehouseName = warehouse.warehousesName || warehouse.warehouseId
      // 仓库选择后，清空库位信息
      this.currentEditRow.locationId = null
      this.currentEditRow.locationName = null
      this.currentEditRow.locationCode = null
      this.currentEditRow = null
    },
    /** 打开库位选择器 */
    openLocationSelector(row) {
      if (this.isDetailMode || this.form.orderStatus === 2) return
      if (!row.warehouseId) {
        this.$message.warning("请先选择仓库")
        return
      }
      this.currentEditRow = row
      this.currentEditRowWarehousesId = row.warehouseId
      this.locationSelectorVisible = true
    },
    /** 库位选择回调 */
    handleLocationSelected(location) {
      if (!location || !this.currentEditRow) return
      this.currentEditRow.locationId = location.locationId || location.id
      this.currentEditRow.locationName = location.locationName || location.locationCode
      this.currentEditRow.locationCode = location.locationCode
      this.currentEditRow = null
      this.currentEditRowWarehousesId = null
    },
    /** 清空仓库选择 */
    clearWarehouse(row) {
      row.warehouseId = null
      row.warehouseId = null
      row.warehouseName = null
      // 清空仓库时，同时清空库位
      row.locationId = null
      row.locationName = null
      row.locationCode = null
    },
    /** 清空库位选择 */
    clearLocation(row) {
      row.locationId = null
      row.locationName = null
      row.locationCode = null
    },
    clearQueryOwner() {
      this.queryOwnerName = null
      this.queryParams.ownerId = null
      this.handleQuery()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除退库单编号为"' + ids + '"的数据项？', '提示', {
        type: 'warning'
      }).then(() => {
        return delReturnOrder(ids)
      }).then(() => {
        this.getList()
        this.$message.success("删除成功")
      }).catch(() => {})
    },
    /** 添加明细按钮 */
    handleAddItem() {
      this.materialSelectOpen = true
      this.selectedMaterialIds = []
      this.selectedMaterials = []
      this.$nextTick(() => {
        if (this.$refs.materialSelector) {
          this.$refs.materialSelector.clearSelection()
        }
      })
    },
    /** 物料选择变化回调 */
    handleMaterialChange(selectedRows) {
      this.selectedMaterials = selectedRows
    },
    /** 确认选择物料并添加到明细 */
    confirmMaterialSelect() {
      if (this.selectedMaterials.length === 0) {
        this.$message.warning("请选择物料")
        return
      }

      // 将选中的物料添加到退库明细
      this.selectedMaterials.forEach(material => {
        // 检查是否已存在该物料，避免重复添加
        const exists = this.form.returnOrderItemsList.some(
          item => item.materialCode === material.sapNo
        )

        if (!exists) {
          this.form.returnOrderItemsList.push({
            materialId: material.id,
            materialCode: material.sapNo,
            materialName: material.materialName,
            batchCode: null,
            warehouseId: null,
            warehouseName: null,
            locationId: null,
            locationName: null,
            locationCode: null,
            plannedQuantity: 0,
            actualQuantity: 0,
            unitPrice: 0,
            totalAmount: 0,
            remark: null
          })
        } else {
          this.$message.warning(`物料 ${material.materialCode} 已存在，跳过添加`)
        }
      })

      this.materialSelectOpen = false
      this.$message.success(`成功添加 ${this.selectedMaterials.length} 个物料`)
    },
    /** 明细项选择变化 */
    handleItemsSelectionChange(selection) {
      this.selectedItems = selection
      this.multipleItems = selection.length === 0
    },
    /** 删除明细项 */
    handleDeleteItems() {
      if (this.selectedItems.length === 0) {
        this.$message.warning("请选择要删除的明细项")
        return
      }
      this.$confirm('确认删除选中的 ' + this.selectedItems.length + ' 条明细吗？', '提示', {
        type: 'warning'
      }).then(() => {
        const selectedIds = this.selectedItems.map(item => item.materialId)
        this.form.returnOrderItemsList = this.form.returnOrderItemsList.filter(
          item => !selectedIds.includes(item.materialId)
        )
        this.selectedItems = []
        this.multipleItems = true
        this.$message.success("删除成功")
      }).catch(() => {})
    },
    /** 数量变化时计算金额 */
    handleQuantityChange(row) {
      // 重新计算金额
      const amount = (row.actualQuantity || 0) * (row.unitPrice || 0)
      row.totalAmount = parseFloat(amount.toFixed(2))
      this.calculateTotals()
    },
    /** 金额变化 */
    handleAmountChange(row) {
      const amount = (row.actualQuantity || 0) * (row.unitPrice || 0)
      row.totalAmount = parseFloat(amount.toFixed(2))
    },
    /** 格式化金额，保留2位小数 */
    formatAmount(amount) {
      if (amount === null || amount === undefined || isNaN(amount)) {
        return '0.00'
      }
      return parseFloat(amount).toFixed(2)
    },
    /** 计算总数 */
    calculateTotals() {
      if (!this.form.returnOrderItemsList || this.form.returnOrderItemsList.length === 0) {
        this.form.totalPlannedQuantity = 0
        this.form.totalActualQuantity = 0
        return
      }

      const totals = this.form.returnOrderItemsList.reduce(
        (acc, item) => {
          acc.plannedQuantity += parseFloat(item.plannedQuantity) || 0
          acc.actualQuantity += parseFloat(item.actualQuantity) || 0
          return acc
        },
        { plannedQuantity: 0, actualQuantity: 0 }
      )

      this.form.totalPlannedQuantity = totals.plannedQuantity
      this.form.totalActualQuantity = totals.actualQuantity
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return

        // 验证明细表
        if (!this.form.returnOrderItemsList || this.form.returnOrderItemsList.length === 0) {
          this.$message.warning('请至少添加一条退库明细')
          return
        }

        // 自动计算总数
        this.calculateTotals()

        // 提交数据
        const submitData = {
          ...this.form,
          returnOrderItemsList: this.form.returnOrderItemsList.map(item => ({
            ...item,
            orderId: this.form.orderId // 确保明细项有主表ID
          }))
        }

        if (this.form.id != null) {
          updateReturnOrder(submitData).then(response => {
            this.$message.success("修改成功")
            this.open = false
            this.getList()
          })
        } else {
          addReturnOrder(submitData).then(response => {
            this.$message.success("新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: null,
        orderId: null,
        returnDate: null,
        returnType: '1',
        ownerId: null,
        ownerName: null,
        ownerCode: null,
        originalOrderId: null,
        returnReason: null,
        orderStatus: 1,
        totalPlannedQuantity: 0,
        totalActualQuantity: 0,
        remark: null,
        returnOrderItemsList: []
      }
      this.selectedItems = []
      this.multipleItems = true
      this.isDetailMode = false
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    /** 导出退库单数据 */
    handleExport() {
      const params = { ...this.queryParams }
      if (params.dateRange && params.dateRange.length === 2) {
        params.startDate = params.dateRange[0]
        params.endDate = params.dateRange[1]
      }
      delete params.dateRange
      delete params.pageNum
      delete params.pageSize

      this.download('inventory/return_order_items/export', {
        ...params
      }, `退库物料数据_${new Date().getTime()}.xlsx`)
    },
    /** 查询字典数据列表 */
    getDictData() {
      this.loading = true
      listData({"dictType": "return_orders_type"}).then(response => {
        this.returnTypeOptions = response.rows.map(item => {return {value: item.dictValue, label: item.dictLabel}})
        this.loading = false
        console.log("return_orders_type", response.rows)
      })
    }
  }
}
</script>

<style scoped>
/* 页面容器样式 */
.page-container {
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 140px);
  min-height: 600px;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  min-height: 0;
  margin-top: 16px;
  display: flex;
  flex-direction: column;
}

.scrollable-dialog .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.link-text {
  color: #1890ff;
  cursor: pointer;
}

.link-text:hover {
  text-decoration: underline;
}

.text-content {
  color: #606266;
}

.w20 {
  width: 150px;
}
</style>

