<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点计划编号" prop="planNo" label-width="110px">
        <el-input v-model="queryParams.planNo" placeholder="请输入盘点计划编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="盘点计划名称" prop="planName" label-width="110px">
        <el-input v-model="queryParams.planName" placeholder="请输入盘点计划名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="计划状态" prop="planStatus">
        <el-select v-model="queryParams.planStatus" placeholder="请选择计划状态">
          <el-option v-for="item in plan_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点方式" prop="inventoryMethod">
        <el-select v-model="queryParams.inventoryMethod" placeholder="请选择盘点方式">
          <el-option v-for="item in plan_mode" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="周期类型" prop="cycleType">
        <el-select v-model="queryParams.cycleType" placeholder="请选择周期类型">
          <el-option v-for="item in cycle_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </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:wmsInventoryPlan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['ware:wmsInventoryPlan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['ware:wmsInventoryPlan:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="VideoPlay" @click="handleGenerateAll"
          v-hasPermi="['ware:wmsInventoryPlan:generate']">执行全部</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wmsInventoryPlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="盘点计划编号" align="center" prop="planNo" width="180" />
      <el-table-column label="盘点计划名称" align="center" prop="planName" width="180" />
      <el-table-column label="盘点类型" align="center" prop="planType">
        <template #default="scope">
          <dict-tag :options="plan_type" :value="scope.row.planType" />
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="warehouseId" />
      <el-table-column label="库区" align="center" prop="areaNames" />
      <el-table-column label="物资" align="center" prop="materialNames" />
      <el-table-column label="计划开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划状态" align="center" prop="planStatus">
        <template #default="scope">
          <dict-tag :options="plan_status" :value="scope.row.planStatus" />
        </template>
      </el-table-column>
      <el-table-column label="盘点方式" align="center" prop="inventoryMethod">
        <template #default="scope">
          <dict-tag :options="plan_mode" :value="scope.row.inventoryMethod" />
        </template>
      </el-table-column>
      <el-table-column label="周期类型" align="center" prop="cycleType">
        <template #default="scope">
          <dict-tag :options="cycle_type" :value="scope.row.cycleType" />
        </template>
      </el-table-column>
      <el-table-column label="周期值" align="center" prop="cycleValue" />
      <!-- <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="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['ware:wmsInventoryPlan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ware:wmsInventoryPlan:remove']">删除</el-button>
          <el-button link type="primary" icon="VideoPlay" @click="handleGenerate(scope.row)"
            v-hasPermi="['ware:wmsInventoryPlan:generate']">执行</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="wmsInventoryPlanRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="盘点计划编号" prop="planNo">
          <el-input v-model="form.planNo" placeholder="请输入盘点计划编号" />
        </el-form-item>
        <el-form-item label="盘点计划名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入盘点计划名称" />
        </el-form-item>
        <el-form-item label="盘点类型" prop="planType">
          <el-select v-model="form.planType" placeholder="请选择盘点类型" @change="handlePlanTypeChange">
            <el-option v-for="item in plan_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <div style="display: flex; align-items: center;">
            <el-input v-model="form.warehouseName" placeholder="请选择仓库" readonly style="flex: 1;" />
            <el-button type="primary" @click="openWarehouseSelectDialog">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="库区" prop="areaIds">
          <div style="display: flex; align-items: center;">
            <el-input v-model="form.areaNames" placeholder="请选择库区" readonly style="flex: 1;" />
            <el-button type="primary" @click="openAreaSelectDialog">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="物资" prop="materialIds">
          <div style="display: flex; align-items: center;">
            <el-input v-model="form.materialNames" placeholder="请选择物资" readonly style="flex: 1;" />
            <el-button type="primary" @click="openMaterialSelectDialog">选择</el-button>
          </div>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="盘点方式" prop="inventoryMethod">
          <el-select v-model="form.inventoryMethod" placeholder="请选择盘点方式">
            <el-option v-for="item in plan_mode" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="周期类型" prop="cycleType" v-if="form.planType === '1'">
          <el-select v-model="form.cycleType" placeholder="请选择周期类型">
            <el-option v-for="item in cycle_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="周期值" prop="cycleValue" v-if="form.planType === '1'">
          <el-input v-model="form.cycleValue" placeholder="请输入周期值" />
        </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="warehouseSelectVisible"
      @confirm="handleWarehouseConfirm" />

    <!-- 库区选择对话框 -->
    <AreaSelectTreeDialog ref="areaSelectDialogRef" v-model:visible="areaSelectVisible" @confirm="handleAreaConfirm" />

    <!-- 物资选择对话框 -->
    <MaterialSelectDialog ref="materialSelectDialogRef" v-model:visible="materialSelectVisible"
      @confirm="handleMaterialConfirm" />
  </div>
</template>

