<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formJobProject"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormJobProject()" @reset="resetFormJobProject">
        <el-form-item label="出国劳务标题">
          <el-input
            class="filter-item"
            v-model="formFilter.jobTitleFilter"
            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.belongTabFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="belongTabFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in belongTabFilterWidgetDropdownList"
              :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.isHotspotFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isHotspotFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isHotspotFilterWidgetDropdownList"
              :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.enableFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="enableFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in enableFilterWidgetDropdownList"
              :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.isUrgentFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isUrgentFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isUrgentFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formJobProjectTable"
      class="page-table"
      :data="formJobProjectTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formJobProjectTableWidgetCurrentPage - 1) * formJobProjectTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formJobProjectTableWidget.onSortChange"
      @refresh="formJobProjectTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formJobProject:formJobProject:addJobProject')"
          @click="onAddJobProjectClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formJobProject:formJobProject:exportJobProject')"
          @click="onExportJobProjectClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formJobProject:formJobProject:importJobProject')"
          :on-change="onImportJobProjectClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formJobProject:formJobProject:importJobProject')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formJobProjectTableWidget.getTableIndex" :width="80" />
      <vxe-column title="出国劳务标题" field="jobTitle" />
      <vxe-column title="所属分类" field="belongTabDictMap.name" />
      <vxe-column title="招聘人数" field="jobPeople" />
      <vxe-column title="工资上限" field="salaryCap" />
      <vxe-column title="工资下限" field="salaryFloor" />
      <vxe-column title="工资单位" field="salaryUnit" />
      <vxe-column title="劳务项目图" min-width="100px">
        <template v-slot="scope">
          <el-image v-for="item in parseUploadData(scope.row.jobUrl, { id: scope.row.id, fieldName: 'jobUrl', asImage: true })"
            :preview-src-list="getPictureList(scope.row.jobUrl, { id: scope.row.id, fieldName: 'jobUrl', 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="isHotspotDictMap.name" />
      <vxe-column title="显示顺序" field="showOrder" />
      <vxe-column title="是否启用" field="enableDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditJobProjectClick(scope.row)"
            :disabled="!checkPermCodeExist('formJobProject:formJobProject:editJobProject')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteJobProjectClick(scope.row)"
            :disabled="!checkPermCodeExist('formJobProject:formJobProject:deleteJobProject')"
          >
            删除
          </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="formJobProjectTableWidgetTotalCount"
            :current-page="formJobProjectTableWidgetCurrentPage"
            :page-size="formJobProjectTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formJobProjectTableWidget.onCurrentPageChange"
            @size-change="formJobProjectTableWidget.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: 'formJobProject',
};
</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 { JobFileData } from '@/api/generated/jobFileController';
import { JobContentData } from '@/api/generated/jobContentController';
import { JobProjectData } from '@/api/generated/jobProjectController';
import { JobFileController, JobContentController, JobProjectController } from '@/api/generated';
import FormEditJobProject from '@/pages/jobProject/formEditJobProject.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({
  // 出国劳务标题
  jobTitleFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 是否急聘
  isUrgentFilter: undefined,
});
const formFilterCopy = reactive({
  // 出国劳务标题
  jobTitleFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 是否急聘
  isUrgentFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormJobProjectTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    jobProjectDtoFilter: {
      jobTitle: formFilter.jobTitleFilter,
      belongTab : formFilter.belongTabFilter,
      isHotspot : formFilter.isHotspotFilter,
      enable : formFilter.enableFilter,
      isUrgent : formFilter.isUrgentFilter
    }
  };
  return new Promise((resolve, reject) => {
    JobProjectController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormJobProjectTableVerify = () => {
  formFilterCopy.jobTitleFilter = formFilter.jobTitleFilter;
  formFilterCopy.belongTabFilter = formFilter.belongTabFilter;
  formFilterCopy.isHotspotFilter = formFilter.isHotspotFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  formFilterCopy.isUrgentFilter = formFilter.isUrgentFilter;
  return true;
};
/**
 * 新建
 */
const onAddJobProjectClick = (row?: JobProjectData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditJobProject, { area: ['1300px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      formJobProjectTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditJobProjectClick = (row?: JobProjectData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', FormEditJobProject, { area: ['1300px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      formJobProjectTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportJobProjectClick = (row?: JobProjectData) => {
  let params: ANY_OBJECT = {
    jobProjectDtoFilter: {
      searchString: formFilter.jobTitleFilter,
      jobTitle: formData.JobProject.jobTitle,
    }
  };

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    JobProjectController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formJobProjectTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formJobProjectTableOptions: TableOptions<JobProjectData> = {
  loadTableData: loadFormJobProjectTableWidgetData,
  verifyTableParameter: loadFormJobProjectTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'createTime',
  ascending: false,
};
// 表格组件表格组件
const formJobProjectTable = ref();
const formJobProjectTableWidget = useTable(formJobProjectTableOptions);
const {
  dataList: formJobProjectTableWidgetDataList,
  currentPage: formJobProjectTableWidgetCurrentPage,
  pageSize: formJobProjectTableWidgetPageSize,
  totalCount: formJobProjectTableWidgetTotalCount,
} = formJobProjectTableWidget;
/**
 * 所属分类下拉数据获取函数
 */
const loadBelongTabFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
      directoryType:2
    };
    DictionaryController.dictDirectoryInfoBytype(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 所属分类配置参数
const belongTabFilterOptions: DropdownOptions<DictData> = {
  loadData: loadBelongTabFilterDropdownList,
  isTree: false,
};
// 所属分类下拉组件
const belongTabFilterWidget = useDropdown(belongTabFilterOptions);
const { dropdownList: belongTabFilterWidgetDropdownList } = belongTabFilterWidget
/**
 * 是否热点下拉数据获取函数
 */
const loadIsHotspotFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Hotspot.getList(),
  });
};
// 是否热点配置参数
const isHotspotFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsHotspotFilterDropdownList,
  isTree: false,
};
// 是否热点下拉组件
const isHotspotFilterWidget = useDropdown(isHotspotFilterOptions);
const { dropdownList: isHotspotFilterWidgetDropdownList } = isHotspotFilterWidget
/**
 * 是否启用下拉数据获取函数
 */
const loadEnableFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 是否启用配置参数
const enableFilterOptions: DropdownOptions<DictData> = {
  loadData: loadEnableFilterDropdownList,
  isTree: false,
};
// 是否启用下拉组件
const enableFilterWidget = useDropdown(enableFilterOptions);
const { dropdownList: enableFilterWidgetDropdownList } = enableFilterWidget
/**
 * 是否急聘下拉数据获取函数
 */
const loadIsUrgentFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'IsUrgent', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 是否急聘配置参数
const isUrgentFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsUrgentFilterDropdownList,
  isTree: false,
};
// 是否急聘下拉组件
const isUrgentFilterWidget = useDropdown(isUrgentFilterOptions);
const { dropdownList: isUrgentFilterWidgetDropdownList } = isUrgentFilterWidget
const refreshFormJobProject = () => {
  // 刷新段落
  formJobProjectTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormJobProject = () => {
  formFilter.jobTitleFilter = undefined;
  formFilterCopy.jobTitleFilter = undefined;
  formFilter.belongTabFilter = undefined;
  formFilterCopy.belongTabFilter = undefined;
  formFilter.isHotspotFilter = undefined;
  formFilterCopy.isHotspotFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  formFilter.isUrgentFilter = undefined;
  formFilterCopy.isUrgentFilter = undefined;
  refreshFormJobProject();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormJobProject();
};
const formInit = () => {
  belongTabFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isHotspotFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isUrgentFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormJobProject();
};

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