<template>
  <div class="custom-page">
    <el-row :gutter="20">
      <splitpanes class="default-theme">
        <!-- <pane size="16">
          <el-col>
            <custom-table-tree title="土地用途分类信息" :data="treeData" :option="treeOption" filter @node-click="handleNodeClick">
              <template #default="{ data }">
                <div :class="{ 'text-primary': data.id == treeSelected.id || data.id == treeSelected.pId }">
                  {{ data.landType }}
                </div>
              </template>
            </custom-table-tree>
          </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"
              @row-save="rowSave"
              @row-update="rowUpdate"
            >
              <template #icon="{ row }">
                <i :class="row.icon" style="font-size: 24px"></i>
              </template>
              <!-- <template #icon="{ row }">
                <i :class="row.icon" style="font-size: 24px"></i>
              </template>
              <template #menu="{ row, size }">
                <el-button :size="size" text type="primary" @click="handleAdd(row)">新增子级</el-button>
              </template> -->
              <template #menu-left>
                <el-button type="success" icon="download" @click="onExport">导出</el-button>
              </template>

              <template #status="{ row }">
                <el-tag v-if="row.status == 1" type="success">启用</el-tag>
                <el-tag v-if="row.status == 0" type="danger">禁用</el-tag>
              </template>

              <template #menu="scope">
                <custom-table-operate :actions="state.options.actions" :data="scope" />
              </template>
            </avue-crud>
            <!-- <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"
              @row-save="rowSave"
              @row-update="rowUpdate"
            >
              <template #menu-left>
                <el-button type="success" icon="download" @click="onExport">导出</el-button>
              </template>

              <template #status="{ row }">
                <el-tag v-if="row.status == 1" type="success">启用</el-tag>
                <el-tag v-if="row.status == 0" type="danger">禁用</el-tag>
              </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, nextTick, watch } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { getLandTypeTree, landTypeSave, getLandType, exportLandType, delLandType, editLandType } from '@/apis/baseInfo';
import { useUserStore } from '@/store/modules/user';
import { isEmpty, getParentIds, flattenTree, setDicLabel, downloadFile } from '@/utils';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();
const crudRef = ref(null);
const treeData = ref([]);
const treeOption = ref({
  nodeKey: 'id',
  props: { children: 'children', label: 'landType', id: 'id' },
});
const treeSelected = ref({});
const treeDicData = ref([]);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {
    status: 1,
  },
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    headerAlign: 'center',
    align: 'center',
    border: true,
    index: true,
    rowKey: 'id',
    rowParentKey: 'pid',
    dialogWidth: 600,
    selection: false,
    column: [
      // { label: '编号', prop: 'id', addDisplay: false, editDisplay: false },
      {
        label: '分类名称',
        prop: 'landType',
        span: 24,
        rules: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
      },
      {
        label: '用途分类',
        prop: 'pid',
        display: false,
        render: ({ row }) => {
          return setDicLabel(treeDicData.value, row.pid);
        },
      },
      {
        label: '用途分类',
        prop: 'pids',
        type: 'cascader',
        checkStrictly: true,
        hide: true,
        addDisplay: true,
        editDisplay: true,
        viewDisplay: false,
        props: {
          label: 'landType',
          value: 'id',
          children: 'children',
        },
        dicUrl: `${VITE_APP_BASE_API}/land-resource/baseInfo/landTree`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => [{ id: '0', landType: '土地分类', children: res.data }],
        span: 24,
        rules: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        dicData: [
          {
            label: '启用',
            value: 1,
          },
          {
            label: '禁用',
            value: 0,
          },
        ],
        value: 1,
        addDisplay: false,
        editDisplay: false,
      },
    ],
    actions: [
      {
        name: ({ row }) => `${row.status == '0' ? '启' : '禁'}用`,
        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: {},
});

watch(
  () => treeData.value,
  (val) => {
    if (!isEmpty(val)) {
      const list = flattenTree(val);
      treeDicData.value = list.map((item) => {
        return { label: item.landType, value: item.id, id: item.id, parentId: item.pid };
      });
    }
  }
);

const getLandTree = async () => {
  try {
    const res = await getLandTypeTree();
    if (res.code == 200) {
      const { current, size, total, records } = res.data;
      treeData.value = [{ id: '0', landType: '土地分类', children: res.data }];
      state.data = treeData.value;
      state.pageData = {
        currentPage: current || 1,
        pageSize: size || 10,
        total: total,
      };
    }
  } catch (err) {
    app.$message.error(err.msg);
  }
};

getLandTree();

const loadData = () => {
  state.loading = true;
  getLandType({
    pid: treeSelected.value?.id ?? '0',
    ...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 handleNodeClick = (data, node) => {
  treeSelected.value = data;
  // loadData();
  getLandTree();
};

onMounted(() => {
  // loadData();
  getLandTree();
});

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

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

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

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

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

// 启用
async function rowStatus(row) {
  const { id } = row;
  let status = row.status == '1' ? '0' : '1';
  let params = {
    id,
    status,
  };
  let res = await editLandType(params);
  if (res.code == 200) {
    app.$message.success('操作成功！');
    nextTick(() => {
      row.status = status;
      // loadData();
      // getLandTree();
    });
  }
}

// 删除
async function rowDel(row, done, loading) {
  let res = await delLandType(row.id);
  if (res.code === 200) {
    app.$message.success('已删除！');
    getLandTree();
    // loadData();
    done();
  }
  loading();
}

const setPid = (row) => {
  if (!isEmpty(row.pids)) {
    const len = row.pids.length;
    row.pid = row?.pids[len - 1] ?? '0';
  }
};

// 新增
const rowSave = async (row, done, loading) => {
  setPid(row);
  landTypeSave(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('添加成功！');
        done();
        getLandTree();
        // loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 编辑
const rowEdit = (row) => {
  row.pids = getParentIds(treeData.value, row.id);
  console.log('pids=', row.pids);
  crudRef.value && crudRef.value.rowEdit(row);
};

const rowUpdate = (row, index, done, loading) => {
  setPid(row);
  editLandType(row).then((res) => {
    if (res.code === 200) {
      app.$message.success('更新成功！');
      // loadData();
      getLandTree();
      done();
    }
  });
  loading();
};

// 导出
const onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('请先选择用地分类!');
    return;
  }
  state.loading = true;
  const fileName = '用地分类.xlsx';
  exportLandType({
    pid: treeSelected.value.id,
  })
    .then((res) => {
      if (res.status === 200) {
        downloadFile(res.data, fileName, 'blob');
        app.$message.success('导出成功！');
      }
    })
    .catch((err) => {
      app.$message.error('导出失败！');
    })
    .finally(() => {
      state.loading = false;
    });
};
</script>
