<template>
  <div class="custom-page">
    <el-row :gutter="20">
      <splitpanes class="default-theme">
        <pane size="16">
          <el-col>
            <custom-table-tree title="行政区域" :data="typeTree" :option="treeOption" @node-click="handleNodeClick" />
          </el-col>
        </pane>
        <pane size="84">
          <el-col>
            <avue-crud
              ref="crudRef"
              v-model="state.form"
              v-model:search="state.query"
              v-model:page="state.pageData"
              :table-loading="state.loading"
              :data="state.data"
              :option="state.options"
              @refresh-change="refreshChange"
              @search-reset="searchChange"
              @search-change="searchChange"
              @selection-change="selectionChange"
              @current-change="currentChange"
              @size-change="sizeChange"
              @row-del="rowDel"
            >
              <template #menu-left>
                <el-button type="primary" icon="Plus" @click="onAdd">新增</el-button>
                <el-button type="success" icon="download" @click="onExport">导出</el-button>
              </template>

              <template #menu="scope">
                <custom-table-operate :actions="state.options.actions" :data="scope" />
              </template>
            </avue-crud>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { useUserStore } from '@/store/modules/user';
import { getRegion } from '@/apis/index';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();

const crudRef = ref(null);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '',
    addBtn: false,
    column: [
      { label: '编号', prop: 'gridManager', addDisplay: false, editDisplay: false },
      {
        label: '所属上级',
        prop: 'villageCode',
        type: 'cascader',
        checkStrictly: true,
        props: {
          label: 'areaName',
          value: 'areaCode',
          children: 'areaChildVOS',
        },
        dicUrl: `${VITE_APP_BASE_API}/system/area/region?areaCode=530000`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res.data ?? [],
        rules: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
      },
      { label: '名称', prop: 'gridManager' },
      { label: '状态', prop: 'gridManager', addDisplay: false, editDisplay: false },
    ],
    actions: [
      {
        name: (row) => getStatusButtonText(row.status),
        icon: 'edit',
        event: ({ row }) => rowStatus(row),
      },
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

const typeTree = ref([]);
const treeOption = ref({
  nodeKey: 'areaCode',
  props: { children: 'areaChildVOS', label: 'areaName' },
});
const townOptions = reactive([]);
const infoData = reactive({
  countyId: '',
  townId: '',
  name: '',
});

const loadData = () => {
  //state.loading = true;
  // getAnnualList(state.query)
  //   .then((res) => {
  //     if (res.code === 200) {
  //       const { current, size, total, records } = res.data;
  //       state.data = records;
  //       state.pageData = {
  //         currentPage: current || 1,
  //         pageSize: size || 10,
  //         total: total,
  //       };
  //     }
  //   })
  //   .catch((err) => {
  //     app.$message.error(err.msg);
  //     state.data = [];
  //   })
  //   .finally(() => {
  //     state.loading = false;
  //   });
};

const getTree = () => {
  getRegion().then((res) => {
    if (res.code === 200) {
      const { code, data } = res;
      typeTree.value = data;
      console.info('区域信息', typeTree.value);
    }
  });
};

onMounted(() => {
  getTree();
  loadData();
});

// 页数
const currentChange = (current) => {
  state.query.current = current;
  loadData();
};

// 条数
const sizeChange = (size) => {
  state.query.size = size;
  loadData();
};

// 搜索
const searchChange = (params, done) => {
  if (done) done();
  state.query = params;
  state.query.current = 1;
  loadData();
};

// 刷新
const refreshChange = () => {
  loadData();
  app.$message.success('刷新成功');
};

// 选择
const selectionChange = (rows) => {
  state.selection = rows;
};

const handleNodeClick = (data) => {
  // if (data.level == '2') {
  //   return;
  // }
  // if (data.level == '0') {
  //   infoData.countyId = data.id;
  //   infoData.townId = '';
  // }
  // if (data.level == '1') {
  //   let countys =
  //     typeTree.filter((m) => {
  //       return m.id == data.pId;
  //     }) || [];
  //   let town = countys[0] && countys[0].children ? countys[0].children : [];
  //   townOptions = town;
  //   infoData.townId = data.id;
  //   infoData.countyId = data.pId;
  // }
  // console.info('infoData', infoData);
};
// 编辑
const rowStatus = (row) => {
  console.info('操作状态');
};

const rowDel = (row) => {};

const getStatusButtonText = (status) => {
  switch (status) {
    case 'active':
      return '启用';
    case 'inactive':
      return '禁用';
  }
};

const rowEdit = (row) => {
  crudRef.value && crudRef.value.rowEdit(row);
};

const onAdd = () => {
  // infoVisible.value = true;
  crudRef.value && crudRef.value.rowAdd();
};
const onExport = () => {};
</script>
