<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名" prop="equipmentName">
        <el-input v-model="queryParams.equipmentName" placeholder="请输入设备名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="流程归属" prop="flowId">
        <el-select v-model="queryParams.flowId" placeholder="请选择流程归属" clearable style="width: 200px;">
          <el-option v-for="dict in flowOptions" :key="dict.flowId" :label="dict.flowName" :value="dict.flowId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.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="['hnyz:extension:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['hnyz:extension:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['hnyz:extension:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['hnyz:extension:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="extensionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="流程名称" align="center" prop="flowName" />
      <el-table-column label="x坐标" align="center" prop="x" :formatter="(row) => formatNumber(row.x)" />
      <el-table-column label="y坐标" align="center" prop="y" :formatter="(row) => formatNumber(row.y)" />
      <el-table-column label="尺寸(px)" align="center" prop="size" />
      <el-table-column label="启用状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <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="['hnyz:extension:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['hnyz:extension: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="extensionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="equipmentId">
          <el-select v-model="form.equipmentId" placeholder="请选择设备名称" @change="getRealFlowOptions" filterable>
            <el-option v-for="dict in realEquipmentOptions" :key="dict.equipmentId" :label="dict.equipmentName"
              :value="dict.equipmentId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流程名称" prop="flowId">
          <el-select v-model="form.flowId" placeholder="请选择流程名称" @change="getRealEquipmentOptions" filterable>
            <el-option v-for="dict in realFlowOptions" :key="dict.flowId" :label="dict.flowName"
              :value="dict.flowId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="x坐标" prop="x">
          <el-input v-model="form.x" placeholder="请输入x坐标" />
        </el-form-item>
        <el-form-item label="y坐标" prop="y">
          <el-input v-model="form.y" placeholder="请输入y坐标" />
        </el-form-item>
        <el-form-item label="尺寸" prop="size">
          <el-input-number v-model="form.size" placeholder="请输入尺寸,单位px" style="width: 100%;"
            controls-position="right" class="sizeInput"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </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>
  </div>
</template>

<script setup name="Extension">
import { changeStatus, listExtension, getExtension, delExtension, addExtension, updateExtension, getEquipmentExtensionFormList } from "@/api/hnyz/extension";
import { getFlowList } from "@/api/hnyz/flow";
import { getEquipmentList } from "@/api/hnyz/equipment";
import { onMounted } from "vue";
onMounted(() => {
  getFlowOptions();
  getEquipmentOptions();
});
const flowOptions = ref([]);// 流程选项
// 获取总流程选项
function getFlowOptions() {
  getFlowList({}).then(response => {
    flowOptions.value = response.data;
    realFlowOptions.value = response.data;
  });
}
const equipmentOptions = ref([]);// 设备选项
// 获取设备选项
function getEquipmentOptions() {
  getEquipmentList().then(response => {
    equipmentOptions.value = response.data;
    realEquipmentOptions.value = response.data;
  });
}

const realEquipmentOptions = ref([]);// 真实设备选项
const realFlowOptions = ref([]);// 真实流程选项

// 获取真实流程选项
function getRealFlowOptions() {
  const params = { equipmentId: form.value.equipmentId };
  getFlowList(params).then(response => {
    realFlowOptions.value = response.data;
    //如果queryparams中的flowId不在真实流程选项中，则将其设置为默认值
    if (form.value.flowId && !realFlowOptions.value.some(item => item.flowId == form.value.flowId)) {
      form.value.flowId = null;
    }
  });
}
//获取真实设备选项
function getRealEquipmentOptions() {
  getEquipmentList({ flowIds: form.value.flowId }).then(response => {
    realEquipmentOptions.value = response.data;
    //如果queryparams中的equipmentId不在真实设备选项中，则将其设置为默认值
    if (form.value.equipmentId && !realEquipmentOptions.value.some(item => item.equipmentId == form.value.equipmentId)) {
      form.value.equipmentId = null;
    }
  });
}
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const extensionList = 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 data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentId: null,
    equipmentName: null,
    flowId: null,
    flowName: null,
    status: null,
  },
  rules: {
    equipmentId: [
      { required: true, message: "设备id不能为空", trigger: "change" }
    ],
    flowId: [
      { required: true, message: "流程id不能为空", trigger: "change" }
    ],
    x: [
      { required: true, message: "x坐标不能为空", trigger: "blur" }
    ],
    y: [
      { required: true, message: "y坐标不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询设备拓展管理列表 */
function getList() {
  loading.value = true;
  getEquipmentExtensionFormList(queryParams.value).then(response => {
    extensionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    equipmentId: null,
    flowId: null,
    x: null,
    y: null,
    status: "0",
    remark: null,
  };
  proxy.resetForm("extensionRef");
  //下拉框重置
  realFlowOptions.value = flowOptions.value;
  realEquipmentOptions.value = equipmentOptions.value;
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.status == "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '"id为"' + row.id + '"的数据项吗?').then(function () {
    return changeStatus(row.id, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status == "0" ? "1" : "0";
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 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;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备拓展管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getExtension(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备拓展管理";
  });
}

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

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备拓展管理编号为"' + _ids + '"的数据项？').then(function () {
    return delExtension(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

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

getList();

/** 格式化数字 */
function formatNumber(val) {
  if (val == null || val === '') return '';
  const num = Number(val);
  return Number.isInteger(num) ? num : num.toString();
}

</script>
<style lang="scss" scoped>
:deep(.sizeInput){
  .el-input-number .el-input__inner{
    text-align: left;
  }
}
</style>