<template>
  <div class="custom-page">
    <el-row :gutter="20">
      <el-col :span="4">
        <custom-table-tree title="种养殖基地分类" :data="treeData" @node-click="onNodeClick" />
      </el-col>
      <el-col :span="20">
        <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="danger" icon="delete" @click="onDel(state.selection)">批量删除</el-button>
          </template>

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

          <template #menu="scope">
            <custom-table-operate :actions="state.options.actions" :data="scope" />
          </template>
        </avue-crud>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useApp } from '@/hooks';
import { useUserStore } from '@/store/modules/user';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, mockData, sleep, setDicData } from '@/utils';
import { getLandsList } from '@/apis/land';

const { VITE_APP_BASE_API, VITE_APP_NAME } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();
const router = useRouter();
const crudRef = ref(null);
const treeData = ref([
  {
    label: '基地分类',
    id: null,
    children: [
      { label: '种植基地', id: '1', children: [], pid: null },
      { label: '养殖基地', id: '2', children: [], pid: null },
    ],
  },
]);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '添加',
    // addBtn: false,
    selection: true,
    column: [
      {
        label: '基地名称',
        prop: 'p1',
        search: true,
        width: 200,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
        overHidden: true,
      },
      {
        label: '基地分类',
        prop: 'type',
        type: 'select',
        dicData: [
          {
            label: '种植基地',
            value: 1,
          },
          {
            label: '养殖基地',
            value: 2,
          },
        ],
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '地块名',
        prop: 'landName',
        width: 200,
        type: 'select',
        props: {
          label: 'landName',
          value: 'id',
        },
        dicUrl: `${VITE_APP_BASE_API}/land-resource/landManage/page?current=1&size=20`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res.data?.records ?? [],
        filterable: true,
        remote: true,
        clearable: true,
        remoteMethod: (val) => remoteLandList(val),
        change: (val) => selectedChange(val),
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
        // addDisplay: true,
        // editDisplay: true,
        // viewDisplay: false,
        // overHidden: true,
      },
      {
        label: '区域位置',
        prop: 'p3',
        width: 200,
        overHidden: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '区域面积',
        prop: 'p4',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        dicData: [
          {
            label: '启用',
            value: 1,
          },
          {
            label: '禁用',
            value: 0,
          },
        ],
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '负责人',
        prop: 'p5',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '联系电话',
        prop: 'p6',
        width: 150,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '创建时间',
        prop: 'createTime',
        width: 150,
        // search: true,
        display: false,
      },
      {
        label: '更新时间',
        prop: 'updateTime',
        width: 150,
        display: false,
      },
    ],
    actions: [
      {
        name: '查看',
        icon: 'view',
        event: ({ row }) => rowView(row),
      },
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      // {
      //   type: 'success',
      //   name: ({ row }) => {
      //     return row.status === 1 ? '禁用' : '启用';
      //   },
      //   icon: ({ row }) => {
      //     return row.status === 1 ? 'turnOff' : 'open';
      //   },
      //   event: ({ row }) => rowStatus(row),
      // },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

const loadData = async () => {
  //state.loading = true;
  // GetEntityList(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;
  //   });

  state.loading = true;
  await sleep(500);
  state.data = mockData(
    {
      p1: '耿马镇一号基地',
      landName: '耿马镇2025001号地块',
      p3: '耿马傣族佤族自治县/耿马镇',
      p4: '1000',
      p5: '张三',
      p6: '13837633838',
      status: 1,
      type: 1,
      createTime: '2025-01-01',
      updateTime: '2025-01-15',
    },
    10
  );
  state.loading = false;
};

loadData();

const onNodeClick = (data) => {
  console.log('onNodeClick', data);
};

// 页数
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 rowView = (row) => {
  crudRef.value.rowView(row);
};

// 启用、禁用
const rowStatus = (row) => {
  console.info('操作状态');
};

// 新增
const onAdd = () => {
  crudRef.value && crudRef.value.rowAdd();
};

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

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

const rowUpdate = (row, index, done, loading) => {
  // UpdateEntity(row)
  //   .then((res) => {
  //     if (res.code === 200) {
  //       app.$message.success('更新成功！');
  //       done();
  //       loadData();
  //     }
  //   })
  //   .catch((err) => {
  //     app.$message.error(err.msg);
  //   })
  //   .finally(() => {
  //     loading();
  //   });
};

// 删除
const onDel = (rows = []) => {
  if (isEmpty(rows)) return;
  const ids = rows.map((item) => item.id);
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      // DeleteEntity({ ids: ids.join(',') })
      //   .then((res) => {
      //     if (res.code === 200) {
      //       app.$message.success('删除成功！');
      //       loadData();
      //     }
      //   })
      //   .catch((err) => {
      //     app.$message.error(err.msg);
      //   });
    })
    .catch(() => {});
};

const rowDel = (row, index, done) => {
  onDel([row]);
};

// 远程搜搜
const remoteLandList = async (val) => {
  if (isEmpty(val)) return;
  const query = { landName: val, current: 1, size: 20 };
  const res = await getLandsList(query);
  if (res.code === 200) {
    setDicData(state.options.column, 'landName', res.data.records);
  }
};

// 选择赋值
const selectedChange = ({ value, item }) => {
  console.log(430, value, item, item.landName, item.address, item.area);
};
</script>