<script setup name="WmsInventoryPlan">
import { listWmsInventoryPlan, getWmsInventoryPlan, delWmsInventoryPlan, addWmsInventoryPlan, updateWmsInventoryPlan, generateAllInventoryPlan, generateInventoryPlan } from "@/api/ware/wmsInventoryPlan"
import WarehouseSelectDialog from "@/components/WarehouseSelectDialog.vue"
import AreaSelectTreeDialog from "@/components/AreaSelectTreeDialog.vue"
import MaterialSelectDialog from "@/components/MaterialSelectDialog.vue"

const { proxy } = getCurrentInstance()

const { cycle_type, plan_type, plan_mode, plan_status } = proxy.useDict('cycle_type', 'plan_type', 'plan_mode', 'plan_status')

const wmsInventoryPlanList = 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 warehouseSelectDialogRef = ref(null)
const areaSelectDialogRef = ref(null)
const materialSelectDialogRef = ref(null)

const warehouseSelectVisible = ref(false)
const areaSelectVisible = ref(false)
const materialSelectVisible = ref(false)

const data = reactive({
  form: {
    warehouseName: '',
    areaNames: '',
    materialNames: ''
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planNo: null,
    planName: null,
    planType: null,
    warehouseId: null,
    areaIds: null,
    materialIds: null,
    startTime: null,
    endTime: null,
    planStatus: null,
    inventoryMethod: null,
    cycleType: null,
    cycleValue: null,
    approvalStatus: null,
  },
  rules: {
    planNo: [
      { required: true, message: "盘点计划编号不能为空", trigger: "blur" }
    ],
    planName: [
      { required: true, message: "盘点计划名称不能为空", trigger: "blur" }
    ],
    planType: [
      { required: true, message: "盘点类型不能为空", trigger: "change" }
    ],
    warehouseId: [
      { required: true, message: "仓库ID不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "计划开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "计划结束时间不能为空", trigger: "blur" }
    ],
    inventoryMethod: [
      { required: true, message: "盘点方式不能为空", trigger: "change" }
    ],
    cycleType: [
      { required: true, message: "周期类型不能为空", trigger: "change" }
    ],
    cycleValue: [
      { required: true, message: "周期值不能为空", trigger: "blur" }
    ],
  }
})

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

/** 查询盘点计划列表 */
function getList() {
  loading.value = true
  listWmsInventoryPlan(queryParams.value).then(response => {
    wmsInventoryPlanList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

// 打开仓库选择对话框
function openWarehouseSelectDialog() {
  warehouseSelectVisible.value = true
  warehouseSelectDialogRef.value?.handleQuery()
}

// 打开库区选择对话框
function openAreaSelectDialog() {
  areaSelectVisible.value = true
  areaSelectDialogRef.value?.handleQuery()
}

// 打开物资选择对话框
function openMaterialSelectDialog() {
  materialSelectVisible.value = true
  materialSelectDialogRef.value?.handleQuery()
}

// 处理仓库选择确认
function handleWarehouseConfirm(selection) {
  if (selection && selection.length > 0) {
    const warehouse = selection[0]
    form.value.warehouseId = warehouse.warehouseId
    form.value.warehouseName = warehouse.warehouseName
  }
}

// 处理库区选择确认
function handleAreaConfirm(selection) {
  if (selection && selection.length > 0) {
    form.value.areaIds = '|' + selection.map(item => item.areaId).join('||') + '|'
    form.value.areaNames = selection.map(item => item.areaName).join(',')
  }
}

// 处理物资选择确认
function handleMaterialConfirm(selection) {
  if (selection && selection.length > 0) {
    form.value.materialIds = '|' + selection.map(item => item.materialId).join('||') + '|'
    form.value.materialNames = selection.map(item => item.materialName).join(',')
  }
}

// 表单重置
function reset() {
  form.value = {
    planId: null,
    planNo: null,
    planName: null,
    planType: '1',
    warehouseId: null,
    warehouseName: '',
    areaIds: null,
    areaNames: '',
    materialIds: null,
    materialNames: '',
    startTime: null,
    endTime: null,
    planStatus: null,
    inventoryMethod: null,
    cycleType: null,
    cycleValue: null,
    approvalStatus: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("wmsInventoryPlanRef")
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加盘点计划"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  form.value = row;
  open.value = true
  title.value = "修改盘点计划"
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _planIds = row.planId || ids.value
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delWmsInventoryPlan(_planIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

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

/** 执行全部计划 */
function handleGenerateAll() {
  proxy.$modal.confirm('是否确认执行全部盘点计划？').then(function() {
    return generateAllInventoryPlan()
  }).then((response) => {
    proxy.$modal.msgSuccess(response.msg || "执行成功")
    getList()
  }).catch(() => {})
}

/** 执行单个计划 */
function handleGenerate(row) {
  proxy.$modal.confirm('是否确认执行该盘点计划？').then(function() {
    return generateInventoryPlan(row.planId)
  }).then((response) => {
    proxy.$modal.msgSuccess(response.msg || "执行成功")
    getList()
  }).catch(() => {})
}

/** 处理盘点类型改变 */
function handlePlanTypeChange() {
  if (form.value.planType !== '1') { // 手动盘点
    form.value.cycleType = null
    form.value.cycleValue = null
  }
}

getList()
</script>
