<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourFansRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourFans()" @reset="resetFormTourFans">
        <el-form-item label="被关注人">
          <el-select
            class="filter-item"
            v-model="formFilter.attentionIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="attentionIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in attentionIdFilterWidgetDropdownList"
              :key="item.userId"
              :label="item.showName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关注人">
          <el-select
            class="filter-item"
            v-model="formFilter.createUserIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="createUserIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in createUserIdFilterWidgetDropdownList"
              :key="item.userId"
              :label="item.showName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourFansTable"
      class="page-table"
      :data="formTourFansTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourFansTableWidgetCurrentPage - 1) * formTourFansTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourFansTableWidget.onSortChange"
      @refresh="formTourFansTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddTourFansClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportTourFansClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportTourFansClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourFansTableWidget.getTableIndex" :width="80" />
      <vxe-column title="被关注人" field="attentionIdDictMap.name" />
      <vxe-column title="关注人" field="createUserIdDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditTourFansClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourFansClick(scope.row)"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="formTourFansTableWidgetTotalCount"
            :current-page="formTourFansTableWidgetCurrentPage"
            :page-size="formTourFansTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourFansTableWidget.onCurrentPageChange"
            @size-change="formTourFansTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formTourFans',
};
</script>

<script setup lang="ts">
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { TourFansData } from '@/api/generated/tourFansController';
import { TourFansController,TourUserController } from '@/api/generated';
import FormEditTourFans from '@/pages/tourFans/formEditTourFans.vue';
import {TourVisaData} from "@/api/generated/tourVisaController";
import TourUser from "@/types/table/tourUser";

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 被关注人
  attentionIdFilter: undefined,
  // 关注人
  createUserIdFilter: undefined,
});
const formFilterCopy = reactive({
  // 被关注人
  attentionIdFilter: undefined,
  // 关注人
  createUserIdFilter: undefined,
});

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormTourFans();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourFansTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourFansDtoFilter: {
      attentionId: formFilter.attentionIdFilter,
      createUserId: formFilter.createUserIdFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourFansController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourFansTableVerify = () => {
  formFilterCopy.attentionIdFilter = formFilter.attentionIdFilter;
  formFilterCopy.createUserIdFilter = formFilter.createUserIdFilter;
  return true;
};
/**
 * 新建
 */
const onAddTourFansClick = (row?: TourFansData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditTourFans, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourFansTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditTourFansClick = (row?: TourFansData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };
  Dialog
    .show('编辑', FormEditTourFans, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourFansTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportTourFansClick = (row?: TourFansData) => {
  let params: ANY_OBJECT = {
  };

  TourFansController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportTourFansClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  TourFansController.import(params).then(res => {
    ElMessage.success('导入成功');
    formTourFansTableWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeleteTourFansClick = (row?: TourFansData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourFansController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourFansTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourFansTableOptions: TableOptions<TourFansData> = {
  loadTableData: loadFormTourFansTableWidgetData,
  verifyTableParameter: loadFormTourFansTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourFansTable = ref();
const formTourFansTableWidget = useTable(formTourFansTableOptions);
const {
  dataList: formTourFansTableWidgetDataList,
  currentPage: formTourFansTableWidgetCurrentPage,
  pageSize: formTourFansTableWidgetPageSize,
  totalCount: formTourFansTableWidgetTotalCount,
} = formTourFansTableWidget;
/**
 * 被关注人下拉数据获取函数
 */
const loadAttentionIdFilterDropdownList = (): Promise<ListData<TourUser>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    TourUserController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 被关注人配置参数
const attentionIdFilterOptions: DropdownOptions<TourUser> = {
  loadData: loadAttentionIdFilterDropdownList,
  isTree: false,
};
// 被关注人下拉组件
const attentionIdFilterWidget = useDropdown(attentionIdFilterOptions);
const { dropdownList: attentionIdFilterWidgetDropdownList } = attentionIdFilterWidget
/**
 * 关注人下拉数据获取函数
 */
const loadCreateUserIdFilterDropdownList = (): Promise<ListData<TourUser>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    TourUserController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 关注人配置参数
const createUserIdFilterOptions: DropdownOptions<TourUser> = {
  loadData: loadCreateUserIdFilterDropdownList,
  isTree: false,
};
// 关注人下拉组件
const createUserIdFilterWidget = useDropdown(createUserIdFilterOptions);
const { dropdownList: createUserIdFilterWidgetDropdownList } = createUserIdFilterWidget
const refreshFormTourFans = () => {
  // 刷新段落
  formTourFansTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourFans = () => {
  formFilter.attentionIdFilter = undefined;
  formFilterCopy.attentionIdFilter = undefined;
  formFilter.createUserIdFilter = undefined;
  formFilterCopy.createUserIdFilter = undefined;
  refreshFormTourFans();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourFans();
};
const formInit = () => {
  attentionIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  createUserIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourFans();
};

onMounted(() => {
  formInit();
});
</script>
