<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourVisaRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourVisa()" @reset="resetFormTourVisa">
        <el-form-item label="名称">
          <el-input
            class="filter-item"
            v-model="formFilter.visaTitleFilter"
            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.visaTypeIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="visaTypeIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in visaTypeIdFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="签证国家">
          <el-select
            class="filter-item"
            v-model="formFilter.countryCodeIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="countryCodeIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in countryCodeIdFilterWidgetDropdownList"
              :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.embassyNameFilter"
            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.interviewFlagFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="interviewFlagFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in interviewFlagFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourVisaTable"
      class="page-table"
      :data="formTourVisaTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourVisaTableWidgetCurrentPage - 1) * formTourVisaTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourVisaTableWidget.onSortChange"
      @refresh="formTourVisaTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddTourVisaClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportTourVisaClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportTourVisaClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourVisaTableWidget.getTableIndex" :width="80" />
      <vxe-column title="名称" field="visaTitle" />
      <vxe-column title="签证类型" field="visaTypeIdDictMap.name" />
      <vxe-column title="签证国家" field="countryCodeIdDictMap.name" />
      <vxe-column title="使馆名称" field="embassyName" />
      <vxe-column title="使馆地址" field="embassyAddress" />
      <vxe-column title="是否面签" field="interviewFlagDictMap.name" />
      <vxe-column title="有效期（日）" field="validity" />
      <vxe-column title="停留天数" field="idleDays" />
      <vxe-column title="预计办理天数" field="processingDays" />
      <vxe-column title="预计价格" field="floorPrice" />
      <vxe-column title="受理范围" field="acceptanceRange" />
      <vxe-column title="入境次数" field="entriesNum" />
      <vxe-column title="出签地" field="issueVisaCodeDictMap.name" />
      <vxe-column title="负责顾问" field="counselorIdDictMap.name" />
      <vxe-column title="热门数据" field="hotValueDictMap.name" />
      <vxe-column title="图片">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.img, {
                id: scope.row.id,
                fieldName: 'img',
                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="onListVisaMetarialsListClick(scope.row)"
          >
            签证基础资料管理
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditTourVisaClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourVisaClick(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="formTourVisaTableWidgetTotalCount"
            :current-page="formTourVisaTableWidgetCurrentPage"
            :page-size="formTourVisaTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourVisaTableWidget.onCurrentPageChange"
            @size-change="formTourVisaTableWidget.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: 'formTourVisa',
};
</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 { VisaMetarialsListData } from '@/api/generated/visaMetarialsListController';
import { TourVisaData } from '@/api/generated/tourVisaController';
import { VisaMetarialsListController, TourVisaController } from '@/api/generated';
import FormVisaMetarialsList from '@/pages/tourVisa/formVisaMetarialsList.vue';
import FormEditTourVisa from '@/pages/tourVisa/formEditTourVisa.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({
  // 名称
  visaTitleFilter: undefined,
  // 签证类型
  visaTypeIdFilter: undefined,
  // 签证国家
  countryCodeIdFilter: undefined,
  // 使馆名称
  embassyNameFilter: undefined,
  // 是否面签
  interviewFlagFilter: undefined,
});
const formFilterCopy = reactive({
  // 名称
  visaTitleFilter: undefined,
  // 签证类型
  visaTypeIdFilter: undefined,
  // 签证国家
  countryCodeIdFilter: undefined,
  // 使馆名称
  embassyNameFilter: undefined,
  // 是否面签
  interviewFlagFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourVisaTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourVisaDtoFilter: {
      visaTitle: formFilter.visaTitleFilter,
      visaTypeId: formFilter.visaTypeIdFilter,
      countryCodeId: formFilter.countryCodeIdFilter,
      embassyName: formFilter.embassyNameFilter,
      interviewFlag: formFilter.interviewFlagFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourVisaController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourVisaTableVerify = () => {
  formFilterCopy.visaTitleFilter = formFilter.visaTitleFilter;
  formFilterCopy.visaTypeIdFilter = formFilter.visaTypeIdFilter;
  formFilterCopy.countryCodeIdFilter = formFilter.countryCodeIdFilter;
  formFilterCopy.embassyNameFilter = formFilter.embassyNameFilter;
  formFilterCopy.interviewFlagFilter = formFilter.interviewFlagFilter;
  return true;
};
/**
 * 新建
 */
const onAddTourVisaClick = (row?: TourVisaData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditTourVisa, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourVisaTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 签证基础资料管理
 */
const onListVisaMetarialsListClick = (row?: TourVisaData) => {
  let params: ANY_OBJECT = {
    visaId: row?.id,
  };

  router.push({
    name: 'formVisaMetarialsList',
    query: { ...params, subPage: true }
  });
};
/**
 * 编辑
 */
const onEditTourVisaClick = (row?: TourVisaData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

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

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourVisaController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourVisaTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourVisaTableOptions: TableOptions<TourVisaData> = {
  loadTableData: loadFormTourVisaTableWidgetData,
  verifyTableParameter: loadFormTourVisaTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourVisaTable = ref();
const formTourVisaTableWidget = useTable(formTourVisaTableOptions);
const {
  dataList: formTourVisaTableWidgetDataList,
  currentPage: formTourVisaTableWidgetCurrentPage,
  pageSize: formTourVisaTableWidgetPageSize,
  totalCount: formTourVisaTableWidgetTotalCount,
} = formTourVisaTableWidget;
/**
 * 签证类型下拉数据获取函数
 */
const loadVisaTypeIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourVisaType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 签证类型配置参数
const visaTypeIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadVisaTypeIdFilterDropdownList,
  isTree: false,
};
// 签证类型下拉组件
const visaTypeIdFilterWidget = useDropdown(visaTypeIdFilterOptions);
const { dropdownList: visaTypeIdFilterWidgetDropdownList } = visaTypeIdFilterWidget
/**
 * 签证国家下拉数据获取函数
 */
const loadCountryCodeIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCountryCode(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 签证国家配置参数
const countryCodeIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadCountryCodeIdFilterDropdownList,
  isTree: false,
};
// 签证国家下拉组件
const countryCodeIdFilterWidget = useDropdown(countryCodeIdFilterOptions);
const { dropdownList: countryCodeIdFilterWidgetDropdownList } = countryCodeIdFilterWidget
/**
 * 是否面签下拉数据获取函数
 */
const loadInterviewFlagFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.InterviewFlag.getList(),
  });
};
// 是否面签配置参数
const interviewFlagFilterOptions: DropdownOptions<DictData> = {
  loadData: loadInterviewFlagFilterDropdownList,
  isTree: false,
};
// 是否面签下拉组件
const interviewFlagFilterWidget = useDropdown(interviewFlagFilterOptions);
const { dropdownList: interviewFlagFilterWidgetDropdownList } = interviewFlagFilterWidget
const refreshFormTourVisa = () => {
  // 刷新段落
  formTourVisaTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourVisa = () => {
  formFilter.visaTitleFilter = undefined;
  formFilterCopy.visaTitleFilter = undefined;
  formFilter.visaTypeIdFilter = undefined;
  formFilterCopy.visaTypeIdFilter = undefined;
  formFilter.countryCodeIdFilter = undefined;
  formFilterCopy.countryCodeIdFilter = undefined;
  formFilter.embassyNameFilter = undefined;
  formFilterCopy.embassyNameFilter = undefined;
  formFilter.interviewFlagFilter = undefined;
  formFilterCopy.interviewFlagFilter = undefined;
  refreshFormTourVisa();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourVisa();
};
const formInit = () => {
  visaTypeIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  countryCodeIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  interviewFlagFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourVisa();
};

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