<template>
  <div>
    <div v-show="!inspectorEditState.show && !inspectorAddState.show" class="app-container">
      <el-row :gutter="20">
        <el-col :lg="4" :xs="24">
          <el-tree
            ref="deptTreeRef"
            class="mt-2"
            node-key="id"
            :data="deptOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </el-col>
        <el-col :lg="20" :xs="24">
          <transition name="fade">
            <div v-show="showSearch">
              <el-form ref="queryFormRef" :model="queryParams">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item prop="nickName">
                      <el-input v-model="queryParams.nickName" placeholder="请输入巡查人员" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-button type="primary" @click="handleQuery">搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </transition>
          <el-row :gutter="10">
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAdd()">新建</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Top" @click="handleImport()"> 批量导入 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain :disabled="multiple" icon="Delete" @click="handleDelete(selectedRow)"> 删除 </el-button>
            </el-col>
          </el-row>
          <el-table ref="multipleTable" v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="姓名" align="center" prop="nickName" />
            <el-table-column label="联系方式" align="center" prop="phone" />
            <el-table-column label="粤政易组织" align="center" prop="yzy_organization" />
            <el-table-column label="责任区划" align="center" prop="division_responsibility" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-text class="common-btn-text-primary" @click="handleUpdate(scope.row)">编辑</el-text>
                <el-text class="common-btn-text-danger" @click="handleDelete(scope.row)">删除</el-text>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="tableData"
          />
        </el-col>
      </el-row>
    </div>
    <InspectorEdit v-if="inspectorEditState.show" :event-id="inspectorEditState.eventId" @close="handleCancel" />
    <InspectorAdd v-if="inspectorAddState.show" @close="handleCancel" @refresh="fetchUserData" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { deptList, inspectorList, inspectorDelete } from '@/api/inspectionWork/inspector';
import InspectorEdit from './inspectorEdit.vue';
import InspectorAdd from './inspectorAdd.vue';
import { to } from 'await-to-js';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deptOptions = ref([]);
const deptTreeRef = ref(null);
const tableData = ref([]);
const selectedRow = ref<InspectorVO | null>(null);
const initFormData = reactive({
  nickName: '',
  phone: '',
  yzy_organization: '',
  division_responsibility: '',
  id: ''
});
export interface InspectorVO {
  phone: number;
  nickName: string;
  yzy_organization: string;
  division_responsibility: string;
  id: number;
}
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    page: 1,
    pageSize: 10,
    nickName: '',
    deptId: ''
  }
});

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

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const getTreeSelect = async () => {
  const res = await deptList();
  deptOptions.value = res.data; // 直接赋值给 deptOptions
  loading.value = false; // 加载完成后关闭加载提示
};

const fetchUserData = async () => {
  const res = await inspectorList(queryParams.value); // 调用 inspectorList 接口
  tableData.value = res.data.map((item) => ({
    id: item.id,
    nickName: item.nick_name,
    phone: item.phonenumber,
    yzy_organization: item.ancestors_names || '', // 如果 yzy_account 为空，则显示空字符串
    division_responsibility: item.area // 显示责任区划
  }));
  total.value = res.total;
};

// 监听查询参数变化并重新获取数据
watch(queryParams, () => {
  fetchUserData();
});
let inspectorEditState = reactive({
  show: false,
  eventId: ''
});
let inspectorAddState = reactive({
  show: false
});
const handleCancel = () => {
  inspectorEditState.show = false;
  inspectorAddState.show = false;
};
const handleImport = () => {
  // 实现导入逻辑
};

const handleAdd = async () => {
  inspectorAddState.show = true;
};
const handleDelete = async (row) => {
  let id = [];
  if (row) {
    id = [row.id];
  } else {
    id = ids.value;
  }
  const [err] = await to(proxy?.$modal.confirm('是否确认删除选择的数据项？') as any);
  if (!err) {
    await inspectorDelete(id);
    proxy.$modal.msgSuccess('删除成功');
    fetchUserData();
  }
};
const handleUpdate = (row) => {
  if (row) {
    inspectorEditState.eventId = row.id; // 假设eventId是id字段
    inspectorEditState.show = true;
  }
};
const handleQuery = () => {
  queryParams.value.page = 1;
  fetchUserData();
};
/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.deptId = data.id;
  handleQuery();
};
// 重置查询条件
const resetQuery = () => {
  queryParams.value = { page: 1, pageSize: 10, nickName: '', deptId: '' };
  handleQuery();
};
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  selectedRow.value = selection.length === 1 ? selection[0] : null;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

onMounted(async () => {
  await getTreeSelect();
  fetchUserData();
});
</script>
<style scoped>
.mt-2 {
  max-width: 300px; /* 设置最大宽度 */
  max-height: 800px; /* 设置最大高度 */
  overflow-y: auto; /* 如果内容超出高度则显示滚动条 */
}
</style>
