<template>
  <CustomCard>
    <div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-tree style="max-width: 600px" :data="typeTree" :props="{ children: 'children', label: 'label' }" @node-click="handleNodeClick" />
        </el-col>
        <el-col :span="18">
          <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>
      </el-row>
    </div>
    <el-dialog v-model="infoVisible" title="新增行政区域信息" width="800" center>
      <div>
        <el-form ref="infoRef" :model="infoData" :rules="infoRules">
          <el-row :gutter="20">
            <el-col v-if="infoData.countyId != ''" :span="12">
              <el-form-item label="县" prop="countyId">
                <el-select
                  v-model="infoData.countyId"
                  placeholder="请选择县"
                  :disabled="true"
                  style="width: 240px"
                  :clearable="true"
                  :multiple="false"
                >
                  <el-option v-for="item in countyOptions" :key="item.id" :label="item.label" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="infoData.townId != ''" :span="12">
              <el-form-item label="镇" prop="townId">
                <el-select v-model="infoData.townId" placeholder="请选择镇" :disabled="true" style="width: 240px" :clearable="true" :multiple="false">
                  <el-option v-for="item in townOptions" :key="item.id" :label="item.label" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称:" prop="name">
                <el-input v-model="infoData.name" placeholder="请输入" style="width: 240px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="infoCancel">取消</el-button>
          <el-button type="primary" @click="subMitInfo(infoRef)"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </CustomCard>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import CustomCard from '@/components/CustomCard.vue';

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

/* --------------- data --------------- */
// #region
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '',
    addBtn: false,
    column: [
      { label: '编号', prop: 'gridManager' },
      { label: '所属区县', prop: 'gridManager' },
      { label: '所属乡镇', prop: 'gridManager' },
      { label: '村名', prop: 'gridManager' },
      { label: '状态', prop: 'gridManager' },
    ],
    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: {},
});

let typeTree = reactive([
  {
    label: '耿马县',
    id: '0',
    level: '0',
    children: [
      {
        label: '镇1',
        level: '1',
        id: '01',
        children: [
          { label: '村1', children: [], id: '0101', pId: '01', level: '2' },
          { label: '村2', children: [], id: '0102', pId: '01', level: '2' },
        ],
        pId: '0',
      },
      { label: '镇2', level: '1', children: [], id: '02', pId: '0' },
    ],
  },
  {
    label: '县1',
    id: '1',
    level: '0',
    children: [{ label: '镇1', children: [], id: '11', pId: '10', level: '1' }],
  },
]);

const infoVisible = ref(false);
const infoRef = ref();
const countyOptions = reactive([
  { label: '耿马县', id: '0' },
  { label: '县1', id: '1' },
]);
let townOptions = reactive([]);

let infoData = reactive({
  countyId: '',
  townId: '',
  name: '',
});

const infoRules = reactive({
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
});

// #endregion

/* --------------- methods --------------- */
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;
  //   });
};

onMounted(() => {
  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;
  }
  // console.info('data', data);
  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 = () => {};

const onAdd = () => {
  infoVisible.value = true;
};
const onExport = () => {};

const subMitInfo = (formEl) => {};

const infoCancel = () => {
  infoHide();
};

const infoHide = () => {
  infoRef.value && infoRef.value.resetFields();
  infoVisible.value = false;
};

// #region

// #endregion
</script>

<style lang="scss" scoped></style>
