<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourUserInfo"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourUserInfo()" @reset="resetFormTourUserInfo">
        <el-form-item label="用户登录名称">
          <el-input
            class="filter-item"
            v-model="formFilter.loginNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input
            class="filter-item"
            v-model="formFilter.showNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            class="filter-item"
            v-model="formFilter.userStatusFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="userStatusFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in userStatusFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户邮箱">
          <el-input
            class="filter-item"
            v-model="formFilter.emailFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="用户手机">
          <el-input
            class="filter-item"
            v-model="formFilter.mobileFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            class="filter-item"
            v-model="formFilter.sexFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="sexFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in sexFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="toueUser"
      class="page-table"
      :data="toueUserWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((toueUserWidgetCurrentPage - 1) * toueUserWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="toueUserWidget.onSortChange"
      @refresh="toueUserWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourUserInfo:formTourUserInfo:addFormTourUserInfo')"
          @click="onAddFormTourUserInfoClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourUserInfo:formTourUserInfo:export')"
          @click="onExportClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formTourUserInfo:formTourUserInfo:import')"
          :on-change="onImportClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formTourUserInfo:formTourUserInfo:import')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="toueUserWidget.getTableIndex" :width="80" />
      <vxe-column title="用户登录名称" field="loginName" />
      <vxe-column title="昵称" field="showName" />
      <vxe-column title="用户头像" min-width="100px">
        <template v-slot="scope">
          <el-image v-for="item in parseUploadData(scope.row.headImageUrl, { userId: scope.row.userId, fieldName: 'headImageUrl', asImage: true })"
            :preview-src-list="getPictureList(scope.row.headImageUrl, { userId: scope.row.userId, fieldName: 'headImageUrl', asImage: true })"
            class="table-cell-image" :key="item.url" :src="item.url" fit="fill">
            <template #error>
              <div class="table-cell-image">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </template>
      </vxe-column>
      <vxe-column title="状态" field="userStatusDictMap.name" />
      <vxe-column title="用户邮箱" field="email" />
      <vxe-column title="用户手机" field="mobile" />
      <vxe-column title="性别" field="sexDictMap.name" />
      <vxe-column title="生日" field="birthday">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.birthday, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditFormTourUserInfoClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourUserInfo:formTourUserInfo:editFormTourUserInfo')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourUserInfo:formTourUserInfo:delete')"
          >
            删除
          </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="toueUserWidgetTotalCount"
            :current-page="toueUserWidgetCurrentPage"
            :page-size="toueUserWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="toueUserWidget.onCurrentPageChange"
            @size-change="toueUserWidget.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: 'formTourUserInfo',
};
</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 { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode } from '@/common/utils';
import { TourUserData } from '@/api/generated/tourUserController';
import { TourUserController } from '@/api/generated';
import FormEditTourUserInfo from '@/pages/tourUserInfo/formEditTourUserInfo.vue';

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({
  // 用户登录名称
  loginNameFilter: undefined,
  // 昵称
  showNameFilter: undefined,
  // 状态
  userStatusFilter: undefined,
  // 用户邮箱
  emailFilter: undefined,
  // 用户手机
  mobileFilter: undefined,
  // 性别
  sexFilter: undefined,
});
const formFilterCopy = reactive({
  // 用户登录名称
  loginNameFilter: undefined,
  // 昵称
  showNameFilter: undefined,
  // 状态
  userStatusFilter: undefined,
  // 用户邮箱
  emailFilter: undefined,
  // 用户手机
  mobileFilter: undefined,
  // 性别
  sexFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadToueUserWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourUserDtoFilter:{
      loginName: formFilter.loginNameFilter,
      showName: formFilter.showNameFilter,
      userStatus: formFilter.userStatusFilter,
      email: formFilter.emailFilter,
      mobile: formFilter.mobileFilter,
      sex: formFilter.sexFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourUserController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadToueUserVerify = () => {
  formFilterCopy.loginNameFilter = formFilter.loginNameFilter;
  formFilterCopy.showNameFilter = formFilter.showNameFilter;
  formFilterCopy.userStatusFilter = formFilter.userStatusFilter;
  formFilterCopy.emailFilter = formFilter.emailFilter;
  formFilterCopy.mobileFilter = formFilter.mobileFilter;
  formFilterCopy.sexFilter = formFilter.sexFilter;
  return true;
};
/**
 * 新建
 */
const onAddFormTourUserInfoClick = (row?: TourUserData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditTourUserInfo, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      toueUserWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditFormTourUserInfoClick = (row?: TourUserData) => {
  let params: ANY_OBJECT = {
    userId: row?.userId,
  };

  Dialog
    .show('编辑', FormEditTourUserInfo, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      toueUserWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportClick = (row?: TourUserData) => {
  let params: ANY_OBJECT = {
    tourUserDtoFilter: {
      loginName: formFilter.loginNameFilter,
      showName: formFilter.showNameFilter,
      userStatus: formFilter.userStatusFilter,
      email: formFilter.emailFilter,
      mobile: formFilter.mobileFilter,
      sex: formFilter.sexFilter,
    }
  };

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

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

  TourUserController.delete(params).then(res => {
    ElMessage.success('删除成功');
    toueUserWidget.refreshTable(false, 1);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const toueUserOptions: TableOptions<TourUserData> = {
  loadTableData: loadToueUserWidgetData,
  verifyTableParameter: loadToueUserVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'updateTime',
  ascending: false,
};
// 表格组件表格组件
const toueUser = ref();
const toueUserWidget = useTable(toueUserOptions);
const {
  dataList: toueUserWidgetDataList,
  currentPage: toueUserWidgetCurrentPage,
  pageSize: toueUserWidgetPageSize,
  totalCount: toueUserWidgetTotalCount,
} = toueUserWidget;
/**
 * 状态下拉数据获取函数
 */
const loadUserStatusFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.SysUserStatus.getList(),
  });
};
// 状态配置参数
const userStatusFilterOptions: DropdownOptions<DictData> = {
  loadData: loadUserStatusFilterDropdownList,
  isTree: false,
};
// 状态下拉组件
const userStatusFilterWidget = useDropdown(userStatusFilterOptions);
const { dropdownList: userStatusFilterWidgetDropdownList } = userStatusFilterWidget
/**
 * 性别下拉数据获取函数
 */
const loadSexFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'UserSex', itemIdType: 'String' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 性别配置参数
const sexFilterOptions: DropdownOptions<DictData> = {
  loadData: loadSexFilterDropdownList,
  isTree: false,
};
// 性别下拉组件
const sexFilterWidget = useDropdown(sexFilterOptions);
const { dropdownList: sexFilterWidgetDropdownList } = sexFilterWidget
const refreshFormTourUserInfo = () => {
  // 刷新段落
  toueUserWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourUserInfo = () => {
  formFilter.loginNameFilter = undefined;
  formFilterCopy.loginNameFilter = undefined;
  formFilter.showNameFilter = undefined;
  formFilterCopy.showNameFilter = undefined;
  formFilter.userStatusFilter = undefined;
  formFilterCopy.userStatusFilter = undefined;
  formFilter.emailFilter = undefined;
  formFilterCopy.emailFilter = undefined;
  formFilter.mobileFilter = undefined;
  formFilterCopy.mobileFilter = undefined;
  formFilter.sexFilter = undefined;
  formFilterCopy.sexFilter = undefined;
  refreshFormTourUserInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourUserInfo();
};
const formInit = () => {
  userStatusFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  sexFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourUserInfo();
};

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