<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="请输入地区名称" clearable @keyup.enter="handleQuery" />
            </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="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:addressarea:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        ref="areaTableRef"
        v-loading="loading"
        :data="addressareaList"
        row-key="id"
        border
        lazy
        :load="loadChildren"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="areaName" label="地区名称"></el-table-column>
        <el-table-column prop="areaCode" align="center" label="地区编码"></el-table-column>
        <el-table-column prop="level" align="center" label="地区等级">
          <template #default="scope">
            <el-tag v-if="scope.row.level === 1" type="success">省</el-tag>
            <el-tag v-else-if="scope.row.level === 2" type="warning">市</el-tag>
            <el-tag v-else-if="scope.row.level === 3">区/县</el-tag>
            <el-tag v-else type="info">{{ scope.row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="simpleName" align="center" label="简称"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"> </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="280">
          <template #default="scope">
            <el-button v-hasPermi="['system:addressarea:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button v-hasPermi="['system:addressarea:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
            <el-button v-hasPermi="['system:addressarea:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="600px">
      <el-form ref="addressareaFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col v-if="form.parentId !== 0" :span="24">
            <el-form-item label="上级地区" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="areaOptions"
                :props="{ value: 'id', label: 'areaName', children: 'children' } as any"
                value-key="id"
                placeholder="选择上级地区"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区名称" prop="areaName">
              <el-input v-model="form.areaName" placeholder="请输入地区名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区编码" prop="areaCode">
              <el-input v-model="form.areaCode" placeholder="请输入地区编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区等级" prop="level">
              <el-select v-model="form.level" placeholder="请选择地区等级" style="width: 100%">
                <el-option label="省" :value="1" />
                <el-option label="市" :value="2" />
                <el-option label="区/县" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区简称" prop="simpleName">
              <el-input v-model="form.simpleName" placeholder="请输入地区简称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Addressarea" lang="ts">
import { listAddressarea, getAddressarea, delAddressarea, addAddressarea, updateAddressarea } from '@/api/system/addressarea';
import { AddressareaVO, AddressareaQuery, AddressareaForm } from '@/api/system/addressarea/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface AreaOptionsType {
  id: number | string;
  areaName: string;
  children: AreaOptionsType[];
}

const addressareaList = ref<AddressareaVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const areaOptions = ref<AreaOptionsType[]>([]);
const isExpandAll = ref(true);

const areaTableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();
const addressareaFormRef = ref<ElFormInstance>();

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

const initFormData: AddressareaForm = {
  id: undefined,
  areaCode: undefined,
  areaName: undefined,
  parentId: undefined,
  simpleName: undefined,
  level: undefined,
  pinYin: undefined,
  dataSource: undefined
};
const data = reactive<PageData<AddressareaForm, AddressareaQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaName: undefined,
    params: {}
  },
  rules: {
    areaName: [{ required: true, message: '地区名称不能为空', trigger: 'blur' }],
    areaCode: [{ required: true, message: '地区编码不能为空', trigger: 'blur' }],
    level: [{ required: true, message: '地区等级不能为空', trigger: 'blur' }]
  }
});

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

/** 查询地区列表列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAddressarea({ pageNum: 1, pageSize: 10000, areaName: queryParams.value.areaName });
  const level1Data = res.rows
    ?.filter((item) => item.parentId === null || item.parentId === 0)
    .map((item) => ({
      ...item,
      hasChildren: true
    }));
  if (level1Data) {
    addressareaList.value = level1Data;
  }
  loading.value = false;
};

/** 懒加载子节点 */
const loadChildren = async (row: AddressareaVO, treeNode: any, resolve: (data: AddressareaVO[]) => void) => {
  const res = await listAddressarea({ pageNum: 1, pageSize: 10000 });
  const children = res.rows
    ?.filter((item) => item.parentId === row.id)
    .map((item) => ({
      ...item,
      hasChildren: item.level < 3
    }));
  resolve(children || []);
};

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

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

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

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

/** 新增按钮操作 */
const handleAdd = async (row?: AddressareaVO) => {
  reset();
  const res = await listAddressarea({ pageNum: 1, pageSize: 10000 });
  const processedData = res.rows?.map((item) => ({
    ...item,
    parentId: item.parentId === null ? 0 : item.parentId
  }));
  const data = proxy?.handleTree<AreaOptionsType>(processedData, 'id', 'parentId');
  if (data) {
    areaOptions.value = data;
    if (row && row.id) {
      form.value.parentId = row.id as number;
    }
  }
  dialog.visible = true;
  dialog.title = '添加地区';
};

/** 修改按钮操作 */
const handleUpdate = async (row: AddressareaVO) => {
  reset();
  const res = await getAddressarea(row.id);
  form.value = res.data;
  const response = await listAddressarea({ pageNum: 1, pageSize: 10000 });
  const processedData = response.rows?.map((item) => ({
    ...item,
    parentId: item.parentId === null ? 0 : item.parentId
  }));
  const data = proxy?.handleTree<AreaOptionsType>(processedData, 'id', 'parentId');
  if (data) {
    areaOptions.value = data;
  }
  dialog.visible = true;
  dialog.title = '修改地区';
};

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

/** 删除按钮操作 */
const handleDelete = async (row: AddressareaVO) => {
  await proxy?.$modal.confirm('是否确认删除地区"' + row.areaName + '"？');
  await delAddressarea(row.id);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

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