<template>
  <div class="item-select-dlg dialog-box">
    <el-form
      ref="selectJobProjectRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshSelectJobProject()" @reset="resetSelectJobProject">
        <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-cascader
            class="filter-item"
            v-model="belongTabFilterPath"
            :options="belongTabFilterWidgetDropdownList"
            placeholder=""
            :clearable="true"
            :filterable="true"
            :show-all-levels="false"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
            @change="onBelongTabFilterValueChange"
          />
        </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>
        <template #operation>
          <el-button type="primary" @click="onSubmit" :size="layoutStore.defaultFormItemSize">
            确定
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <table-box
      ref="jobProject"
      class="main-box"
      :data="jobProjectWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((jobProjectWidgetCurrentPage - 1) * jobProjectWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
      @sort-change="jobProjectWidget.onSortChange"
      @refresh="jobProjectWidget.refreshTable()"
      @radio-select-change="onSelectChange"
    >
      <vxe-column title="" type="radio" align="center" :width="80" />
      <vxe-column title="出国劳务标题" field="jobTitle" />
      <vxe-column title="标签" field="jobLabel" />
      <vxe-column title="所属分类" field="belongTabDictMap.name" />
      <vxe-column title="工资上限" field="salaryCap" />
      <vxe-column title="工资下限" field="salaryFloor" />
      <vxe-column title="工资单位" field="salaryUnit" />
      <vxe-column title="是否急聘" field="isUrgentDictMap.name" />
      <vxe-column title="是否热点" field="isHotspotDictMap.name" />
      <vxe-column title="是否启用" field="enableDictMap.name" />
      <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="jobProjectWidgetTotalCount"
            :current-page="jobProjectWidgetCurrentPage"
            :page-size="jobProjectWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="jobProjectWidget.onCurrentPageChange"
            @size-change="jobProjectWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

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

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
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';

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 pps = withDefaults(
  defineProps<{
    modelValue: JobProjectData[];
    subPage?: number | string | boolean;
    props: {
      label: string;
      value: string;
    };
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    modelValue: () => [],
    props: () => {
      return {
        label: 'name',
        value: 'id',
      };
    },
    dialog: undefined,
  },
);
// 选中数据
const dialogSelectItems = ref<JobProjectData>();
const formFilter = reactive({
  // 出国劳务标题
  jobTitleFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});
const formFilterCopy = reactive({
  // 出国劳务标题
  jobTitleFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});

const onCancel = () => {
  if (pps.dialog) {
    pps.dialog.cancel();
  }
};

const onSubmit = () => {
  if (pps.dialog) {
    pps.dialog.submit(dialogSelectItems.value);
  }
};

/**
 * 重置过滤值
 */
const resetSelectJobProject = () => {
  formFilter.jobTitleFilter = undefined;
  formFilterCopy.jobTitleFilter = undefined;
  formFilter.belongTabFilter = undefined;
  formFilterCopy.belongTabFilter = undefined;
  belongTabFilterPath.value = [];
  formFilter.isHotspotFilter = undefined;
  formFilterCopy.isHotspotFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  refreshSelectJobProject();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetSelectJobProject();
};
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadJobProjectWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    jobProjectDtoFilter: {
      jobTitle: formFilter.jobTitleFilter,
      belongTab: formFilter.belongTabFilter,
      isHotspot: formFilter.isHotspotFilter,
      enable: formFilter.enableFilter,
    }
  };
  return new Promise((resolve, reject) => {
    JobProjectController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
      nextTick(() => {
        setTableSelectRow();
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadJobProjectVerify = () => {
  formFilterCopy.jobTitleFilter = formFilter.jobTitleFilter;
  formFilterCopy.belongTabFilter = formFilter.belongTabFilter;
  formFilterCopy.isHotspotFilter = formFilter.isHotspotFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  return true;
};
// 表格组件表格组件参数
const jobProjectOptions: TableOptions<JobProjectData> = {
  loadTableData: loadJobProjectWidgetData,
  verifyTableParameter: loadJobProjectVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const jobProject = ref();
const jobProjectWidget = useTable(jobProjectOptions);
const {
  dataList: jobProjectWidgetDataList,
  currentPage: jobProjectWidgetCurrentPage,
  pageSize: jobProjectWidgetPageSize,
  totalCount: jobProjectWidgetTotalCount,
} = jobProjectWidget;
/**
 * 所属分类下拉数据获取函数
 */
const loadBelongTabFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictDirectoryInfo(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 所属分类选中值改变
 */
const onBelongTabFilterValueChange = (value) => {
  formFilter.belongTabFilter = Array.isArray(value) ? value[value.length - 1] : value;
};
// 所属分类配置参数
const belongTabFilterOptions: DropdownOptions<DictData> = {
  loadData: loadBelongTabFilterDropdownList,
  isTree: true,
};
// 所属分类选中数据
const belongTabFilterPath = ref<Array<string | number>>([]);
// 所属分类下拉组件
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 setTableSelectRow = () => {
  if (jobProject.value == null || !Array.isArray(jobProjectWidget.dataList.value))
    return;
  setTimeout(() => {
    let selectRow = findItemFromList(
      jobProjectWidget.dataList.value,
      (dialogSelectItems.value || {})[pps.props.value],
      pps.props.value,
    );
    jobProject.value.getTableImpl().setRadioRow(selectRow);
  }, 50);
};
const refreshSelectJobProject = () => {
  // 重新获取数据组件的数据
  jobProjectWidget.refreshTable();
};
const onSelectChange = (row?: JobProjectData) => {
  dialogSelectItems.value = row;
};

const formInit = () => {
  belongTabFilterWidget.onVisibleChange(true).then(res => {
    // TODO: 获取级联选中路径
    belongTabFilterPath.value = findTreeNodePath(res, formFilter.belongTabFilter);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
  isHotspotFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshSelectJobProject();
};

onMounted(() => {
  if (Array.isArray(pps.modelValue) && pps.modelValue.length > 0) {
    dialogSelectItems.value = {
      ...pps.modelValue[0],
    };
  }
  formInit();
});
</script>

<style scoped>
.main-box {
  flex-grow: 1;
}
</style>
