<template>
  <div class="system-config-area-container layout-padding">
    <div class="layout-padding-auto layout-padding-view pd20">
      <div class="flex-center-between mb20">
        <el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
          <el-form-item label="关键字" prop="keyword" class="mb0">
            <el-input v-model="state.queryParams.keyword" placeholder="区域名称" clearable @keyup.enter="handleQuery" style="width: 250px" />
          </el-form-item>
          <el-form-item class="mb0">
            <el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
            <el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button" :loading="state.loading"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" @click="expand"
          ><SvgIcon
              name="ele-ArrowDownBold"
              style="transition: transform var(--el-transition-duration)"
              :style="state.isExpand ? 'transform: none' : 'transform: rotateZ(180deg)'"
              class="mr5"
          />
            {{ state.isExpand ? '收起' : '展开' }}</el-button
          >
          <el-button type="primary" @click="onOpenAddArea('')" v-auth="'system:config:area:add'"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-auto-resizer class="table" v-loading="state.loading">
        <template #default="{ height, width }">
          <el-table-v2
              v-model:expanded-row-keys="state.expandedRowKeys"
              :columns="state.columns"
              :data="state.orgTableData"
              expand-column-key="areaName"
              fixed
              :width="width"
              :height="height"
          >
            <template #empty>
              <Empty />
            </template>
          </el-table-v2>
        </template>
      </el-auto-resizer>
    </div>
    <area-add ref="areaAddRef" @updateList="queryList" />
    <area-edit ref="areaEditRef" @updateList="queryList" />
  </div>
</template>
<script lang="ts" setup name="systemConfigArea">
import { defineAsyncComponent, ref, h, reactive, onMounted, watch } from 'vue';
import {ElButton, ElMessage, ElMessageBox} from 'element-plus';
import type { FormInstance } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { auth } from '/@/utils/authFunction';
import { throttle } from '/@/utils/tools';
import other from '/@/utils/other';
import {treeArea,treeAreaDelete} from '/@/api/system/area';
// 引入组件
const AreaAdd = defineAsyncComponent(() => import('/@/views/system/config/area/component/Area-add.vue'));  // 新增区域
const AreaEdit = defineAsyncComponent(() => import('/@/views/system/config/area/component/Area-edit.vue'));  // 编辑区域

// 定义变量内容
const state = reactive({
  orgTableData: <EmptyArrayType>[], // 获取所有菜单
  staticArr: <EmptyArrayType>[],  // 静态数据
  loading: false, // 加载状态
  queryParams: {
    keyword: '',  // 关键字
  },
  expandedRowKeys: <EmptyArrayType>[],  // 展开行
  columns: [
    {
      key: 'areaName',
      dataKey: 'areaName',
      title: '区域名称',
      width: 600,
    },
    {
      key: 'id',
      dataKey: 'id',
      title: '区域代码',
      width: 400,
    },
    {
      key: 'creationTime',
      dataKey: 'creationTime',
      title: '创建时间',
      width: 200,
      cellRenderer: (data: any) => h('span', {}, { default: () => formatDate(new Date(data.rowData.creationTime), 'YYYY-mm-dd HH:MM:SS') }),
    },
    {
      key: 'handle',
      title: '操作',
      width: 100,
      fixed: 'right',
      align: 'center',
      cellRenderer: ({ rowData }: any) => {
        return h('span', { class: 'flex' }, [
          (auth('system:config:area:edit') && rowData.isCanModify)
              ? h(
                  ElButton,
                  {
                    onClick: () => onOpenEditArea(rowData),
                    type: 'primary',
                    title: '修改',
                    link: true,
                  },
                  { default: () => '修改' }
              )
              : '',
          (auth('system:config:area:delete') && rowData.isCanModify)
              ? h(
                  ElButton,
                  {
                    onClick: () => onDelArea(rowData),
                    type: 'danger',
                    title: '删除',
                    link: true,
                  },
                  { default: () => '删除' }
              )
              : '',
        ]);
      },
    },
  ],
  isExpand: false, // 是否展开
});
const ruleFormRef = ref<RefType>(); // 搜索表单ref
// 搜索
const formatTable = (list: any[], keyword: string) => {
  if (!list.length || !Array.isArray(list)) return [];
  let emptyArr: any[] = [];
  list.map((item) => {
    if (item.areaName.includes(keyword)) {
      if (item.children && Array.isArray(item.children) && item.children.length > 0) {
        item.children = formatTable(item.children, keyword);
      }
      emptyArr.push(item);
    } else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      item.children = formatTable(item.children, keyword);
      if (item.children.length) {
        emptyArr.push(item);
      }
    }
  });
  return emptyArr;
};
let emptyArr: any[] = [];
const getExpand = (list: any[]) => {
  if (!list.length || !Array.isArray(list)) return [];
  list.map((item) => {
    if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      getExpand(item.children);
    }
    emptyArr.push(item.id);
  });
  return emptyArr;
};
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
  if (state.queryParams.keyword) {
    state.loading = true;
    state.expandedRowKeys = [];
    emptyArr = [];
    state.orgTableData = formatTable(other.deepClone(state.staticArr), state.queryParams.keyword);
    state.expandedRowKeys = getExpand(state.orgTableData);
    state.loading = false;
  } else {
    queryList();
  }
}, 300);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  queryList();
  state.expandedRowKeys = [];
  emptyArr = [];
}, 300);
// 打开新增弹窗
const areaAddRef = ref<RefType>(); // 新增组织机构ref
const onOpenAddArea = (row?: any) => {
  areaAddRef.value.openDialog(state.orgTableData, row);
};
// 打开编辑弹窗
const areaEditRef = ref<RefType>();  // 编辑组织机构ref
const onOpenEditArea = (row: any) => {
  areaEditRef.value.openDialog(row, state.orgTableData);
};
const expand = () => {
  state.isExpand = !state.isExpand;
};
watch(
    () => state.isExpand,
    (old: Boolean) => {
      if (old) getAllIds(state.orgTableData);
      else state.expandedRowKeys = [];
    }
);
const getAllIds = (arr: any) => {
  if (!arr) return [];
  arr.forEach((v: any) => {
    if (v.children?.length) {
      getAllIds(v.children);
      state.expandedRowKeys.push(v.id);
    }
  });
};
// 删除当前行
const onDelArea = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除次区域：${row.areaName}, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
    treeAreaDelete(row.id).then(() => {
			ElMessage.success('删除成功');
      queryList();
		})
	}).catch(() => { });
};
// 获取所有部门结构
const queryList = async () => {
  if (!auth('system:config:area:query')) ElMessage.error('抱歉，您没有权限获区域列表！');
  else {
    state.loading = true;
    try {
      const res: any = await Promise.all([treeArea()]);
      state.orgTableData = res[0].result ?? [];
      state.staticArr = res[0].result ?? [];
      state.loading = false;
    } catch (error) {
      console.log(error)
      state.loading = false;
    }
  }
};
// 页面加载时
onMounted(() => {
  queryList();
});
</script>
<style lang="scss" scoped>
.system-config-area-container{
  .table {
    flex: 1;
  }
}
</style>
