<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourVisaCounselorRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourVisaCounselor()" @reset="resetFormTourVisaCounselor">
        <el-form-item label="顾问电话">
          <el-input
            class="filter-item"
            v-model="formFilter.counselorPhoneFilter"
            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.counselorNameFilter"
            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.indexFlagFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="indexFlagFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in indexFlagFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourVisaCounselorTable"
      class="page-table"
      :data="formTourVisaCounselorTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourVisaCounselorTableWidgetCurrentPage - 1) * formTourVisaCounselorTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourVisaCounselorTableWidget.onSortChange"
      @refresh="formTourVisaCounselorTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddTourVisaCounselorClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportTourVisaCounselorClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportTourVisaCounselorClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourVisaCounselorTableWidget.getTableIndex" :width="80" />
      <vxe-column title="顾问姓名" field="counselorName" />
      <vxe-column title="顾问电话" field="counselorPhone" />
      <vxe-column title="顾问级别" field="levelDictMap.name" />
      <vxe-column title="上班时间" field="start" />
      <vxe-column title="下班时间" field="end" />
      <vxe-column title="首页显示顾问" field="indexFlagDictMap.name" />
      <vxe-column title="顾问头像">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.counselorAvatar, {
                id: scope.row.id,
                fieldName: 'counselorAvatar',
                asImage: true
              })
            "
            type="card"
            direction="horizontal"
            :readonly="true"
          />
        </template>
      </vxe-column>
      <vxe-column title="顾问微信">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.counselorWechat, {
                id: scope.row.id,
                fieldName: 'counselorWechat',
                asImage: true
              })
            "
            type="card"
            direction="horizontal"
            :readonly="true"
          />
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditTourVisaCounselorClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourVisaCounselorClick(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="formTourVisaCounselorTableWidgetTotalCount"
            :current-page="formTourVisaCounselorTableWidgetCurrentPage"
            :page-size="formTourVisaCounselorTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourVisaCounselorTableWidget.onCurrentPageChange"
            @size-change="formTourVisaCounselorTableWidget.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: 'formTourVisaCounselor',
};
</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, stringCase } from '@/common/utils';
import { TourVisaCounselorData } from '@/api/generated/tourVisaCounselorController';
import { TourVisaCounselorController } from '@/api/generated';
import FormEditTourVisaCounselor from '@/pages/tourVisaCounselor/formEditTourVisaCounselor.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({
  // 顾问电话
  counselorPhoneFilter: undefined,
  // 顾问姓名
  counselorNameFilter: undefined,
  // 是否是显示顾问
  indexFlagFilter: undefined,
});
const formFilterCopy = reactive({
  // 顾问电话
  counselorPhoneFilter: undefined,
  // 顾问姓名
  counselorNameFilter: undefined,
  // 是否是显示顾问
  indexFlagFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourVisaCounselorTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourVisaCounselorDtoFilter: {
      counselorPhone: formFilter.counselorPhoneFilter,
      counselorName: formFilter.counselorNameFilter,
      indexFlag: formFilter.indexFlagFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourVisaCounselorController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourVisaCounselorTableVerify = () => {
  formFilterCopy.counselorPhoneFilter = formFilter.counselorPhoneFilter;
  formFilterCopy.counselorNameFilter = formFilter.counselorNameFilter;
  formFilterCopy.indexFlagFilter = formFilter.indexFlagFilter;
  return true;
};
/**
 * 新建
 */
const onAddTourVisaCounselorClick = (row?: TourVisaCounselorData) => {
  let params: ANY_OBJECT = {
  };

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

  Dialog
    .show('编辑', FormEditTourVisaCounselor, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourVisaCounselorTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportTourVisaCounselorClick = (row?: TourVisaCounselorData) => {
  let params: ANY_OBJECT = {
  };

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourVisaCounselorController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourVisaCounselorTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourVisaCounselorTableOptions: TableOptions<TourVisaCounselorData> = {
  loadTableData: loadFormTourVisaCounselorTableWidgetData,
  verifyTableParameter: loadFormTourVisaCounselorTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourVisaCounselorTable = ref();
const formTourVisaCounselorTableWidget = useTable(formTourVisaCounselorTableOptions);
const {
  dataList: formTourVisaCounselorTableWidgetDataList,
  currentPage: formTourVisaCounselorTableWidgetCurrentPage,
  pageSize: formTourVisaCounselorTableWidgetPageSize,
  totalCount: formTourVisaCounselorTableWidgetTotalCount,
} = formTourVisaCounselorTableWidget;
/**
 * 是否是显示顾问下拉数据获取函数
 */
const loadIndexFlagFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.VisaIndexFlag.getList(),
  });
};
// 是否是显示顾问配置参数
const indexFlagFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIndexFlagFilterDropdownList,
  isTree: false,
};
// 是否是显示顾问下拉组件
const indexFlagFilterWidget = useDropdown(indexFlagFilterOptions);
const { dropdownList: indexFlagFilterWidgetDropdownList } = indexFlagFilterWidget
const refreshFormTourVisaCounselor = () => {
  // 刷新段落
  formTourVisaCounselorTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourVisaCounselor = () => {
  formFilter.counselorPhoneFilter = undefined;
  formFilterCopy.counselorPhoneFilter = undefined;
  formFilter.counselorNameFilter = undefined;
  formFilterCopy.counselorNameFilter = undefined;
  formFilter.indexFlagFilter = undefined;
  formFilterCopy.indexFlagFilter = undefined;
  refreshFormTourVisaCounselor();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourVisaCounselor();
};
const formInit = () => {
  indexFlagFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourVisaCounselor();
};

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