<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资" prop="materialId">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="阈值" prop="thresholdValue">
        <el-input
          v-model="queryParams.thresholdValue"
          placeholder="请输入阈值"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
  
      <el-form-item label="预警级别" prop="alertLevel">
        <el-select
          v-model="queryParams.alertLevel"
          placeholder="请选择预警级别"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option v-for="item in alert_level" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnabled">
        <el-radio-group v-model="queryParams.isEnabled">
          <el-radio v-for="item in is_enabled" :key="item.value" :label="item.value" :value="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </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:wmsAlertRule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ware:wmsAlertRule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ware:wmsAlertRule:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wmsAlertRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="预警类型" align="center" prop="alertType">
        <template #default="scope">
          <dict-tag :options="alarm_type" :value="scope.row.alertType" />
        </template>
      </el-table-column>
      <el-table-column label="物资信息" align="center">
        <template #default="scope">
          <div>{{ scope.row.material?.materialName  }}</div>
          <div style="font-size: 12px; color: #909399;">{{ scope.row.material?.materialCode  }} | {{ scope.row.material?.unit }} | {{ scope.row.material?.specification }}</div>
        </template>
      </el-table-column>
      <el-table-column label="阈值" align="center" prop="thresholdValue" />
      <el-table-column label="比较运算符" align="center" prop="comparisonOperator">
        <template #default="scope">
          <dict-tag :options="comparison_operator" :value="scope.row.comparisonOperator" />
        </template>
      </el-table-column>
      <el-table-column label="预警级别" align="center" prop="alertLevel">
        <template #default="scope">
          <dict-tag :options="alert_level" :value="scope.row.alertLevel" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="通知方式" align="center" prop="notificationType" />
      <el-table-column label="通知接收人" align="center" prop="notificationReceivers" /> -->
      <el-table-column label="是否启用" align="center" prop="isEnabled">
        <template #default="scope">
          <dict-tag :options="is_enabled" :value="scope.row.isEnabled" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ware:wmsAlertRule:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ware:wmsAlertRule:remove']">删除</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="wmsAlertRuleRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="预警类型" prop="alertType">
          <el-select v-model="form.alertType" placeholder="请选择预警类型">
            <el-option v-for="item in alarm_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物资" prop="materialId">
          <el-input v-model="form.materialName" placeholder="请选择物资" readonly style="cursor: pointer;" @click="openMaterialSelectDialog">
            <template #append>
              <el-button type="primary" size="small" @click="openMaterialSelectDialog">选择</el-button>
            </template>
          </el-input>
          
        </el-form-item>
        <el-form-item label="阈值" prop="thresholdValue">
          <el-input v-model="form.thresholdValue" placeholder="请输入阈值" />
        </el-form-item>
        <el-form-item label="比较运算符" prop="comparisonOperator">
          <el-select v-model="form.comparisonOperator" placeholder="请选择比较运算符">
            <el-option v-for="item in comparison_operator" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警级别" prop="alertLevel">
          <el-select v-model="form.alertLevel" placeholder="请选择预警级别">
            <el-option v-for="item in alert_level" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
       
        <el-form-item label="是否启用" prop="isEnabled">
          <el-select v-model="form.isEnabled" placeholder="请选择是否启用">
            <el-option v-for="item in is_enabled" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </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>

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

<script setup name="WmsAlertRule">
import { listWmsAlertRule, getWmsAlertRule, delWmsAlertRule, addWmsAlertRule, updateWmsAlertRule } from "@/api/ware/wmsAlertRule"
import MaterialSelectDialog from "@/components/MaterialSelectDialog.vue"

const { proxy } = getCurrentInstance()
const { alarm_type,alert_level,is_enabled } = proxy.useDict('alarm_type', 'alert_level', 'is_enabled')


const comparison_operator = [
  { value: '>', label: '大于' },
  { value: '<', label: '小于' },
  { value: '>=', label: '大于等于' },
  { value: '<=', label: '小于等于' },
  { value: '==', label: '等于' },
  { value: '!=', label: '不等于' },
]

const wmsAlertRuleList = 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 materialSelectDialogRef = ref(null)
const materialSelectVisible = ref(false)
const materialInfo = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ruleName: null,
    alertType: null,
    warehouseId: null,
    materialCategoryId: null,
    materialId: null,
    materialName: null, // 使用物资名称搜索而非ID
    conditionType: null,
    thresholdValue: null,
    comparisonOperator: null,
    alertLevel: null,
    notificationType: null,
    notificationReceivers: null,
    isEnabled: null,
  },
  rules: {
      ruleName: [
        { required: true, message: "规则名称不能为空", trigger: "blur" }
      ],
      alertType: [
        { required: true, message: "预警类型不能为空", trigger: "change" }
      ],
      materialId: [
        { required: true, message: "物资ID不能为空", trigger: "change" }
      ],
    thresholdValue: [
      { required: true, message: "阈值不能为空", trigger: "blur" }
    ],
    comparisonOperator: [
      { required: true, message: "比较运算符不能为空", trigger: "change" }
    ],
    alertLevel: [
      { required: true, message: "预警级别不能为空", trigger: "change" }
    ],
    notificationReceivers: [
      { required: true, message: "通知接收人不能为空", trigger: "blur" }
    ],
    isEnabled: [
      { required: true, message: "是否启用不能为空", trigger: "change" }
    ],
  }
})

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

/** 查询预警规则列表 */
function getList() {
  loading.value = true
  listWmsAlertRule(queryParams.value).then(response => {
    wmsAlertRuleList.value = response.rows || []
    total.value = response.total
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    ruleId: null,
    ruleName: null,
    alertType: null,
    warehouseId: null,
    materialCategoryId: null,
    materialId: null,
    conditionType: null,
    thresholdValue: null,
    comparisonOperator: null,
    alertLevel: null,
    notificationType: null,
    notificationReceivers: null,
    isEnabled: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("wmsAlertRuleRef")
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加预警规则"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _ruleId = row.ruleId || ids.value
  getWmsAlertRule(_ruleId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改预警规则"
  })
}

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

// 处理物资选择确认
function handleMaterialSelectConfirm(materials) {
  if (materials && materials.length > 0) {
    const selectedMaterial = materials[0]
    form.value.materialId = selectedMaterial.materialId
    form.value.materialName = selectedMaterial.materialName
    // 可以选择存储更多物资信息，方便显示
    materialInfo.value = selectedMaterial
  }
}

// 处理物资选择取消
function handleMaterialSelectCancel() {
  materialSelectVisible.value = false
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _ruleIds = row.ruleId || ids.value
  proxy.$modal.confirm('是否确认删除预警规则编号为"' + _ruleIds + '"的数据项？').then(function() {
    return delWmsAlertRule(_ruleIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

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

getList()
</script>
