<template>
  <div class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model="state.form"
      v-model:search="state.query"
      :table-loading="state.loading"
      :data="state.data"
      :option="state.options"
      @refresh-change="refreshChange"
      @search-reset="searchChange"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @row-del="rowDel"
    >
      <template #status="{ row }">
        <el-tag v-if="row.status == 0" type="success">启用</el-tag>
        <el-tag v-if="row.status == 1" type="danger">禁用</el-tag>
      </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, getTree } from '@/utils';
import { useUserStore } from '@/store/modules/user';
import { GetEntityList, AddEntity, UpdateEntity, DeleteEntity } from '@/apis/system/dept';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();
const crudRef = ref(null);
const state = reactive({
  loading: false,
  query: {},
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    rowKey: 'deptId',
    index: false,
    selection: false,
    tree: true,
    defaultExpandAll: true,
    treeProps: { children: 'children', hasChildren: 'hasChildren' },
    column: [
      {
        label: '部门名称',
        prop: 'deptName',
        search: true,
        width: 200,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '上级部门',
        prop: 'parentId',
        type: 'select',
        hide: true,
        props: {
          label: 'deptName',
          value: 'deptId',
        },
        dicUrl: `${VITE_APP_BASE_API}/system/dept/list`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => {
          const data = [{ deptId: 0, deptName: '根目录' }, ...res.data];
          return data;
        },
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        search: true,
        dicData: [
          {
            label: '启用',
            value: '0',
          },
          {
            label: '禁用',
            value: '1',
          },
        ],
        value: '0',
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '排序',
        prop: 'orderNum',
        type: 'number',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '负责人',
        prop: 'leader',
        hide: true,
      },
      {
        label: '联系电话',
        prop: 'phone',
        hide: true,
      },
      {
        label: '邮箱',
        prop: 'email',
        hide: true,
      },
    ],
    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: [],
  minWeek: null,
  maxWeek: null,
  currentRow: {},
});

// 加载
const loadData = () => {
  state.loading = true;
  GetEntityList(state.query)
    .then((res) => {
      if (res.code === 200) {
        state.data = getTree(res.data, 'deptId');
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
      state.data = [];
    })
    .finally(() => {
      state.loading = false;
    });
};

loadData();

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

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

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

// 查看
const rowView = (row) => {
  crudRef.value.rowView(row);
};

// 新增
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.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 rowDel = (row, index, done) => {
  if (isEmpty(row)) return;
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      DeleteEntity({ id: row.deptId })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};
</script>
