<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>-->
    <!--              <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="['system:areaStation: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="areaStationTableRef" v-loading="loading" :data="areaStationList" row-key="id" border
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="区域名称" prop="name" width="300" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <el-tag :type="getTypeStyle(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="省市编码" align="center" prop="code" width="200" />
        <!--        <el-table-column label="排序权重" align="center" prop="sort" />-->
        <el-table-column label="详细地址" align="center" prop="address" width="400" />
        <el-table-column label="站长姓名" align="center" prop="leaderName" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" />
        <!--        <el-table-column label="经度" align="center" prop="longitude" />-->
        <!--        <el-table-column label="纬度" align="center" prop="latitude" />-->
        <!--        <el-table-column label="状态" align="center" prop="status" width="100" />-->
        <el-table-column label="操作" align="center" fixed="right" 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="['system:areaStation:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                v-hasPermi="['system:areaStation:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:areaStation:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改区域站点对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="areaStationFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio v-for="type in typeList" :key="type.value" :label="type.value">
              <el-tag :type="type.style">
                {{ type.label }}
              </el-tag>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item v-if="form.type === 0 || form.type === 1 || form.type === 2" label="父级ID" prop="parentId">-->
        <!--          <el-tree-select-->
        <!--            v-model="form.parentId"-->
        <!--            :data="areaStationOptions"-->
        <!--            :props="{ value: 'id', label: 'name', children: 'children' }"-->
        <!--            value-key="id"-->
        <!--            placeholder="请选择父级ID"-->
        <!--            check-strictly-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="省市编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入省市编码" />
        </el-form-item>
        <el-form-item v-if="form.type === 2" label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item v-if="form.type === 2" label="联系人" prop="leaderName">
          <el-input v-model="form.leaderName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item v-if="form.type === 2" label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item v-if="form.type === 0 || form.type === 1" label="排序权重" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序权重" />
        </el-form-item>
        <el-form-item v-if="form.type === 0 || form.type === 1" label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item v-if="form.type === 0 || form.type === 1" label="纬度" prop="latitude">
          <el-input v-model="form.latitude" 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="AreaStation" lang="ts">
import { listAreaStation, getAreaStation, delAreaStation, addAreaStation, updateAreaStation, listType } from '@/api/system/areaStation';
import { AreaStationVO, AreaStationQuery, AreaStationForm, SysAreaStationTypeVo } from '@/api/system/areaStation/types';

type AreaStationOption = {
  id: number;
  name: string;
  children?: AreaStationOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const areaStationList = ref<AreaStationVO[]>([]);
const areaStationOptions = ref<AreaStationOption[]>([]);
const typeList = ref<SysAreaStationTypeVo[]>([]); // 区域类型列表
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const areaStationFormRef = ref<ElFormInstance>();
const areaStationTableRef = ref<ElTableInstance>();

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

const initFormData: AreaStationForm = {
  id: undefined,
  name: undefined,
  parentId: undefined,
  code: undefined,
  sort: undefined,
  address: undefined,
  leaderName: undefined,
  contactPhone: undefined,
  longitude: undefined,
  latitude: undefined,
  type: undefined,
  status: undefined
};

const data = reactive<PageData<AreaStationForm, AreaStationQuery>>({
  form: { ...initFormData },
  queryParams: {
    params: {}
  },
  rules: {
    id: [{ required: true, message: '序号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '区域名称不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }]
  }
});

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

/** 查询区域站点列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAreaStation(queryParams.value);
  const data = proxy?.handleTree<AreaStationVO>(res.data, 'id', 'parentId');
  if (data) {
    areaStationList.value = data;
    loading.value = false;
  }
};

/** 查询区域站点下拉树结构 */
const getTreeselect = async () => {
  const res = await listAreaStation();
  areaStationOptions.value = [];
  const data: AreaStationOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<AreaStationOption>(res.data, 'id', 'parentId');
  areaStationOptions.value.push(data);
};

/** 获取区域类型列表 */
const getTypeList = async () => {
  try {
    const res = await listType();
    typeList.value = res.data || res;
  } catch (error) {
    console.error('获取区域类型列表失败:', error);
  }
};

/** 根据类型值获取标签文本 */
const getTypeLabel = (value: any): string => {
  const type = typeList.value.find((item) => item.value === value);
  return type ? type.label : value;
};

/** 根据类型值获取标签样式 */
const getTypeStyle = (value: any): string => {
  const type = typeList.value.find((item) => item.value === value);
  return type ? type.style : 'default';
};

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

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

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

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

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

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: AreaStationVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getAreaStation(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改区域站点';
};

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

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

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