<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="areaName">
              <el-input v-model="queryParams.areaName" placeholder="请输入区域名称" prefix-icon="Search" clearable />
            </el-form-item>
            <el-form-item label="区域类型" prop="areaType">
              <el-select v-model="queryParams.areaType" placeholder="请选择区域类型" clearable>
                <el-option v-for="dict in BUILDAREATYPE" :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-input v-model="queryParams.areaName" placeholder="请输入区域名称" prefix-icon="Search" clearable />
        <el-row :gutter="10" class="mb8 mt4">
          <!-- <el-col :span="1.5">
            <el-button v-hasPermi="['room:ptArea:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</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" :search="false" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="ptAreaTableRef"
        v-loading="loading"
        height="calc(100vh - 17.8rem)"
        :data="ptAreaList"
        row-key="areaId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :expand-row-keys="expandKeys"
        highlight-current-row
        @row-click="rowClick"
      >
        <!-- <el-table-column label="父区域id" align="center" prop="parentId" />
        <el-table-column label="祖级列表" align="center" prop="ancestors" /> -->
        <el-table-column label="区域名称" align="left" prop="areaName" show-overflow-tooltip min-width="150" />
        <el-table-column label="类型" align="left" prop="areaType" show-overflow-tooltip width="70">
          <template #default="scope">
            <dict-tag :options="BUILDAREATYPE" :value="scope.row.areaType" />
          </template>
        </el-table-column>
        <el-table-column label="编码" align="left" prop="areaCode" width="100" show-overflow-tooltip />
        <!-- <el-table-column label="备注" align="left" prop="remark" show-overflow-tooltip /> -->
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" min-width="100">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['room:ptArea:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button v-hasPermi="['room:ptArea:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['room:ptArea:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改建筑物区域对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="ptAreaFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父区域" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="ptAreaOptions"
            :props="{ value: 'areaId', label: 'areaName', children: 'children' }"
            value-key="areaId"
            placeholder="请选择父区域"
            check-strictly
          />
        </el-form-item>
        <!-- <el-form-item label="祖级列表" prop="ancestors">
          <el-input v-model="form.ancestors" placeholder="请输入祖级列表" />
        </el-form-item> -->
        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域类型" prop="areaType">
          <el-select v-model="form.areaType" placeholder="请选择区域类型">
            <el-option v-for="dict in BUILDAREATYPE" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域编码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入区域编码" />
        </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>

<!-- 1.只有楼栋才能添加房间，2.只能有一个学校类型的区域，3.楼层下面不能再新增区域 -->
<script setup name="PtArea" lang="ts">
import { listPtArea, getPtArea, delPtArea, addPtArea, updatePtArea } from '@/api/basics/room/ptArea';
import { PtAreaVO, PtAreaQuery, PtAreaForm, PtAreaOption } from '@/api/basics/room/ptArea/types';

const emit = defineEmits(['getAreaId']);
/* defineProps({
  getAreaId: {
    type: Function,
    default: () => {}
  }
}); */

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { BUILDAREATYPE } = toRefs<any>(proxy?.useDict('BUILDAREATYPE'));

const ptAreaList = ref<PtAreaVO[]>([]);
const ptAreaOptions = ref<PtAreaOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(false);
const isExpandAll = ref(false);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const ptAreaFormRef = ref<ElFormInstance>();
const ptAreaTableRef = ref<ElTableInstance>();

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

const initFormData: PtAreaForm = {
  areaId: undefined,
  parentId: undefined,
  ancestors: undefined,
  areaName: undefined,
  areaType: undefined,
  areaCode: undefined,
  remark: undefined
};

const data = reactive<PageData<PtAreaForm, PtAreaQuery>>({
  form: { ...initFormData },
  queryParams: {
    areaName: undefined,
    areaType: undefined,
    params: {}
  },
  rules: {
    /* areaId: [{ required: true, message: '区域Id,主键不能为空', trigger: 'blur' }], */
    parentId: [{ required: true, message: '父区域不能为空', trigger: 'blur' }],
    /* ancestors: [{ required: true, message: '祖级列表不能为空', trigger: 'blur' }], */
    areaName: [{ required: true, message: '区域名称不能为空', trigger: 'blur' }],
    areaType: [{ required: true, message: '区域类型不能为空', trigger: 'change' }],
    areaCode: [{ required: true, message: '区域编码不能为空', trigger: 'change' }]
  }
});

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

/** 根据名称筛选部门树 */
watch(
  queryParams,
  (newValue, oldValue) => {
    getList();
  },
  { deep: true }
);

watchEffect(
  () => {
    ptAreaList.value?.filter((e) => {
      return e.areaName.indexOf(queryParams.value.areaName) !== -1;
    });
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询建筑物区域列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPtArea(queryParams.value);
  const data = proxy?.handleTree<PtAreaVO>(res.data, 'areaId', 'parentId');
  if (data) {
    ptAreaList.value = data;
    loading.value = false;
  }
};

/** 查询建筑物区域下拉树结构 */
const getTreeselect = async () => {
  const res = await listPtArea();
  ptAreaOptions.value = [];
  // const data: PtAreaOption = { areaId: 0, areaName: '顶级节点', children: [] };
  const data: PtAreaOption[] = proxy?.handleTree<PtAreaOption>(res.data, 'areaId', 'parentId');
  // data.children = proxy?.handleTree<PtAreaOption>(res.data, 'areaId', 'parentId');
  ptAreaOptions.value.push(...data);
};

const rowClick = (row: any, col: any, event: any) => {
  selectedRowId.value = row.areaId;
  emit('getAreaId', row.areaId);
};
const selectedRowId = ref<number>();
const expandKeys = ref<string[]>([]);
/* const tableRowClassName = ({ row, rowIndex }) => {
  console.log('selectedRowId', selectedRowId.value, row.areaId);
  // 假设你有一个data属性来存储被选中行的ID
  if (selectedRowId.value === row.areaId) {
    console.log('dddd', row.areaId);
    return 'selected-row';
  }
  return '';
}; */

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

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

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

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

/** 新增按钮操作 */
const handleAdd = (row?: PtAreaVO) => {
  reset();
  getTreeselect();
  if (row != null && row.areaId) {
    form.value.parentId = row.areaId;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加建筑物区域';
};

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: PtAreaVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getPtArea(row.areaId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改建筑物区域';
};

/** 提交按钮 */
const submitForm = () => {
  ptAreaFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.areaType == '01') {
        // 2.只能有一个学校类型的区域
        proxy?.$modal.alertError('学校区域只能在初始化租户时创建');
        return;
      }
      buttonLoading.value = true;
      if (form.value.areaId) {
        await updatePtArea(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPtArea(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: PtAreaVO) => {
  await proxy?.$modal.confirm('是否确认删除建筑物区域编号为"' + row.areaId + '"的数据项？');
  loading.value = true;
  await delPtArea(row.areaId).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(async () => {
  await getList();
  const first = ptAreaList.value[0];
  expandKeys.value.push('' + first?.areaId);
  // console.log('expandKeys', expandKeys.value);
});
</script>

<style lang="scss" scoped>
.selected-row {
  background-color: b-b-blue; /* 你想要的选中行背景色 */
}
/* 选中某行时的背景色*/
.el-table__body tr.current-row > td {
  color: #28a458;
  background: blue !important;
}
</style>
