<template>
  <div class="app-container">
    <div class="head-container">
      <div>
        <el-form :inline="true" label-position="right" label-width="100px" label-suffix=":" class="demo-form-inline">
          <el-form-item label="ID"><el-input v-model="query.id" clearable size="mini" placeholder="请输入ID" @keyup.enter.native="crud.toQuery" /></el-form-item>
          <el-form-item label="操作人"><el-input v-model="query.creator" clearable size="mini" placeholder="请输入操作人" @keyup.enter.native="crud.toQuery" /></el-form-item>
          <el-form-item label="工单编号"><el-input v-model="query.workOrder" clearable size="mini" placeholder="请输入工单编号" @keyup.enter.native="crud.toQuery" /></el-form-item>
          <el-form-item label="物料编码"><el-input v-model="query.skuCode" clearable size="mini" placeholder="请输入物料编码/名称" @keyup.enter.native="crud.toQuery" /></el-form-item>
          <el-form-item label="产线"><el-input v-model="query.productionLine" clearable size="mini" placeholder="请输入产线" @keyup.enter.native="crud.toQuery" /></el-form-item>
          <el-form-item label="目标地点"><el-input v-model="query.targetArea" clearable size="mini" placeholder="请输入目标库存地点" @keyup.enter.native="crud.toQuery" /></el-form-item>
          <el-form-item label="状态">
            <el-select v-model="query.status" clearable size="mini" placeholder="请选择状态" class="filter-item" @change="crud.toQuery">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="需求日期">
            <el-date-picker v-model="query.datepick" type="daterange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <rrOperation :crud="crud" />
        </el-form>
      </div>
      <div style="margin-bottom: 10px; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
        <crudOperation :permission="permission" />
        <el-button size="mini" type="success" :disabled="!multipleSelection.length" @click="handleBatchPush">下推</el-button>
      </div>
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="900px">
        <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="110px" label-suffix=":" style="border: 1px solid #cfe0df;margin-top: 10px;padding: 10px;">
          <el-row>
            <el-col :span="12"><el-form-item label="操作人" prop="creator"><el-input v-model.trim="form.creator" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="需求日期" prop="createTime"><el-date-picker v-model="form.createTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择需求日期" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="优先级" prop="priority"><el-input-number v-model="form.priority" :min="0" :max="99999" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="状态" prop="status"><el-select v-model="form.status" style="width: 280px;" placeholder="请选择状态"><el-option v-for="item in statusOptions" :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="workOrder"><el-input v-model.trim="form.workOrder" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="物料编码" prop="skuCode"><el-input v-model.trim="form.skuCode" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="物料名称" prop="skuName"><el-input v-model.trim="form.skuName" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="数量" prop="qty"><el-input-number v-model="form.qty" :min="0" :precision="4" :step="1" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="已分配数量" prop="assignQty"><el-input-number v-model="form.assignQty" :min="0" :precision="4" :step="1" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="单位" prop="unit"><el-input v-model.trim="form.unit" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="目标库存地点" prop="targetArea"><el-input v-model.trim="form.targetArea" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="产线" prop="productionLine"><el-input v-model.trim="form.productionLine" style="width: 280px;" /></el-form-item></el-col>
            <el-col :span="12"><el-form-item label="车辆序列号" prop="sn"><el-input v-model.trim="form.sn" style="width: 280px;" /></el-form-item></el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer"><el-button type="text" @click="crud.cancelCU">取消</el-button><el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button></div>
      </el-dialog>

      <!-- 库存分配对话框 -->
      <el-dialog :visible.sync="allocateVisible" title="库存分配" width="820px" :close-on-click-modal="false" @close="closeAllocateDialog">
        <div style="margin-bottom:10px;color:#606266;font-size:13px;">
          需求单：<strong>{{ currentDemand.workOrder }}</strong> &nbsp;|&nbsp;
          物料：<strong>{{ currentDemand.skuCode }} {{ currentDemand.skuName }}</strong> &nbsp;|&nbsp;
          需求数量：<strong style="color:#E6A23C;">{{ currentDemand.qty }} {{ currentDemand.unit }}</strong>
        </div>
        <el-table ref="allocateTable" :data="inventoryList" size="small" border v-loading="inventoryLoading" @selection-change="handleInventorySelection">
          <el-table-column type="selection" width="45" />
          <el-table-column prop="houseCode" label="仓库编号" min-width="130" show-overflow-tooltip />
          <el-table-column prop="houseName" label="仓库名称" min-width="140" show-overflow-tooltip />
          <el-table-column prop="skuCode" label="物料编码" min-width="130" show-overflow-tooltip />
          <el-table-column prop="qty" label="库存数量" width="110" />
          <el-table-column label="分配数量" width="160">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.allocQty" :min="0" :max="scope.row.qty" :precision="4" size="mini" style="width:130px;" :disabled="!scope.row._selected" />
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="closeAllocateDialog">取消</el-button>
          <el-button size="mini" type="primary" :loading="allocateSaving" @click="saveAllocate">保存分配</el-button>
        </div>
      </el-dialog>

      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="220" show-overflow-tooltip />
        <el-table-column prop="creator" label="操作人" min-width="100" show-overflow-tooltip />
        <el-table-column prop="createTime" label="需求日期" min-width="160" show-overflow-tooltip />
        <el-table-column prop="priority" label="优先级" width="80" />
        <el-table-column prop="status" label="状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="statusTagType(scope.row.status)" size="mini">{{ statusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="workOrder" label="工单编号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="skuCode" label="物料编码" min-width="140" show-overflow-tooltip />
        <el-table-column prop="skuName" label="物料名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="qty" label="数量" width="100" />
        <el-table-column prop="assignQty" label="已分配数量" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="targetArea" label="目标库存地点" min-width="140" show-overflow-tooltip />
        <el-table-column prop="productionLine" label="产线" min-width="100" show-overflow-tooltip />
        <el-table-column prop="sn" label="车辆序列号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="createAt" label="创建时间" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="180px" align="center" fixed="right">
          <template slot-scope="scope">
            <udOperation style="display: inline" :data="scope.row" :permission="permission" />
            <el-button size="mini" type="warning" plain style="margin-left:4px;" @click="openAllocateDialog(scope.row)">分配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDemand, { queryInventory, allocate, push } from './demand'
