<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
<!--            <el-form-item label="主键标识" prop="deviceBomId">
              <el-input v-model="queryParams.deviceBomId" placeholder="请输入主键标识" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="父级标识" prop="parentId">
              <el-input v-model="queryParams.parentId" placeholder="请输入父级标识" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="设备" prop="machineId">
              <el-input v-model="queryParams.machineId" placeholder="请输入设备" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="BOM数量" prop="bomAmount">
              <el-input v-model="queryParams.bomAmount" placeholder="请输入BOM数量" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="祖级列表" prop="ancestors">
              <el-input v-model="queryParams.ancestors" placeholder="请输入祖级列表" clearable @keyup.enter="handleQuery" />
            </el-form-item>-->
            <el-form-item label="激活标识" prop="activeFlag">
<!--              <el-input v-model="queryParams.activeFlag" placeholder="请输入激活标识" clearable @keyup.enter="handleQuery" />-->
              <el-select v-model="queryParams.activeFlag" placeholder="请选择激活标识" clearable >
                <el-option v-for="dict in active_flag" :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-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['dms:dmsBaseDeviceBom:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="dmsBaseDeviceBomTableRef"
        v-loading="loading"
        :data="dmsBaseDeviceBomList"
        row-key="deviceBomId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
<!--        <el-table-column label="主键" align="center" prop="deviceBomId" />
        <el-table-column label="父级标识" align="center" prop="parentId" />-->
        <el-table-column label="设备" align="center" prop="machineName" />
        <el-table-column label="BOM数量" align="center" prop="bomAmount" />
<!--        <el-table-column label="祖级列表" align="center" prop="ancestors" />-->
        <el-table-column label="激活标识" align="center" prop="activeFlag" >
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag"/>
          </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-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dms:dmsBaseDeviceBom:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['dms:dmsBaseDeviceBom:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dms:dmsBaseDeviceBom:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改设备BOM信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dmsBaseDeviceBomFormRef" :model="form" :rules="rules" label-width="120px">
<!--        <el-form-item label="主键标识" prop="deviceBomId">
          <el-input v-model="form.deviceBomId" placeholder="请输入主键标识" />
        </el-form-item>-->
        <el-form-item label="父级标识" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="dmsBaseDeviceBomOptions"
            :props="{ value: 'deviceBomId', label: 'machineName', children: 'children' }"
            value-key="deviceBomId"
            placeholder="请选择父级标识"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="设备" prop="machineId">
<!--          <el-input v-model="form.machineId" placeholder="请输入设备" />-->
          <el-select v-model="form.machineId" placeholder="请选择设备" clearable filterable>
            <el-option v-for="item in machineOptions"
                       :key="item.machineId"
                       :label="item.machineName"
                       :value="item.machineId" />
          </el-select>
        </el-form-item>
        <el-form-item label="BOM数量" prop="bomAmount">
          <el-input-number v-model="form.bomAmount" :min="0" />
        </el-form-item>
<!--        <el-form-item label="祖级列表" prop="ancestors">
          <el-input v-model="form.ancestors" placeholder="请输入祖级列表" />
        </el-form-item>-->
        <el-form-item label="激活标识" prop="activeFlag">
<!--          <el-input v-model="form.activeFlag" placeholder="请输入激活标识" />-->
          <el-radio-group v-model="form.activeFlag">
            <el-radio
              v-for="dict in active_flag"
              :key="dict.value"
              :value="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DmsBaseDeviceBom" lang="ts">
import { listDmsBaseDeviceBom, getDmsBaseDeviceBom, delDmsBaseDeviceBom, addDmsBaseDeviceBom, updateDmsBaseDeviceBom } from "@/api/dms/dmsBaseDeviceBom";
import { DmsBaseDeviceBomVO, DmsBaseDeviceBomQuery, DmsBaseDeviceBomForm } from '@/api/dms/dmsBaseDeviceBom/types';
import { getDmsBaseMachineInfoList } from "@/api/dms/dmsBaseMachineInfo";


type DmsBaseDeviceBomOption = {
  deviceBomId: number;
  machineName: string;
  children?: DmsBaseDeviceBomOption[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { active_flag } = toRefs<any>(proxy?.useDict('active_flag'));

const dmsBaseDeviceBomList = ref<DmsBaseDeviceBomVO[]>([]);
const dmsBaseDeviceBomOptions = ref<DmsBaseDeviceBomOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const dmsBaseDeviceBomFormRef = ref<ElFormInstance>();
const dmsBaseDeviceBomTableRef = ref<ElTableInstance>()

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});


const initFormData: DmsBaseDeviceBomForm = {
    deviceBomId: undefined,
    parentId: undefined,
    machineId: undefined,
    bomAmount: undefined,
    ancestors: undefined,
    activeFlag: "1",
    remark: undefined,
  machineName: undefined,
}

const data = reactive<PageData<DmsBaseDeviceBomForm, DmsBaseDeviceBomQuery>>({
  form: {...initFormData},
  queryParams: {
    deviceBomId: undefined,
    parentId: undefined,
    machineId: undefined,
    bomAmount: undefined,
    ancestors: undefined,
    activeFlag: undefined,
    machineName: undefined,
    params: {
    }
  },
  rules: {
/*    deviceBomId: [
      { required: false, message: "主键标识不能为空" },
    ],*/
    parentId: [
      { required: false, message: "父级标识不能为空" , trigger: 'change'},
    ],
    machineId: [
      { required: false, message: "设备不能为空" ,trigger: 'change'},
    ],
    activeFlag: [
      { required: false, message: "激活标识不能为空",trigger: 'blur' },
    ],
    bomAmount: [
      { required: false, message: "BOM数量不能为空",trigger: 'blur' },
    ],
  }
});

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

/** 查询设备BOM信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDmsBaseDeviceBom(queryParams.value);
  const data = proxy?.handleTree<DmsBaseDeviceBomVO>(res.data, "deviceBomId", "parentId");
  if (data) {
    dmsBaseDeviceBomList.value = data;
    loading.value = false;
  }
}

/** 查询设备BOM信息下拉树结构 */
const getTreeselect = async () => {
  const res = await listDmsBaseDeviceBom();
  dmsBaseDeviceBomOptions.value = [];
  const data: DmsBaseDeviceBomOption = { deviceBomId: 0, machineName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<DmsBaseDeviceBomOption>(res.data, "deviceBomId", "parentId");
  dmsBaseDeviceBomOptions.value.push(data);
}

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
}

// 表单重置
const reset = () => {
  form.value = {...initFormData}
  dmsBaseDeviceBomFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
const handleAdd = (row?: DmsBaseDeviceBomVO) => {
  reset();
  getTreeselect();
  if (row != null && row.deviceBomId) {
    form.value.parentId = row.deviceBomId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = "添加设备BOM信息";
}

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(dmsBaseDeviceBomList.value, isExpandAll.value)
}

/** 展开/折叠操作 */
const toggleExpandAll = (data: DmsBaseDeviceBomVO[], status: boolean) => {
  data.forEach((item) => {
    dmsBaseDeviceBomTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: DmsBaseDeviceBomVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getDmsBaseDeviceBom(row.deviceBomId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改设备BOM信息";
}

/** 提交按钮 */
const submitForm = () => {
  dmsBaseDeviceBomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.deviceBomId) {
        await updateDmsBaseDeviceBom(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addDmsBaseDeviceBom(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row: DmsBaseDeviceBomVO) => {
  await proxy?.$modal.confirm('是否确认删除设备BOM信息编号为"' + row.deviceBomId + '"的数据项？');
  loading.value = true;
  await delDmsBaseDeviceBom(row.deviceBomId).finally(() => loading.value = false);
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
}

// 获取设备下拉框数据
let machineOptions = ref<any[]>([]);
const getMachineOptions = async () => {
  const res = await getDmsBaseMachineInfoList(null);
  machineOptions.value = res.data;
}

onMounted(() => {
  getMachineOptions();
  getList();
});
</script>
