<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:return_order_items:export']"
        >导出Excel</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="ownerId">
        <el-input
          v-model="queryOwnerName"
          placeholder="请选择货主"
          readonly
          @focus="openOwnerSelector"
          :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="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入物料ID或编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-input
          v-model="queryWarehouseName"
          placeholder="请选择仓库"
          readonly
          @focus="openWarehouseSelector"
          :suffix-icon="''"
        >
          <template v-if="queryWarehouseName" #suffix>
            <i
              class="el-icon-circle-close el-input__icon"
              style="cursor: pointer;"
              @click.stop="clearQueryWarehouse"
            ></i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="库位" prop="locationId">
        <el-input
          v-model="queryLocationName"
          placeholder="请选择库位"
          readonly
          @focus="openLocationSelector"
          :suffix-icon="''"
          :disabled="!queryParams.warehousesCode"
        >
          <template v-if="queryLocationName" #suffix>
            <i
              class="el-icon-circle-close el-input__icon"
              style="cursor: pointer;"
              @click.stop="clearQueryLocation"
            ></i>
          </template>
        </el-input>
      </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="returnOrderItemList" border height="100%" style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
        <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="ownerName" width="120" />
        <el-table-column label="物料ID" align="center" prop="materialId" width="150" />
        <el-table-column label="物料名称" align="center" prop="materialName" min-width="150" show-overflow-tooltip />
        <el-table-column label="批次ID" align="center" prop="batchCode" width="120" />
        <el-table-column label="仓库" align="center" prop="warehouseName" width="120" />
        <el-table-column label="库位" align="center" prop="locationName" width="120" />
        <el-table-column label="计划数量" align="center" prop="plannedQuantity" width="100" />
        <el-table-column label="实际数量" align="center" prop="actualQuantity" width="100" />
        <el-table-column label="单价" align="center" prop="unitPrice" width="100">
          <template slot-scope="scope">
            {{ formatAmount(scope.row.unitPrice) }}
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="totalAmount" width="120">
          <template slot-scope="scope">
            {{ formatAmount(scope.row.totalAmount || (scope.row.actualQuantity || 0) * (scope.row.unitPrice || 0)) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewDetail(scope.row)"
            >详情</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>

    <!-- 货主选择组件 -->
    <OwnerSelector
      v-model="ownerSelectorVisible"
      @selected="handleOwnerSelected"
    />
    <!-- 仓库选择组件 -->
    <WarehouseSelector
      v-model="warehouseSelectorVisible"
      @selected="handleWarehouseSelected"
    />
    <!-- 库位选择组件 -->
    <LocationSelector
      v-model="locationSelectorVisible"
      :warehousesId="queryParams.warehouseId"
      @selected="handleLocationSelected"
    />
    <!-- 详情弹窗中的仓库选择组件 -->
    <WarehouseSelector
      v-model="detailWarehouseSelectorVisible"
      @selected="handleDetailWarehouseSelected"
    />
    <!-- 详情弹窗中的库位选择组件 -->
    <LocationSelector
      v-model="detailLocationSelectorVisible"
      :warehousesId="detailQueryParams.warehouseId"
      @selected="handleDetailLocationSelected"
    />
    <!-- 详情弹窗 -->
    <el-dialog
      title="退库物料详情"
      :visible.sync="detailDialogVisible"
      width="1400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="detailQueryParams" ref="detailQueryForm" size="small" :inline="true" label-width="100px" style="margin-bottom: 15px;">
        <el-form-item label="仓库" prop="warehouseId">
          <el-input
            v-model="detailWarehouseName"
            placeholder="请选择仓库"
            readonly
            @focus="openDetailWarehouseSelector"
            :suffix-icon="''"
            style="width: 200px;"
          >
            <template v-if="detailWarehouseName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearDetailWarehouse"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="库位" prop="locationId">
          <el-input
            v-model="detailLocationName"
            placeholder="请选择库位"
            readonly
            @focus="openDetailLocationSelector"
            :suffix-icon="''"
            :disabled="!detailQueryParams.warehousesCode"
            style="width: 200px;"
          >
            <template v-if="detailLocationName" #suffix>
              <i
                class="el-icon-circle-close el-input__icon"
                style="cursor: pointer;"
                @click.stop="clearDetailLocation"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="批次号" prop="batchCode">
          <el-input
            v-model="detailQueryParams.batchCode"
            placeholder="请输入批次号"
            clearable
            @keyup.enter.native="handleDetailQuery"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDetailQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetDetailQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="detailLoading"
        :data="detailList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="退库单号" align="center" prop="orderId" width="150" />
        <el-table-column label="物料ID" align="center" prop="materialId" width="150" />
        <el-table-column label="物料名称" align="center" prop="materialName" min-width="150" show-overflow-tooltip />
        <el-table-column label="批次ID" align="center" prop="batchCode" width="120" />
        <el-table-column label="仓库" align="center" prop="warehouseName" width="120" />
        <el-table-column label="库位" align="center" prop="locationName" width="120" />
        <el-table-column label="计划数量" align="center" prop="plannedQuantity" width="100" />
        <el-table-column label="实际数量" align="center" prop="actualQuantity" width="100" />
        <el-table-column label="单价" align="center" prop="unitPrice" width="100">
          <template slot-scope="scope">
            {{ formatAmount(scope.row.unitPrice) }}
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="totalAmount" width="120">
          <template slot-scope="scope">
            {{ formatAmount(scope.row.totalAmount || (scope.row.actualQuantity || 0) * (scope.row.unitPrice || 0)) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip />
      </el-table>
      <pagination
        v-show="detailTotal > 0"
        :total="detailTotal"
        :page.sync="detailQueryParams.pageNum"
        :limit.sync="detailQueryParams.pageSize"
        @pagination="getDetailList"
        style="margin-top: 15px;"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReturnOrderItems } from "@/api/inventory/return_order_items"
import RightToolbar from "@/components/RightToolbar"
import PageTitle from "@/components/PageTitle"
import OwnerSelector from "@/views/compononents/OwnerSelector.vue"
import WarehouseSelector from "@/views/compononents/WarehouseSelector.vue"
import LocationSelector from "@/views/compononents/LocationSelector.vue"

export default {
  name: "ReturnOrderItems",
  components: {
    RightToolbar,
    PageTitle,
    OwnerSelector,
    WarehouseSelector,
    LocationSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 退库物料表格数据
      returnOrderItemList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        startDate: null,
        endDate: null,
        ownerId: null,
        materialId: null,
        warehouseId: null,
        warehousesCode: null,
        locationId: null,
        dateRange: null
      },
      // 货主选择相关
      ownerSelectorVisible: false,
      queryOwnerName: null,
      // 仓库选择相关
      warehouseSelectorVisible: false,
      queryWarehouseName: null,
      // 库位选择相关
      locationSelectorVisible: false,
      queryLocationName: null,
      // 详情弹窗相关
      detailDialogVisible: false,
      detailLoading: false,
      detailList: [],
      detailTotal: 0,
      currentDetailRow: null,
      detailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        materialId: null,
        warehouseId: null,
        warehousesCode: null,
        locationId: null,
        batchCode: null
      },
      // 详情弹窗中的仓库和库位选择
      detailWarehouseSelectorVisible: false,
      detailLocationSelectorVisible: false,
      detailWarehouseName: null,
      detailLocationName: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询退库物料列表 */
    getList() {
      this.loading = true
      // 处理日期范围
      const params = { ...this.queryParams }
      if (params.dateRange && params.dateRange.length === 2) {
        params.startDate = params.dateRange[0]
        params.endDate = params.dateRange[1]
      }
      delete params.dateRange

      listReturnOrderItems(params).then(response => {
        this.returnOrderItemList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryOwnerName = null
      this.queryWarehouseName = null
      this.queryLocationName = null
      this.queryParams.dateRange = null
      this.queryParams.warehousesCode = null
      this.handleQuery()
    },
    /** 打开货主选择器 */
    openOwnerSelector() {
      this.ownerSelectorVisible = true
    },
    /** 货主选择回调 */
    handleOwnerSelected(owner) {
      if (!owner) return
      this.queryParams.ownerId = owner.ownerId || owner.ownerCode
      this.queryOwnerName = owner.ownerName || owner.ownerCode
      this.handleQuery()
    },
    /** 清空货主选择 */
    clearQueryOwner() {
      this.queryOwnerName = null
      this.queryParams.ownerId = null
      this.handleQuery()
    },
    /** 打开仓库选择器 */
    openWarehouseSelector() {
      this.warehouseSelectorVisible = true
    },
    /** 仓库选择回调 */
    handleWarehouseSelected(warehouse) {
      if (!warehouse) return
      this.queryParams.warehouseId = warehouse.warehouseId || warehouse.id
      this.queryParams.warehousesCode = warehouse.warehousesCode
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehousesCode
      // 仓库选择后，清空库位信息
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
      console.log('selected warehouse', warehouse);
    },
    /** 清空仓库选择 */
    clearQueryWarehouse() {
      this.queryWarehouseName = null
      this.queryParams.warehouseId = null
      this.queryParams.warehousesCode = null
      // 清空仓库时，同时清空库位
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 打开库位选择器 */
    openLocationSelector() {
      if (!this.queryParams.warehouseId) {
        this.$message.warning("请先选择仓库")
        return
      }
      this.locationSelectorVisible = true
    },
    /** 库位选择回调 */
    handleLocationSelected(location) {
      if (!location) return
      this.queryParams.locationId = location.locationId || location.id
      this.queryLocationName = location.locationName || location.locationCode
      this.handleQuery()
    },
    /** 清空库位选择 */
    clearQueryLocation() {
      this.queryLocationName = null
      this.queryParams.locationId = null
      this.handleQuery()
    },
    /** 格式化金额，保留2位小数 */
    formatAmount(amount) {
      if (amount === null || amount === undefined || isNaN(amount)) {
        return '0.00'
      }
      return parseFloat(amount).toFixed(2)
    },
    /** 导出退库物料数据 */
    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_orders/export', {
        ...params
      }, `退库单数据_${new Date().getTime()}.xlsx`)
    },
    /** 查看详情 */
    handleViewDetail(row) {
      this.currentDetailRow = row
      this.detailDialogVisible = true
      // 初始化详情查询参数
      this.detailQueryParams = {
        pageNum: 1,
        pageSize: 10,
        orderId: row.orderId,
        materialId: row.materialId,
        warehouseId: null,
        warehousesCode: null,
        locationId: null,
        batchCode: null
      }
      this.detailWarehouseName = null
      this.detailLocationName = null
      this.detailList = []
      this.detailTotal = 0
      this.getDetailList()
    },
    /** 查询详情列表 */
    getDetailList() {
      this.detailLoading = true
      const params = { ...this.detailQueryParams }
      listReturnOrderItems(params).then(response => {
        this.detailList = response.rows || []
        this.detailTotal = response.total || 0
        this.detailLoading = false
      }).catch(() => {
        this.detailLoading = false
      })
    },
    /** 详情搜索按钮操作 */
    handleDetailQuery() {
      this.detailQueryParams.pageNum = 1
      this.getDetailList()
    },
    /** 详情重置按钮操作 */
    resetDetailQuery() {
      this.detailQueryParams.warehouseId = null
      this.detailQueryParams.warehousesCode = null
      this.detailQueryParams.locationId = null
      this.detailQueryParams.batchCode = null
      this.detailWarehouseName = null
      this.detailLocationName = null
      this.detailQueryParams.pageNum = 1
      this.getDetailList()
    },
    /** 打开详情弹窗中的仓库选择器 */
    openDetailWarehouseSelector() {
      this.detailWarehouseSelectorVisible = true
    },
    /** 详情弹窗中仓库选择回调 */
    handleDetailWarehouseSelected(warehouse) {
      if (!warehouse) return
      this.detailQueryParams.warehouseId = warehouse.warehouseId || warehouse.id
      this.detailQueryParams.warehousesCode = warehouse.warehousesCode
      this.detailWarehouseName = warehouse.warehousesName || warehouse.warehousesCode
      // 仓库选择后，清空库位信息
      this.detailLocationName = null
      this.detailQueryParams.locationId = null
    },
    /** 清空详情弹窗中的仓库选择 */
    clearDetailWarehouse() {
      this.detailWarehouseName = null
      this.detailQueryParams.warehouseId = null
      this.detailQueryParams.warehousesCode = null
      // 清空仓库时，同时清空库位
      this.detailLocationName = null
      this.detailQueryParams.locationId = null
    },
    /** 打开详情弹窗中的库位选择器 */
    openDetailLocationSelector() {
      if (!this.detailQueryParams.warehousesCode) {
        this.$message.warning("请先选择仓库")
        return
      }
      this.detailLocationSelectorVisible = true
    },
    /** 详情弹窗中库位选择回调 */
    handleDetailLocationSelected(location) {
      if (!location) return
      this.detailQueryParams.locationId = location.locationId || location.id
      this.detailLocationName = location.locationName || location.locationCode
    },
    /** 清空详情弹窗中的库位选择 */
    clearDetailLocation() {
      this.detailLocationName = null
      this.detailQueryParams.locationId = null
    }
  }
}
</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;
  overflow-x: auto;
}

.mb8 {
  margin-bottom: 8px;
}
</style>

