<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourTourismTravelNotesInfo"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourTourismTravelNotesInfo()" @reset="resetFormTourTourismTravelNotesInfo">
        <el-form-item label="项目标题">
          <el-input
            class="filter-item"
            v-model="formFilter.projectTitleFilter"
            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.remarksFilter"
            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>
        <el-form-item label="出发地">
          <el-input
            class="filter-item"
            v-model="formFilter.startPlaceFilter"
            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.endPlaceFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="tourTourismProjectTravelNotes"
      class="page-table"
      :data="tourTourismProjectTravelNotesWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourTourismProjectTravelNotesWidgetCurrentPage - 1) * tourTourismProjectTravelNotesWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="tourTourismProjectTravelNotesWidget.onSortChange"
      @refresh="tourTourismProjectTravelNotesWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourTourismTravelNotesInfo:formTourTourismTravelNotesInfo:add')"
          @click="onAddClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourTourismTravelNotesInfo:formTourTourismTravelNotesInfo:export')"
          @click="onExportClick()"
          >
          导出
        </el-button>
      </template>
      <vxe-column title="序号" type="seq" :index="tourTourismProjectTravelNotesWidget.getTableIndex" :width="80" />
      <vxe-column title="项目标题" field="projectTitle" width="200" align="center"/>
      <vxe-column title="所属分类" field="belongTabDictMap.name" />
      <vxe-column title="是否热点" field="isHotspotDictMap.name"  align="center"/>
      <!-- <vxe-column title="标签" field="projectLabel" /> -->
      <!-- <vxe-column title="出发地" field="startPlace"  align="center"/>
      <vxe-column title="目的地" field="endPlace"  align="center"/> -->
      <vxe-column title="总天数" field="countTimes"  align="center"/>
      <!-- <vxe-column title="显示顺序" field="showOrder" /> -->
      <vxe-column title="是否启用" field="enableDictMap.name" align="center"/>
      <vxe-column title="项目展示图片" min-width="100px" align="center">
        <template v-slot="scope">
          <el-image v-for="item in parseUploadData(scope.row.tourismUrl, { id: scope.row.id, fieldName: 'tourismUrl', asImage: true })"
            :preview-src-list="getPictureList(scope.row.tourismUrl, { id: scope.row.id, fieldName: 'tourismUrl', 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="isOriginal">
      <template #default="{ row }">
        <el-switch
          v-model="row.isOriginal"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
          @change="handleIsOriginalChange(row)"
        />
      </template>
      <!-- <vxe-column title="是否原创" field="isOriginal"> -->
        <!-- <template #default="{ row }">
          <el-radio-group v-model="row.isOriginal" @change="handleIsOriginalChange(row)">
            <el-radio :label="0">非原创</el-radio>
            <el-radio :label="1">原创</el-radio>
          </el-radio-group>
        </template> -->
      </vxe-column>
      <vxe-column title="创建时间" field="createTime" />
      <vxe-column title="更新时间" field="updateTime" />
      <!-- <vxe-column title="项目价格" field="price" />
      <vxe-column title="价格单位" field="priceUnit" /> -->
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourTourismTravelNotesInfo:formTourTourismTravelNotesInfo:edit')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourTourismTravelNotesInfo:formTourTourismTravelNotesInfo:delete')"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onFormTravelNotesProjectListClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourTourismTravelNotesInfo:formTourTourismTravelNotesInfo:formTravelNotesProjectList')"
          >
            关联项目
          </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="tourTourismProjectTravelNotesWidgetTotalCount"
            :current-page="tourTourismProjectTravelNotesWidgetCurrentPage"
            :page-size="tourTourismProjectTravelNotesWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourTourismProjectTravelNotesWidget.onCurrentPageChange"
            @size-change="tourTourismProjectTravelNotesWidget.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: 'formTourTourismTravelNotesInfo',
};
</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 { TourismProjectData } from '@/api/generated/tourismProjectController';
import { TourTourismTravelNotesContentData } from '@/api/generated/tourTourismTravelNotesContentController';
import { TourTourismTravelNotesFileData } from '@/api/generated/tourTourismTravelNotesFileController';
import { TourTourismProjectTravelNotesData } from '@/api/generated/tourTourismProjectTravelNotesController';
import { TourismProjectController, TourTourismTravelNotesContentController, TourTourismTravelNotesFileController, TourTourismProjectTravelNotesController } from '@/api/generated';
import FormEditTourTourismTravelNotes from '@/pages/tourTourismTravelNotes/formEditTourTourismTravelNotes.vue';
import FormTravelNotesProjectList from '@/pages/tourTourismTravelNotes/formTravelNotesProjectList.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({
  // 项目标题
  projectTitleFilter: undefined,
  // 项目简述
  remarksFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 出发地
  startPlaceFilter: undefined,
  // 目的地
  endPlaceFilter: undefined,
});
const formFilterCopy = reactive({
  // 项目标题
  projectTitleFilter: undefined,
  // 项目简述
  remarksFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 出发地
  startPlaceFilter: undefined,
  // 目的地
  endPlaceFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourTourismProjectTravelNotesWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourTourismProjectTravelNotesDtoFilter: {
      projectTitle: formFilter.projectTitleFilter,
      remarks: formFilter.remarksFilter,
      isHotspot: formFilter.isHotspotFilter,
      enable: formFilter.enableFilter,
      belongTab: formFilter.belongTabFilter,
      startPlace: formFilter.startPlaceFilter,
      endPlace: formFilter.endPlaceFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourTourismProjectTravelNotesController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourTourismProjectTravelNotesVerify = () => {
  formFilterCopy.projectTitleFilter = formFilter.projectTitleFilter;
  formFilterCopy.remarksFilter = formFilter.remarksFilter;
  formFilterCopy.belongTabFilter = formFilter.belongTabFilter;
  formFilterCopy.isHotspotFilter = formFilter.isHotspotFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  formFilterCopy.startPlaceFilter = formFilter.startPlaceFilter;
  formFilterCopy.endPlaceFilter = formFilter.endPlaceFilter;
  return true;
};
/**
 * 新建
 */
const onAddClick = (row?: TourTourismProjectTravelNotesData) => {
  let params: ANY_OBJECT = {
  };

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

  Dialog
    .show('编辑', FormEditTourTourismTravelNotes, { area: ['1300px','700px'] }, { ...params, subPage: true })
    .then(res => {
      tourTourismProjectTravelNotesWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportClick = (row?: TourTourismProjectTravelNotesData) => {
  let params: ANY_OBJECT = {
    tourTourismProjectTravelNotesDtoFilter: {
      projectTitle: formFilter.projectTitleFilter,
      remarks: formFilter.remarksFilter,
      belongTab: formFilter.belongTabFilter,
      isHotspot: formFilter.isHotspotFilter,
      enable: formFilter.enableFilter,
      startPlace: formFilter.startPlaceFilter,
      endPlace: formFilter.endPlaceFilter,
    }
  };

  TourTourismProjectTravelNotesController.export(params, '.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 删除
 */
const onDeleteClick = (row?: TourTourismProjectTravelNotesData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  TourTourismProjectTravelNotesController.delete(params).then(res => {
    ElMessage.success('删除成功');
    tourTourismProjectTravelNotesWidget.refreshTable(false, 1);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 关联项目
 */
const onFormTravelNotesProjectListClick = (row?: TourTourismProjectTravelNotesData) => {
  let params: ANY_OBJECT = {
    travelNotesId: row?.id,
  };

  router.push({
    name: 'formTravelNotesProjectList',
    query: { ...params, subPage: true }
  });
};
// 表格组件表格组件参数
const tourTourismProjectTravelNotesOptions: TableOptions<TourTourismProjectTravelNotesData> = {
  loadTableData: loadTourTourismProjectTravelNotesWidgetData,
  verifyTableParameter: loadTourTourismProjectTravelNotesVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'updateTime',
  ascending: false,
};
// 表格组件表格组件
const tourTourismProjectTravelNotes = ref();
const tourTourismProjectTravelNotesWidget = useTable(tourTourismProjectTravelNotesOptions);
const {
  dataList: tourTourismProjectTravelNotesWidgetDataList,
  currentPage: tourTourismProjectTravelNotesWidgetCurrentPage,
  pageSize: tourTourismProjectTravelNotesWidgetPageSize,
  totalCount: tourTourismProjectTravelNotesWidgetTotalCount,
} = tourTourismProjectTravelNotesWidget;
/**
 * 所属分类下拉数据获取函数
 */
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 refreshFormTourTourismTravelNotesInfo = () => {
  // 刷新段落
  tourTourismProjectTravelNotesWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourTourismTravelNotesInfo = () => {
  formFilter.projectTitleFilter = undefined;
  formFilterCopy.projectTitleFilter = undefined;
  formFilter.remarksFilter = undefined;
  formFilterCopy.remarksFilter = undefined;
  formFilter.belongTabFilter = undefined;
  formFilterCopy.belongTabFilter = undefined;
  belongTabFilterPath.value = [];
  formFilter.isHotspotFilter = undefined;
  formFilterCopy.isHotspotFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  formFilter.startPlaceFilter = undefined;
  formFilterCopy.startPlaceFilter = undefined;
  formFilter.endPlaceFilter = undefined;
  formFilterCopy.endPlaceFilter = undefined;
  refreshFormTourTourismTravelNotesInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourTourismTravelNotesInfo();
};
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)});
  refreshFormTourTourismTravelNotesInfo();
};

const handleIsOriginalChange = (row)=>{
  console.log(2234)
  console.log(row)
  let params: ANY_OBJECT = {
    tourTourismProjectTravelNotesDto: {
      id: row.id,
      isOriginal: row.isOriginal
    }
  }
  console.log(params)
  TourTourismProjectTravelNotesController.updateIsOriginalChange(params).then(res => {
    ElMessage.success('保存成功');
    tourTourismProjectTravelNotesWidget.refreshTable(false, 1);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
    tourTourismProjectTravelNotesWidget.refreshTable(false, 1);
  });
}

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