<template>
  <div class="app-container">
    <!-- 标题栏 + 操作按钮 -->
    <PageTitle>
      <template #buttons>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:items: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="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="请输入物料名或sap编码"
          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
          placeholder="请选择库位"
          v-model="queryLocationName"
          readonly
          @focus="openLocationSelector"
          :suffix-icon="''"
        >
          <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 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>

      <!-- 物料查询表格 -->
      <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="materialName" min-width="150" show-overflow-tooltip />
        <el-table-column label="SAP物料号" align="center" prop="sapNo" width="120" />
        <el-table-column label="TS Code" align="center" prop="tsCode" width="120" />
        <el-table-column label="危险类别" align="center" prop="hazardId" width="120" />
        <el-table-column label="规格型号" align="center" prop="specification" width="120" />
        <el-table-column label="计量单位" align="center" prop="materialUnit" width="120" />
        <el-table-column label="单位重量" align="center" prop="unitWeight" width="120" >
          <template slot-scope="scope">
            {{ formatAmount(scope.row.unitWeight || 0) }}
          </template>
        </el-table-column>
        <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="totalAmount" width="100" >
          <template slot-scope="scope">
            {{ formatAmount(scope.row.totalAmount || 0) }}
          </template>
        </el-table-column>
        <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.warehouseId"
            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>
      <div style="max-height: 600px; overflow: auto;">
        <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="物料名称" align="center" prop="materialName" min-width="150" show-overflow-tooltip />
          <el-table-column label="批次" 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 || 0) }}
            </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>
      </div>
      <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 { listInboundOutboundStatistics, exportInboundOutboundStatistics,listInboundOutboundStatisticsList } from "@/api/inventory/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: "OutboundDetail",
  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,
        orderStatus: 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,
        orderStatus: null
      },
      detailWarehouseSelectorVisible: false,
      detailLocationSelectorVisible: false,
      detailWarehouseName: null,
      detailLocationName: null,
      orderStatusOptions: [
        { value: 1, label: '草稿' },
        { value: 2, label: '已完成' }
      ]
    }
  },
  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

      listInboundOutboundStatistics(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
      this.queryWarehouseName = warehouse.warehousesName || warehouse.warehousesCode
      // this.queryLocationName = null
      // this.queryParams.locationId = null
      this.handleQuery()
    },
    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()
    },
    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/items/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,
        orderStatus: this.queryParams.orderStatus
      }
      this.detailWarehouseName = null
      this.detailLocationName = null
      this.detailList = []
      this.detailTotal = 0
      this.getDetailList()
    },
    getDetailList() {
      this.detailLoading = true
      const params = { ...this.detailQueryParams }
      params.warehouseId = params.warehouseId || this.queryParams.warehouseId
      params.locationId = params.locationId || this.queryParams.locationId

      listInboundOutboundStatisticsList(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
      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.warehouseId) {
        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;
}

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