import CRUD, { crud, form, header, presenter } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import rrOperation from '@crud/RR.operation.vue'
import pagination from '@crud/Pagination.vue'

const createDefaultForm = () => ({ id: null, creator: '', createTime: '', priority: 0, status: 0, workOrder: '', skuCode: '', skuName: '', qty: undefined, unit: '', targetArea: '', productionLine: '', sn: '' })

export default {
  name: 'Demand',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(createDefaultForm()), crud()],
  cruds() {
    return CRUD({ title: '需求单', url: 'api/pmDemand', idField: 'id', sort: 'priority,desc', crudMethod: { ...crudDemand }, optShow: { add: true, reset: true } })
  },
  data() {
    return {
      permission: {},
      statusOptions: [
        { value: '0', label: '生成' },
        { value: '01', label: '分配' },
        { value: '10', label: '下发' },
        { value: '20', label: '执行' },
        { value: '50', label: '待回传' },
        { value: '70', label: '回传失败' },
        { value: '80', label: '完成' },
        { value: '90', label: '取消' }
      ],
      allocateVisible: false,
      inventoryLoading: false,
      allocateSaving: false,
      currentDemand: {},
      inventoryList: [],
      selectedInventory: [],
      multipleSelection: [],
      rules: {
        creator: [{ required: true, message: '请输入操作人', trigger: 'blur' }],
        createTime: [{ required: true, message: '请选择需求日期', trigger: 'change' }],
        priority: [{ required: true, message: '请输入优先级', trigger: 'change' }],
        workOrder: [{ required: true, message: '请输入工单编号', trigger: 'blur' }],
        skuCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
        skuName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
        qty: [{ required: true, message: '请输入数量', trigger: 'change' }],
        unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        targetArea: [{ required: true, message: '请输入目标库存地点', trigger: 'blur' }],
        productionLine: [{ required: true, message: '请输入产线', trigger: 'blur' }]
      }
    }
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {
      if (this.query.datepick) {
        this.query.startTime = this.query.datepick[0]
        this.query.endTime = this.query.datepick.length > 1 ? this.query.datepick[1] : this.query.datepick[0]
      } else {
        this.query.startTime = ''
        this.query.endTime = ''
      }
    },
    statusLabel(status) {
      const target = this.statusOptions.find(item => String(item.value) === String(status))
      return target ? target.label : status
    },
    statusTagType(status) {
      const map = { 0: '', '01': 'warning', '10': 'primary', '20': 'primary', '80': 'success', '90': 'danger' }
      return map[String(status)] || ''
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    openAllocateDialog(row) {
      this.currentDemand = { ...row }
      this.inventoryList = []
      this.selectedInventory = []
      this.allocateVisible = true
      this.inventoryLoading = true
      queryInventory(row.skuCode).then(res => {
        const demandQty = Number(row.qty) || 0
        this.inventoryList = (res || []).map(item => ({
          ...item,
          _selected: false,
          allocQty: Math.min(Number(item.qty) || 0, demandQty)
        }))
        if (row.inventoryDis) {
          try {
            const saved = JSON.parse(row.inventoryDis)
            const savedList = Array.isArray(saved) ? saved : [saved]
            this.inventoryList.forEach(item => {
              const match = savedList.find(s => (s.horseCode || s.houseCode) === item.houseCode)
              if (match) {
                item._selected = true
                item.allocQty = Number(match.qty || match.allocQty || 0)
                this.$nextTick(() => {
                  this.$refs.allocateTable && this.$refs.allocateTable.toggleRowSelection(item, true)
                })
              }
            })
          } catch (e) { }
        }
      }).finally(() => {
        this.inventoryLoading = false
      })
    },
    closeAllocateDialog() {
      this.allocateVisible = false
      this.currentDemand = {}
      this.inventoryList = []
      this.selectedInventory = []
    },
    handleInventorySelection(selection) {
      this.selectedInventory = selection
      this.inventoryList.forEach(item => {
        item._selected = selection.some(s => s.houseCode === item.houseCode)
      })
    },
    saveAllocate() {
      if (!this.selectedInventory.length) {
        this.$message.warning('请至少勾选一条库存记录')
        return
      }
      const invalidRow = this.selectedInventory.find(item => !item.allocQty || item.allocQty <= 0)
      if (invalidRow) {
        this.$message.warning(`仓库 ${invalidRow.houseCode} 的分配数量必须大于0`)
        return
      }
      const inventoryDisList = this.selectedInventory.map(item => ({
        horseCode: item.houseCode,
        qty: item.allocQty
      }))
      const inventoryDis = inventoryDisList.length === 1 ? JSON.stringify(inventoryDisList[0]) : JSON.stringify(inventoryDisList)
      this.allocateSaving = true
      allocate({ id: this.currentDemand.id, inventoryDis }).then(() => {
        this.$message.success('库存分配成功')
        this.closeAllocateDialog()
        this.crud.toQuery()
      }).catch(() => {
        this.$message.error('库存分配失败')
      }).finally(() => {
        this.allocateSaving = false
      })
    },
    handleBatchPush() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先勾选要下推的需求单')
        return
      }
      const invalidRows = this.multipleSelection.filter(item => String(item.status) !== '01')
      if (invalidRows.length) {
        this.$message.warning('仅支持批量下推状态为“分配”的需求单')
        return
      }
      this.$confirm(`确认批量下推已勾选的 ${this.multipleSelection.length} 条需求单吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        push(this.multipleSelection).then(() => {
          this.$message.success('下推成功')
          this.crud.toQuery()
        }).catch(() => {
          this.$message.error('下推失败')
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
</style>
