<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formPlatformCarCategoryInfoRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormPlatformCarCategoryInfo()" @reset="resetFormPlatformCarCategoryInfo">
        <!-- <el-form-item label="标题">
          <el-input
            class="filter-item"
            v-model="formFilter.titleFilter"
            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.nameFilter"
            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.modelFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="modelFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in modelFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="tourCarCategory"
      class="page-table"
      :data="tourCarCategoryWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourCarCategoryWidgetCurrentPage - 1) * tourCarCategoryWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="tourCarCategoryWidget.onSortChange"
      @refresh="tourCarCategoryWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formPlatformCarCategoryInfo:formPlatformCarCategoryInfo:add')"
          @click="onAddClick()"
          >
          新建
        </el-button>
      </template>
      <vxe-column title="序号" type="seq" :index="tourCarCategoryWidget.getTableIndex" :width="80" />
      <vxe-column title="车型种类" field="modelDictMap.name" />
      <!-- <vxe-column title="标题" field="title" /> -->
      <vxe-column title="车型名称" field="name" />
      <vxe-column title="包车价格" field="price" />
      <vxe-column title="单位" field="unit" />
      <vxe-column title="座位数" field="seatNumber" />
      <vxe-column title="图片" min-width="100px">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.image, {
                id: scope.row.id,
                fieldName: 'image',
                asImage: true
              })
            "
            type="card"
            direction="horizontal"
            :readonly="true"
          />
        </template>
      </vxe-column>
      <vxe-column title="车型归属" field="typeDictMap.name" />
      <vxe-column title="行李数" field="luggageNumber" />
      <vxe-column title="归属部门" field="deptIdDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditClick(scope.row)"
            :disabled="!checkPermCodeExist('formPlatformCarCategoryInfo:formPlatformCarCategoryInfo:edit')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteClick(scope.row)"
            :disabled="!checkPermCodeExist('formPlatformCarCategoryInfo:formPlatformCarCategoryInfo: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="tourCarCategoryWidgetTotalCount"
            :current-page="tourCarCategoryWidgetCurrentPage"
            :page-size="tourCarCategoryWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourCarCategoryWidget.onCurrentPageChange"
            @size-change="tourCarCategoryWidget.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: 'formPlatformCarCategoryInfo',
};
</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 { TourCarDriverData } from '@/api/generated/tourCarDriverController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { TourCarCategoryData } from '@/api/generated/tourCarCategoryController';
import { TourCarDriverController, SysDeptController, TourCarCategoryController } from '@/api/generated';
import EditPlatformCarCategory from '@/pages/tourContractCarInfo/editPlatformCarCategory.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({
  // 标题
  titleFilter: undefined,
  // 车型名称
  nameFilter: undefined,
  // 车型种类
  modelFilter: undefined,
  // 车型归属
  typeFilter: undefined,
});
const formFilterCopy = reactive({
  // 标题
  titleFilter: undefined,
  // 车型名称
  nameFilter: undefined,
  // 车型种类
  modelFilter: undefined,
  // 车型归属
  typeFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourCarCategoryWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourCarCategoryDtoFilter: {
      model: formFilter.modelFilter,
      title: formFilter.titleFilter,
      name: formFilter.nameFilter,
      //自营为1,第三方为2
      type: 1,
    }
  };
  return new Promise((resolve, reject) => {
    TourCarCategoryController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourCarCategoryVerify = () => {
  formFilterCopy.titleFilter = formFilter.titleFilter;
  formFilterCopy.nameFilter = formFilter.nameFilter;
  formFilterCopy.modelFilter = formFilter.modelFilter;
  formFilterCopy.typeFilter = formFilter.typeFilter;
  return true;
};
/**
 * 新建
 */
 const onAddClick = (row?: TourCarCategoryData) => {
  let params: ANY_OBJECT = {
  };
  //判断是否为管理员，如果不是，则进行提示
  TourCarCategoryController.isAdmin(params).then(res => {
  TourCarCategoryController.existCarCategory(params).then(res => {
  Dialog
    .show('新建', EditPlatformCarCategory, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      tourCarCategoryWidget.refreshTable();
    }).catch(e => {
      return;
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
   console.error(e);
  });
  }).catch(e => {
  // TODO: 异常处理
  console.error(e);
  });
};
/**
 * 编辑
 */
const onEditClick = (row?: TourCarCategoryData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  //判断是否为管理员，如果不是，则进行提示
  TourCarCategoryController.isAdmin(params).then(res => {
  Dialog
    .show('编辑', EditPlatformCarCategory, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      tourCarCategoryWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
}).catch(e => {
  return;
 // TODO: 异常处理
 console.error(e);
});
};
/**
 * 删除
 */
const onDeleteClick = (row?: TourCarCategoryData) => {
  let params: ANY_OBJECT = {
  };

  ElMessageBox.confirm('是否删除该数据').then(res => {
    TourCarCategoryController.delete(params).then(res => {
      ElMessage.success('删除成功');
      tourCarCategoryWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const tourCarCategoryOptions: TableOptions<TourCarCategoryData> = {
  loadTableData: loadTourCarCategoryWidgetData,
  verifyTableParameter: loadTourCarCategoryVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const tourCarCategory = ref();
const tourCarCategoryWidget = useTable(tourCarCategoryOptions);
const {
  dataList: tourCarCategoryWidgetDataList,
  currentPage: tourCarCategoryWidgetCurrentPage,
  pageSize: tourCarCategoryWidgetPageSize,
  totalCount: tourCarCategoryWidgetTotalCount,
} = tourCarCategoryWidget;
/**
 * 车型种类下拉数据获取函数
 */
const loadModelFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCarModel(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 车型种类配置参数
const modelFilterOptions: DropdownOptions<DictData> = {
  loadData: loadModelFilterDropdownList,
  isTree: false,
};
// 车型种类下拉组件
const modelFilterWidget = useDropdown(modelFilterOptions);
const { dropdownList: modelFilterWidgetDropdownList } = modelFilterWidget
/**
 * 车型归属下拉数据获取函数
 */
const loadTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.TourCarType.getList(),
  });
};
// 车型归属配置参数
const typeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadTypeFilterDropdownList,
  isTree: false,
};
// 车型归属下拉组件
const typeFilterWidget = useDropdown(typeFilterOptions);
const { dropdownList: typeFilterWidgetDropdownList } = typeFilterWidget
const refreshFormPlatformCarCategoryInfo = () => {
  // 刷新段落
  tourCarCategoryWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormPlatformCarCategoryInfo = () => {
  formFilter.titleFilter = undefined;
  formFilterCopy.titleFilter = undefined;
  formFilter.nameFilter = undefined;
  formFilterCopy.nameFilter = undefined;
  formFilter.modelFilter = undefined;
  formFilterCopy.modelFilter = undefined;
  formFilter.typeFilter = undefined;
  formFilterCopy.typeFilter = undefined;
  refreshFormPlatformCarCategoryInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormPlatformCarCategoryInfo();
};
const formInit = () => {
  modelFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  typeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormPlatformCarCategoryInfo();
};

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