<template>
    <div>
        <el-affix :offset="20" style="width:100%" v-loading="loading">
            <div class="head-container">
                <el-input v-model="impaNotes" placeholder="请输入备件类型" clearable prefix-icon="Search"
                    style="margin-bottom: 20px" />
            </div>
            <el-row :gutter="10" class="mb8" style="min-height:32px" v-hasPermi="['impa:impa:add']">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAddIMPA">新增
                    </el-button>
                </el-col>
            </el-row>
            <div class="head-container">
                <el-scrollbar height="620px" class="solid radius">
                    <el-tree :data="impaList" :props="{ label: 'label', children: 'children' }"
                        :expand-on-click-node="false" :filter-node-method="filterNode" ref="impaTreeRef"
                        default-expand-all @node-click="handleIMPANodeClick">
                        <template #default="{ node, data }">
                            <span class="impa-tree-node"
                                :class="{ active: data.impaCode == queryParams.impaCode }">
                                <div class="left">
                                    <el-tooltip :content="`${data.impaCode} - ${data.label} \n${data.remark}`" placement="bottom">
                                        <div>
                                          <div>{{ data.impaCode }} - {{ data.label }}</div>
                                          <div class="text-sm text-gray">{{ data.remark }}</div>
                                        </div>
                                        <template #content>
                                          <div>{{ data.impaCode }} - {{ data.label }}</div>
                                          <div>{{ data.remark }}</div>
                                        </template>
                                    </el-tooltip>
                                </div>
                               <div class="action flex align-center">
                                 <div class="flex align-center" v-hasPermi="['impa:impa:edit']">
                                   <el-icon @click.stop="handleUpdateIMPA(data)">
                                     <Edit color="var(--el-color-primary)" />
                                   </el-icon>
                                 </div>
                                 <div class="flex align-center" v-hasPermi="['impa:impa:remove']">
                                   <el-icon @click.stop="handleRemoveIMPA(node, data)" color="var(--el-color-danger)"
                                     class="margin-left-xs">
                                     <Delete />
                                   </el-icon>
                                 </div>
                               </div>
                            </span>
                        </template>
                    </el-tree>
                </el-scrollbar>
            </div>
        </el-affix>

       <!-- 添加或修改物料管理-物料目录对话框 -->
       <el-dialog :title="title" v-model="openIMPACatalog" width="500px" append-to-body>
         <el-form ref="impaRef" :model="impaForm" :rules="rules" label-width="80px">
           <el-form-item label="编号" prop="impaCode">
             <el-input maxlength="100" :disabled="impaForm.id != null" v-model="impaForm.impaCode" placeholder="请输入编号" />
           </el-form-item>
           <el-form-item label="描述" prop="impaNotes">
             <el-input maxlength="100" v-model="impaForm.impaNotes" placeholder="请输入描述" type="textarea" :rows="4" />
           </el-form-item>
           <el-form-item label="备注" prop="remark">
             <el-input maxlength="100" v-model="impaForm.remark" placeholder="请输入备注" type="textarea" :rows="6" />
           </el-form-item>
         </el-form>
         <template #footer>
           <div class="dialog-footer">
             <el-button type="primary" @click="submitIMPAForm">确 定</el-button>
             <el-button @click="cancel">取 消</el-button>
           </div>
         </template>
       </el-dialog>
    </div>
</template>

<script setup name="MaintenanceSidebar">
import {
  listImpa,
  getImpa,
  delImpa,
  addImpa,
  updateImpa,
} from "@/api/impa/impa";

const { proxy } = getCurrentInstance();
const emit = defineEmits();

const props = defineProps({
    modelValue: [String, Number],
});
const { modelValue } = toRefs(props);

const openIMPACatalog = ref(false);
const impaNotes = ref("");
const impaList = ref(undefined);
const title = ref("");
const loading = ref(false)
const data = reactive({
    impaForm: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10
    },
    rules: {
       impaCode: [
         {
           required: true,
           message: "编号不能为空",
           trigger: "blur",
         },
       ],
       impaNotes: [
         {
           required: true,
           message: "描述不能为空",
           trigger: "blur",
         },
       ],
    },
});

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

watch(modelValue, (newValue) => {
    // let array = maintenanceList.value.filter(item => item.maintenanceId == newValue)[0];
    // let name = array ? array.maintenanceName : '';
    queryParams.value.impaCode = newValue;
    // maintenanceName.value = name;
})


const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(impaNotes, (val) => {
    proxy.$refs["impaTreeRef"].filter(val);
});


/** 新增按钮操作 */
function handleAddIMPA() {
    reset();
    title.value = "新增备件类型";
    openIMPACatalog.value = true;
}

/** 查询部门下拉树结构 */
function getTreeselect() {
	loading.value = true;
    listImpa({ pageNum: 1, pageSize: 9999 }).then((response) => {
		response.rows.map((item) => {
			item.label = `${item.impaNotes}`;
		});
		// impaList.value = response.rows.filter((item) => item.status === "0");
		impaList.value = response.rows.sort(
			(a, b) => Number(a.impaCode) - Number(b.impaCode)
		);
		loading.value = false;
		emit("update:impaList", impaList.value);
    });
}

/** 节点单击事件 */
function handleIMPANodeClick(data) {
	if (queryParams.value.impaCode == data.impaCode) {
	    queryParams.value.impaCode = null;
	    // maintenanceName.value = ""
	} else {
	    queryParams.value.impaCode = data.impaCode;
	    // maintenanceName.value = data.maintenanceName
	}
	emit("update:modelValue", queryParams.value.impaCode);
}

/** 修改按钮操作 */
function handleUpdateIMPA(data) {
    impaForm.value = JSON.parse(JSON.stringify(data));
    openIMPACatalog.value = true;
    title.value = "修改备件类型";
}

/** 删除按钮操作 */
function handleRemoveIMPA(node, data) {
    console.log(node, data);
   proxy.$modal
     .confirm(`是否删除【${data.label}】？`)
     .then(() => {
       delImpa(data.id).then(() => {
         getTreeselect();
       });
     })
     .catch(() => { });
}

/** 重置操作表单 */
function reset() {
    impaForm.value = { id: null};
}

/** 提交按钮 */
function submitIMPAForm() {
   proxy.$refs["impaRef"].validate((valid) => {
     console.log(valid);
     if (valid) {
       if (impaForm.value.id != undefined) {
         updateImpa(impaForm.value).then((response) => {
           proxy.$modal.msgSuccess("修改成功");
           openIMPACatalog.value = false;
           getTreeselect();
         });
       } else {
         addImpa(impaForm.value).then((response) => {
           proxy.$modal.msgSuccess("新增成功");
           openIMPACatalog.value = false;
           getTreeselect();
         });
       }
     }
   });
}

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



onActivated(() => {
    // console.log("onActivated")
    getTreeselect();
    // getList();
})
onMounted(() => {
    // console.log("onMounted")
    // getList();
    getTreeselect();
})
</script>

<style lang="scss">
	.el-tree-node__content {
	  height: 46px;
	}
.impa-tree-node {
    width: 90%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    // padding-right: 10px;
    .action {
        display: none;
        margin-right: 10px;
    }

    >.left {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        // margin-right:20px;
        // max-width: 50%;
    }

    &.active {
        background-color: var(--el-tree-node-hover-bg-color);
        color: var(--van-primary-color);
        font-weight: bold;
    }

    &:hover {
        .action {
            display: flex;
        }
    }
}
</style>


