<template>
  <div class="app-container-page">
    <el-form class="table-form-search" ref="queryRef" :model="queryParams" :inline="true" v-show="showSearch"
      label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目编码" prop="project">
            <el-input v-model="queryParams.project" placeholder="请输入项目编码" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仓库编码" prop="warehouse">
            <el-input v-model="queryParams.warehouse" placeholder="请输入仓库编码" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上行 Topic" prop="topicUp">
            <el-input v-model="queryParams.topicUp" placeholder="请输入上行 Topic" clearable @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="下行 Topic" prop="topicDownPrefix">
            <el-input v-model="queryParams.topicDownPrefix" placeholder="请输入下行 Topic" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属部门" prop="deptId">
            <DepartmentCascaDer v-model="queryParams.deptId" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="searchBtn">
          <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-col>
      </el-row>
    </el-form>
    <div class="table-list">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['worn:mqttConfig:add']">
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
            v-hasPermi="['worn:mqttConfig:edit']">
            修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['worn:mqttConfig:remove']">
            删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['worn:mqttConfig:export']">
            导出
          </el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
      </el-row>

      <el-table v-loading="loading" :data="mqttConfigList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="id" />
        <el-table-column label="项目编码" align="center" prop="project" />
        <el-table-column label="仓库编码" align="center" prop="warehouse" />

        <el-table-column label="所属部门" align="center" prop="deptId">
          <template #default="scope">
            {{ getDictLabel(scope.row.deptId, departmentList, { name: 'deptName', value: 'deptId' }) }}
          </template>

        </el-table-column>
        <el-table-column label="上行 Topic" align="center" prop="topicUp" min-width="220" show-overflow-tooltip />
        <el-table-column label="下行 Topic" align="center" prop="topicDownPrefix" min-width="240" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
              {{ scope.row.status === '0' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" align="center"  min-width="100">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['worn:mqttConfig:edit']">
              修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['worn:mqttConfig: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" />
    </div>

    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="mqttConfigRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编码" prop="project">
              <el-input v-model="form.project" placeholder="请输入项目编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehouse">
              <el-input v-model="form.warehouse" placeholder="请输入仓库编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <DepartmentCascaDer v-model="form.deptId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio value="0">启用</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上行 Topic" prop="topicUp">
              <el-input v-model="form.topicUp" placeholder="请输入上行 Topic" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下行 Topic" prop="topicDownPrefix">
              <el-input v-model="form.topicDownPrefix" placeholder="请输入下行 Topic" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>
  </div>
</template>

<script setup name="MqttConfig">
import { listDept } from '@/api/system/dept'
import { getDictLabel, getDeptIdPath } from '@/utils/until'
import { addMqttConfig, delMqttConfig, getMqttConfig, listMqttConfig, updateMqttConfig } from "@/api/worn/mqttConfig"
import DepartmentCascaDer from '../../../components/DepartmentCascaDer/index.vue'

const { proxy } = getCurrentInstance()

const total = ref(0)
const title = ref("")

const ids = ref([])
const mqttConfigList = ref([])
const departmentList = ref([]);

const open = ref(false)
const single = ref(true)
const loading = ref(true)
const multiple = ref(true)
const showSearch = ref(true)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    project: null,
    warehouse: null,
    deptId: null,
    topicUp: null,
    topicDownPrefix: null,
    status: null
  },
  rules: {
    project: [{ required: true, message: "项目编码不能为空", trigger: "blur" }],
    warehouse: [{ required: true, message: "仓库编码不能为空", trigger: "blur" }],
    topicUp: [{ required: true, message: "上行 Topic 不能为空", trigger: "blur" }],
    topicDownPrefix: [{ required: true, message: "下行 Topic不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }]
  }
})

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


function getDepartmentListFun() {
  listDept().then((response) => {
    departmentList.value = response.data
  });
}
getDepartmentListFun()

function getList() {
  loading.value = true
  listMqttConfig(queryParams.value).then(response => {
    mqttConfigList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: null,
    project: null,
    warehouse: null,
    deptId: null,
    topicUp: null,
    topicDownPrefix: null,
    status: "0",
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    isDelete: "0"
  }
  proxy.resetForm("mqttConfigRef")
}

function handleQuery() {
  queryParams.value.pageNum = 1
  if (queryParams.value.deptId) {
    queryParams.value.deptId = queryParams.value.deptId.at(-1)
  }
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = selection.length === 0
}

function handleAdd() {
  reset()
  open.value = true
  title.value = "新增 MQTT 主题配置"
}

function handleUpdate(row) {
  reset()
  const currentId = row?.id || ids.value[0]
  getMqttConfig(currentId).then(response => {
    const department = proxy.handleTree(departmentList.value, "deptId")
    const deptId = getDeptIdPath(department, response.data.deptId)
    form.value = { ...response.data, deptId }
    if (!form.value.status) {
      form.value.status = "0"
    }
    open.value = true
    title.value = "修改 MQTT 主题配置"
  })
}

function submitForm() {
  proxy.$refs["mqttConfigRef"].validate(valid => {
    if (!valid) {
      return
    }
    form.value = { ...form.value, deptId: form.value.deptId.at(-1) }
    const request = form.value.id != null ? updateMqttConfig(form.value) : addMqttConfig(form.value)
    request.then(() => {
      proxy.$modal.msgSuccess(form.value.id != null ? "修改成功" : "新增成功")
      open.value = false
      getList()
    })
  })
}

function handleDelete(row) {
  const currentIds = row?.id || ids.value
  proxy.$modal.confirm(`是否确认删除 MQTT 主题配置编号为 "${currentIds}" 的数据项？`).then(() => {
    return delMqttConfig(currentIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

function handleExport() {
  proxy.download("worn/mqttConfig/export", {
    ...queryParams.value
  }, `mqttConfig_${new Date().getTime()}.xlsx`)
}

getList()
</script>
