<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" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">区域与站点管理</span>
          </div>
          <div class="header-right">
            <el-button type="primary" icon="Plus" @click="handleAdd()" v-hasPermi="['system:areaStation:addCity']">新增城市</el-button>
          </div>
        </div>
      </template>

      <el-table ref="areaStationTableRef" v-loading="loading" :data="areaStationList" row-key="id" 
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        style="width: 100%" :header-cell-style="{ background: '#f8f9fb', color: '#606266' }">
        <el-table-column label="名称" prop="name" width="280" />
        <el-table-column label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getTypeStyle(scope.row.type)" effect="light" size="small">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="编码" prop="code" width="150" align="center" />
        <el-table-column label="详细地址 (站点)" prop="address" min-width="240" />
        <el-table-column label="负责人" prop="leaderName" width="120" align="center" />
        <el-table-column label="联系电话" prop="contactPhone" width="150" align="center" />
        <el-table-column label="操作" width="220" align="right" fixed="right">
          <template #default="scope">
            <div class="op-btns">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:areaStation:edit']">编辑</el-button>
              <el-button v-if="scope.row.type === 0" link type="success" @click="handleAdd(scope.row)" v-hasPermi="['system:areaStation:addArea']">新增区域</el-button>
              <el-button v-if="scope.row.type === 1" link type="success" @click="handleAdd(scope.row)" v-hasPermi="['system:areaStation:addStation']">新增站点</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['system:areaStation:remove']">删除</el-button>
            </div>
          </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 v-if="false" label="区域类型" prop="type">
          <el-radio-group v-model="form.type" :disabled="!!form.id">
            <el-radio v-for="type in filteredTypeList" :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 filteredTypeList = ref<SysAreaStationTypeVo[]>([]);

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();
  let typeLabel = '';
  if (row != null && row.id) {
    form.value.parentId = row.id;
    if (row.type === 0) {
      // 城市底下新增区域
      form.value.type = 1;
      typeLabel = '区域';
    } else if (row.type === 1) {
      // 区域底下新增站点
      form.value.type = 2;
      typeLabel = '站点';
    }
  } else {
    // 头部操作新增城市
    form.value.parentId = 0;
    form.value.type = 0;
    typeLabel = '城市';
  }
  dialog.visible = true;
  dialog.title = `新增${typeLabel}`;
};

/** 展开/折叠操作 */
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();
  // 修改时只能查看当前类型，不能切换
  filteredTypeList.value = typeList.value.filter((item) => item.value === row.type);
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getAreaStation(row.id as number);
  Object.assign(form.value, res.data);
  const typeLabel = getTypeLabel(form.value.type);
  dialog.visible = true;
  dialog.title = `修改${typeLabel}`;
};

/** 提交按钮 */
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>

<style scoped lang="scss">
.p-2 {
  padding: 20px;
  background-color: #f5f7f9;
  min-height: 100vh;
}

.table-card {
  border: none;
  border-radius: 8px;
  
  :deep(.el-card__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.header-right {
  display: flex;
  gap: 12px;
}

.op-btns {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  .el-button {
    font-weight: 400;
    padding: 0;
    
    &.el-button--primary { color: #409eff; }
    &.el-button--success { color: #67c23a; }
    &.el-button--danger { color: #f56c6c; }
  }
}

:deep(.el-table) {
  --el-table-border-color: #f0f0f0;
  
  th.el-table__cell {
    font-weight: 600;
  }

  .el-tag {
    border: none;
  }
}
</style>
