<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formRestaurantInfo"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormRestaurantInfo()" @reset="resetFormRestaurantInfo">
        <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.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.contactInformationFilter"
            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.isBestNewShopFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isBestNewShopFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isBestNewShopFilterWidgetDropdownList"
              :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.isDeliciousShopFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isDeliciousShopFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isDeliciousShopFilterWidgetDropdownList"
              :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.isRecommendedShopFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isRecommendedShopFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isRecommendedShopFilterWidgetDropdownList"
              :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.isSelectShopFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isSelectShopFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isSelectShopFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="restaurantInfo"
      class="page-table"
      :data="restaurantInfoWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((restaurantInfoWidgetCurrentPage - 1) * restaurantInfoWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="restaurantInfoWidget.onSortChange"
      @refresh="restaurantInfoWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formRestaurantInfo:formRestaurantInfo:add')"
          @click="onAddClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formRestaurantInfo:formRestaurantInfo:export')"
          @click="onExportClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formRestaurantInfo:formRestaurantInfo:import')"
          :on-change="onImportClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formRestaurantInfo:formRestaurantInfo:import')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="restaurantInfoWidget.getTableIndex" :width="80" />
      <vxe-column title="店铺名称" field="name" />
      <vxe-column title="店铺种类">
        <template v-slot="scope">
          <span>{{ (scope.row.typeIdDictMapList || []).map(item => item.name).join(',')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="店铺标签" field="tag" />
      <vxe-column title="店铺公告" field="announcement" />
      <vxe-column title="工作时间段" field="workTime" />
      <vxe-column title="店铺地址" field="address" />
      <vxe-column title="是否启用" field="enableDictMap.name" />
      <vxe-column title="店铺图片" min-width="100px">
        <template v-slot="scope">
          <el-image v-for="item in parseUploadData(scope.row.url, { id: scope.row.id, fieldName: 'url', asImage: true })"
            :preview-src-list="getPictureList(scope.row.url, { id: scope.row.id, fieldName: 'url', 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="contactInformation" />
      <vxe-column title="销量" field="totalSales" />
      <vxe-column title="配送费" field="deliveryCharge" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditClick(scope.row)"
            :disabled="!checkPermCodeExist('formRestaurantInfo:formRestaurantInfo:edit')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteClick(scope.row)"
            :disabled="!checkPermCodeExist('formRestaurantInfo:formRestaurantInfo: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="restaurantInfoWidgetTotalCount"
            :current-page="restaurantInfoWidgetCurrentPage"
            :page-size="restaurantInfoWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="restaurantInfoWidget.onCurrentPageChange"
            @size-change="restaurantInfoWidget.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: 'formRestaurantInfo',
};
</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 { RestaurantInfoData } from '@/api/generated/restaurantInfoController';
import { RestaurantInfoController } from '@/api/generated';
import FormEditRestaurant from '@/pages/generated/formEditRestaurant.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({
  // 店铺名称
  nameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 联系方式
  contactInformationFilter: undefined,
  // 是否优选新店
  isBestNewShopFilter: undefined,
  // 是否美味店铺
  isDeliciousShopFilter: undefined,
  // 是否推荐店铺
  isRecommendedShopFilter: undefined,
  // 是否精选好店
  isSelectShopFilter: undefined,
});
const formFilterCopy = reactive({
  // 店铺名称
  nameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 联系方式
  contactInformationFilter: undefined,
  // 是否优选新店
  isBestNewShopFilter: undefined,
  // 是否美味店铺
  isDeliciousShopFilter: undefined,
  // 是否推荐店铺
  isRecommendedShopFilter: undefined,
  // 是否精选好店
  isSelectShopFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadRestaurantInfoWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    restaurantInfoDtoFilter: {
      name: formFilter.nameFilter,
      enable: formFilter.enableFilter,
      contactInformation: formFilter.contactInformationFilter,
      isSelectShop: formFilter.isSelectShopFilter,
      isRecommendedShop: formFilter.isRecommendedShopFilter,
      isDeliciousShop: formFilter.isDeliciousShopFilter,
      isBestNewShop: formFilter.isBestNewShopFilter,
    }
  };
  return new Promise((resolve, reject) => {
    RestaurantInfoController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadRestaurantInfoVerify = () => {
  formFilterCopy.nameFilter = formFilter.nameFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  formFilterCopy.contactInformationFilter = formFilter.contactInformationFilter;
  formFilterCopy.isBestNewShopFilter = formFilter.isBestNewShopFilter;
  formFilterCopy.isDeliciousShopFilter = formFilter.isDeliciousShopFilter;
  formFilterCopy.isRecommendedShopFilter = formFilter.isRecommendedShopFilter;
  formFilterCopy.isSelectShopFilter = formFilter.isSelectShopFilter;
  return true;
};
/**
 * 新建
 */
const onAddClick = (row?: RestaurantInfoData) => {
  let params: ANY_OBJECT = {
  };

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

  Dialog
    .show('编辑', FormEditRestaurant, { area: ['900px','650px'] }, { ...params, subPage: true })
    .then(res => {
      restaurantInfoWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportClick = (row?: RestaurantInfoData) => {
  let params: ANY_OBJECT = {
    restaurantInfoDtoFilter: {
      name: formFilter.nameFilter,
      enable: formFilter.enableFilter,
      contactInformation: formFilter.contactInformationFilter,
    }
  };

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

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

  RestaurantInfoController.delete(params).then(res => {
    ElMessage.success('删除成功');
    restaurantInfoWidget.refreshTable(false, 1);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const restaurantInfoOptions: TableOptions<RestaurantInfoData> = {
  loadTableData: loadRestaurantInfoWidgetData,
  verifyTableParameter: loadRestaurantInfoVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const restaurantInfo = ref();
const restaurantInfoWidget = useTable(restaurantInfoOptions);
const {
  dataList: restaurantInfoWidgetDataList,
  currentPage: restaurantInfoWidgetCurrentPage,
  pageSize: restaurantInfoWidgetPageSize,
  totalCount: restaurantInfoWidgetTotalCount,
} = restaurantInfoWidget;
console.log("restaurantInfoWidgetDataList",restaurantInfoWidgetDataList)
/**
 * 是否启用下拉数据获取函数
 */
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 loadIsBestNewShopFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsBestNewShop.getList(),
  });
};
// 是否优选新店 配置参数
const isBestNewShopFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsBestNewShopFilterDropdownList,
  isTree: false,
};
// 是否优选新店 下拉组件
const isBestNewShopFilterWidget = useDropdown(isBestNewShopFilterOptions);
const { dropdownList: isBestNewShopFilterWidgetDropdownList } = isBestNewShopFilterWidget
/**
 * 是否美味店铺 下拉数据获取函数
 */
const loadIsDeliciousShopFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsDeliciousShop.getList(),
  });
};
// 是否美味店铺 配置参数
const isDeliciousShopFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsDeliciousShopFilterDropdownList,
  isTree: false,
};
// 是否美味店铺 下拉组件
const isDeliciousShopFilterWidget = useDropdown(isDeliciousShopFilterOptions);
const { dropdownList: isDeliciousShopFilterWidgetDropdownList } = isDeliciousShopFilterWidget
/**
 * 是否推荐店铺 下拉数据获取函数
 */
const loadIsRecommendedShopFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsRecommendedShop.getList(),
  });
};
// 是否推荐店铺 配置参数
const isRecommendedShopFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsRecommendedShopFilterDropdownList,
  isTree: false,
};
// 是否推荐店铺 下拉组件
const isRecommendedShopFilterWidget = useDropdown(isRecommendedShopFilterOptions);
const { dropdownList: isRecommendedShopFilterWidgetDropdownList } = isRecommendedShopFilterWidget
/**
 * 是否精选好店下拉数据获取函数
 */
const loadIsSelectShopFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsSelectShop.getList(),
  });
};
// 是否精选好店配置参数
const isSelectShopFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsSelectShopFilterDropdownList,
  isTree: false,
};
// 是否精选好店下拉组件
const isSelectShopFilterWidget = useDropdown(isSelectShopFilterOptions);
const { dropdownList: isSelectShopFilterWidgetDropdownList } = isSelectShopFilterWidget
const refreshFormRestaurantInfo = () => {
  // 刷新段落
  restaurantInfoWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormRestaurantInfo = () => {
  formFilter.nameFilter = undefined;
  formFilterCopy.nameFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  formFilter.contactInformationFilter = undefined;
  formFilterCopy.contactInformationFilter = undefined;
  formFilter.isBestNewShopFilter = undefined;
  formFilterCopy.isBestNewShopFilter = undefined;
  formFilter.isDeliciousShopFilter = undefined;
  formFilterCopy.isDeliciousShopFilter = undefined;
  formFilter.isRecommendedShopFilter = undefined;
  formFilterCopy.isRecommendedShopFilter = undefined;
  formFilter.isSelectShopFilter = undefined;
  formFilterCopy.isSelectShopFilter = undefined;
  refreshFormRestaurantInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormRestaurantInfo();
};
const formInit = () => {
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isBestNewShopFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isDeliciousShopFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isRecommendedShopFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isSelectShopFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormRestaurantInfo();
};

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