<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 { compact } from 'lodash';
import { GetEntityList, AddEntity, UpdateEntity, DeleteEntity, ExportEntity } from '@/apis/resource/grid';

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: [],
  options: {
    ...CRUD_OPTIONS,
    // addBtnText: '添加网格',
    column: [
      {
        label: '网格区',
        prop: 'gridArea',
        search: true,
        width: 200,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '网格名称',
        prop: 'gridName',
        search: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '网格区域',
        prop: 'gridAreaName',
        width: 300,
        display: false,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '网格区域',
        prop: 'cities',
        type: 'cascader',
        hide: true,
        addDisplay: true,
        editDisplay: true,
        viewDisplay: false,
        // multiple: true,
        // checkStrictly: true,
        // collapseTags: true,
        // emitPath: false,
        // checkDescendants: false,
        props: {
          label: 'areaName',
          value: 'areaCode',
          children: 'areaChildVOS',
        },
        dicUrl: `${VITE_APP_BASE_API}/system/area/region?areaCode=530000`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res.data ?? [],
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '网格管理员',
        prop: 'gridManager',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '联系方式',
        prop: 'contactInfo',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '省',
        prop: 'provinceCode',
        hide: true,
        display: false,
      },
      {
        label: '市',
        prop: 'cityCode',
        hide: true,
        display: false,
      },
      {
        label: '县/区',
        prop: 'gridAreaCode',
        hide: true,
        display: false,
      },
      {
        label: '乡镇',
        prop: 'townCode',
        hide: true,
        display: false,
      },
      {
        label: '乡镇',
        prop: 'village',
        hide: true,
        display: false,
      },
      {
        label: '备注',
        prop: 'note',
        type: 'textarea',
        span: 24,
        rows: 4,
        overHidden: true,
        width: 200,
      },
      {
        label: '创建时间',
        prop: 'createTime',
        width: 200,
        hide: true,
        display: false,
      },
    ],
    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;
  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;
    });
};

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

const setCity = (row) => {
  if (!isEmpty(row.cities)) {
    row.provinceCode = row?.cities[0] ?? null;
    row.cityCode = row?.cities[1] ?? null;
    row.gridAreaCode = row?.cities[2] ?? null;
    row.townCode = row?.cities[3] ?? null;
    row.village = row?.cities[4] ?? null;
    // row.village = row?.cities.join(',');
  }
};

// 新增
const rowSave = (row, done, loading) => {
  setCity(row);
  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) => {
  const village = !isEmpty(row.village) ? row.village : [];
  row.cities = compact([row.provinceCode, row.cityCode, row.gridAreaCode ?? '', row.townCode ?? '', ...village]);
  crudRef.value.rowEdit(row);
};
const rowUpdate = (row, index, done, loading) => {
  setCity(row);
  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.id })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};

// 导出
const onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;
  const fileName = '网格明细表';
  ExportEntity(state.query)
    .then((res) => {
      if (res.status === 200) {
        downloadFile(res.data, `${fileName}.xlsx`, 'blob');
        app.$message.success('导出成功！');
      }
    })
    .catch((err) => {
      app.$message.error('导出失败！');
    })
    .finally(() => {
      state.loading = false;
    });
};
</script>
