<template>
  <div class="custom-page">
    <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-save="rowSave"
      @row-update="rowUpdate"
      @row-del="rowDel"
    >
      <template #menu-left>
        <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>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, downloadFile } from '@/utils';
import { useUserStore } from '@/store/modules/user';

// 请根据你的项目路径替换为实际的接口路径
import { GetGridList, GetMemberList, AddMember, UpdateMember, DeleteMember, ExportMember } from '@/apis/resource/member';

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: [],
  gridOptions: [],
  options: {
    ...CRUD_OPTIONS,
    column: [
      {
        label: '网格员姓名',
        prop: 'memberName',
        searchLabelWidth: 100,
        search: true,
        rules: {
          required: true,
          message: '请输入网格员姓名',
          trigger: 'blur',
        },
      },
      {
        label: '所属行政区域',
        prop: 'gridAreaName',
        width: 300,
        searchLabelWidth: 110,
        search: true,
        rules: {
          required: true,
          message: '请输入所属区域',
          trigger: 'blur',
        },
      },
      {
        label: '所属网格',
        prop: 'gridId',
        type: 'select',
        width: 200,
        search: true,
        dicData: [], // 初始为空，将在mounted中填充
        props: {
          label: 'gridName',
          value: 'id',
        },
        rules: {
          required: true,
          message: '请选择所属网格',
          trigger: 'change',
        },
      },
      {
        label: '管理员标识',
        prop: 'adminFlag',
        type: 'radio',
        dicData: [
          { label: '是', value: '1' },
          { label: '否', value: '0' },
        ],
        valueDefault: '0',
        hide: true, // 隐藏字段，如需显示可设置为false
      },
      {
        label: '电话号码',
        prop: 'phone',
        rules: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
        ],
      },
      {
        label: '备注',
        prop: 'note',
        type: 'textarea',
        span: 24,
        rows: 3,
        overHidden: true,
        width: 200,
      },
    ],
    actions: [
      {
        name: '查看',
        icon: 'view',
        event: ({ row }) => rowView(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 loadData = () => {
  state.loading = true;
  GetMemberList(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;
    });
};
loadData();

// 加载网格列表
const loadGridOptions = async () => {
  try {
    const res = await GetGridList(); // 获取足够多的网格数据
    if (res.code === 200) {
      state.options.column.find((item) => item.prop === 'gridId').dicData = res.data.records;
    }
  } catch (error) {
    app.$message.error('获取网格列表失败');
  }
};
loadGridOptions();
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 rowEdit = (row) => {
  crudRef.value.rowEdit(row);
};

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

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

const rowDel = (row, index, done) => {
  if (isEmpty(row)) return;
  app
    .$confirm(`确认删除该网格员吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      DeleteMember(row.id) // 👈 只传 id
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            loadData();
            done?.(); // 若使用 Table 的 inline 操作支持回调
          }
        })
        .catch((err) => app.$message.error(err.msg || '删除失败'));
    })
    .catch(() => {});
};

const onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;

  // 仅发送有效的查询条件
  const { current, size, ...query } = state.query;

  ExportMember(query)
    .then((res) => {
      downloadFile(res, '网格员明细表.xlsx', 'blob');
      app.$message.success('导出成功！');
    })
    .catch(() => app.$message.error('导出失败！'))
    .finally(() => {
      state.loading = false;
    });
};
</script>
