<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditRestaurantRef"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="店铺所属部门" prop="RestaurantInfo.deptId">
              <el-cascader
                class="input-item"
                v-model="deptIdPath"
                :options="deptIdWidgetDropdownList"
                placeholder=""
                :clearable="true"
                :filterable="true"
                :show-all-levels="false"
                :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
                @change="onDeptIdValueChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="店铺种类" prop="RestaurantInfo.typeId">
              <el-select
                class="input-item"
                v-model="typeIdSelect"
                multiple
                :collapse-tags="true"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="typeIdWidget.onVisibleChange"
                @change="onTypeIdValueChange"
              >
                <el-option
                  v-for="item in typeIdWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="店铺名称" prop="RestaurantInfo.name">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.name"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否优选新店" prop="RestaurantInfo.isBestNewShop">
              <el-select
                class="input-item"
                v-model="formData.RestaurantInfo.isBestNewShop"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isBestNewShopWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isBestNewShopWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否精选好店" prop="RestaurantInfo.isSelectShop">
              <el-select
                class="input-item"
                v-model="formData.RestaurantInfo.isSelectShop"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isSelectShopWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isSelectShopWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否美味店铺" prop="RestaurantInfo.isDeliciousShop">
              <el-select
                class="input-item"
                v-model="formData.RestaurantInfo.isDeliciousShop"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isDeliciousShopWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isDeliciousShopWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否推荐店铺" prop="RestaurantInfo.isRecommendedShop">
              <el-select
                class="input-item"
                v-model="formData.RestaurantInfo.isRecommendedShop"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isRecommendedShopWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isRecommendedShopWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐指数" prop="RestaurantInfo.recommendationRate">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantInfo.recommendationRate"
                placeholder=""
                :clearable="true"
                :min="0"
                :max="5"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="店铺标签" prop="RestaurantInfo.tag">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.tag"
                type="textarea"
                placeholder="多个标签请以&分割"
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="送餐时间/min" prop="RestaurantInfo.deliveryTime">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.deliveryTime"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="店铺公告" prop="RestaurantInfo.announcement">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.announcement"
                type="textarea"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="工作时间段" prop="RestaurantInfo.workTime">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.workTime"
                type="text"
                placeholder="(例:8:00-19:00)"
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="是否启用" prop="RestaurantInfo.enable">
              <el-radio-group
                class="input-item"
                v-model="formData.RestaurantInfo.enable"
              >
                <el-radio
                  v-for="item in enableWidgetDropdownList"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所处国家" prop="RestaurantInfo.contry">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.contry"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所处城市" prop="RestaurantInfo.city">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.city"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="店铺地址" prop="RestaurantInfo.address">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.address"
                type="textarea"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系方式" prop="RestaurantInfo.contactInformation">
              <el-input
                class="input-item"
                v-model="formData.RestaurantInfo.contactInformation"
                type="textarea"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="RestaurantInfo.longitude">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantInfo.longitude"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="6"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="RestaurantInfo.latitude">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantInfo.latitude"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="6"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销量" prop="RestaurantInfo.totalSales">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantInfo.totalSales"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送费" prop="RestaurantInfo.deliveryCharge">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantInfo.deliveryCharge"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最低消费" prop="RestaurantInfo.minCharge">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantInfo.minCharge"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="店铺图片" prop="RestaurantInfo.url">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/restaurantInfo/upload')"
                :data="{fieldName: 'url', asImage: true}"
                :on-success="onUrlUploadSuccess"
                :on-remove="onUrlRemoveFile"
                :on-error="onUploadError"
                :file-list="urlWidgetFileList"
                :show-file-list="false"
              >
              <div v-if="urlWidgetFileList && urlWidgetFileList != null" style="position: relative">
                <img class="upload-image-show"
                     v-if="urlWidgetFileList[0]"
                  :src="urlWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onUrlRemoveFile(null, null)" />
              </div>
              <i v-else class="el-icon-plus upload-image-item"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="banner图片" prop="RestaurantInfo.restaurantBanner">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/restaurantInfo/upload')"
                :data="{fieldName: 'restaurantBanner', asImage: true}"
                :on-success="onRestaurantBannerUploadSuccess"
                :on-remove="onRestaurantBannerRemoveFile"
                :on-error="onUploadError"
                :file-list="restaurantBannerWidgetFileList"
                :show-file-list="false"
              >
                <div v-if="restaurantBannerWidgetFileList && restaurantBannerWidgetFileList[0] != null" style="position: relative">
                  <img class="upload-image-show"
                       :src="restaurantBannerWidgetFileList[0].url" />
                  <div class="upload-img-del el-icon-close"
                       @click.stop="onRestaurantBannerRemoveFile(null, null)" />
                </div>
                <i v-else class="el-icon-plus upload-image-item"></i>
              </el-upload>
            </el-form-item>
          </el-col>
<!--          <el-col :span="14">-->
<!--            <el-form-item label="店铺环境图片" prop="RestaurantInfo.environmentImage">-->
<!--              <el-upload-->
<!--                class="upload-image-item upload-image-multi"-->
<!--                name="uploadFile"-->
<!--                :headers="getUploadHeaders"-->
<!--                :action="getUploadActionUrl('/admin/app/restaurantInfo/upload')"-->
<!--                :data="{fieldName: 'environmentImage', asImage: true}"-->
<!--                :on-success="onEnvironmentImage_copyUploadSuccess"-->
<!--                :on-remove="onEnvironmentImage_copyRemoveFile"-->
<!--                :on-error="onUploadError"-->
<!--                :on-exceed="onUploadLimit"-->
<!--                list-type="picture-card"-->
<!--                :file-list="environmentImage_copyWidgetFileList"-->
<!--                :limit="environmentImage_copyWidgetMaxCount"-->
<!--                :show-file-list="true"-->
<!--              >-->
<!--                <i class="el-icon-plus upload-image-item"></i>-->
<!--              </el-upload>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary" @click="onSaveClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditRestaurant',
};
</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 { RestaurantInfoData } from '@/api/generated/restaurantInfoController';
import { RestaurantInfoController } 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 props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
    id?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    id: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);
const environmentImage_copyWidgetFileList = ref([]);
const formEditRestaurantRef = ref();
// 表单数据定义
type FormEditRestaurantData = {
  RestaurantInfo: RestaurantInfoData;
};
// 表单数据
const formData = reactive<FormEditRestaurantData>({
  RestaurantInfo: {
    // 主键id
    id: undefined,
    // 店铺名称
    name: undefined,
    // 店铺标签
    tag: undefined,
    // 店铺种类
    typeId: undefined,
    // 店铺公告
    announcement: undefined,
    // 工作时间段(例:8:00-19:00)
    workTime: undefined,
    // 店铺地址
    address: undefined,
    // 是否启用，0禁用，1启用
    enable: undefined,
    // 店铺图片
    url: undefined,
    // 店铺环境图片
    environmentImage: undefined,
    // 联系方式
    contactInformation: undefined,
    // 经度
    longitude: undefined,
    // 纬度
    latitude: undefined,
    // 销量
    totalSales: undefined,
    // 所处国家
    contry: undefined,
    // 创建用户
    createUserId: undefined,
    // 所处城市
    city: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 用户所在部门Id
    deptId: undefined,
    // 配送费
    deliveryCharge: undefined,
    //最低消费
    minCharge: undefined,
    // 精选好店 标记 1是 2 不是
    isSelectShop: undefined,
    // 推荐店铺 标记 1是 2 不是
    isRecommendedShop: undefined,
    // 美味店铺标记  1是 2不是
    isDeliciousShop: undefined,
    // 优选新店 标记 1是 2 不是
    isBestNewShop: undefined,
    // banner图
    restaurantBanner: undefined,
    // 推荐指数
    recommendationRate: undefined,
    // 送餐时间/min
    deliveryTime: undefined,
  }
},
);
// 表单验证规则
const rules = reactive({
  'RestaurantInfo.deliveryTime': [
  ],
  'RestaurantInfo.restaurantBanner': [
  ],
  'RestaurantInfo.isDeliciousShop': [
    {required: true, message: '请输入是否美味店铺', trigger: 'blur'}
  ],
  'RestaurantInfo.enable': [
    {required: true, message: '请输入是否启用', trigger: 'blur'}
  ],
  'RestaurantInfo.isBestNewShop': [
    {required: true, message: '请输入是否优选新店', trigger: 'blur'}
  ],
  'RestaurantInfo.city': [
  ],
  'RestaurantInfo.address': [
  ],
  'RestaurantInfo.minCharge': [
  ],
  'RestaurantInfo.recommendationRate': [
  ],
  'RestaurantInfo.isSelectShop': [
    {required: true, message: '请输入是否精选好店', trigger: 'blur'}
  ],
  'RestaurantInfo.environmentImage': [
  ],
  'RestaurantInfo.isRecommendedShop': [
    {required: true, message: '请输入是否推荐店铺', trigger: 'blur'}
  ],
  'RestaurantInfo.url': [
  ],
  'RestaurantInfo.longitude': [
  ],
  'RestaurantInfo.contactInformation': [
  ],
  'RestaurantInfo.tag': [
  ],
  'RestaurantInfo.name': [
    {required: true, message: '请输入店铺名称', trigger: 'blur'}
  ],
  'RestaurantInfo.latitude': [
    {type: 'number', message: '纬度只允许输入数字', trigger: 'blur', transform: (value) => Number(value)}
  ],
  'RestaurantInfo.deliveryCharge': [
  ],
  'RestaurantInfo.typeId': [
    {required: true, message: '请输入店铺种类', trigger: 'blur'}
  ],
  'RestaurantInfo.totalSales': [
  ],
  'RestaurantInfo.workTime': [
  ],
  'RestaurantInfo.announcement': [
  ],
  'RestaurantInfo.contry': [
  ],
  'RestaurantInfo.deptId': [
    {required: true, message: '请输入店铺所属部门', trigger: 'blur'}
  ],
});

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

const isEdit = computed(() => {
  return props.saveOnSubmit ? props.id != null : props.rowData != null;
});

// 初始化页面数据
const loadRestaurantInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.RestaurantInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    RestaurantInfoController.view(params).then(res => {
      formData.RestaurantInfo = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 店铺所属部门下拉数据获取函数
 */
const loadDeptIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictSysDept(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 店铺所属部门选中值改变
 */
const onDeptIdValueChange = (value) => {
  formData.RestaurantInfo.deptId = Array.isArray(value) ? value[value.length - 1] : value;
};
// 店铺所属部门配置参数
const deptIdOptions: DropdownOptions<DictData> = {
  loadData: loadDeptIdDropdownList,
  isTree: true,
};
// 店铺所属部门选中数据
const deptIdPath = ref<Array<string | number>>([]);
// 店铺所属部门下拉组件
const deptIdWidget = useDropdown(deptIdOptions);
const { dropdownList: deptIdWidgetDropdownList } = deptIdWidget
/**
 * 店铺种类下拉数据获取函数
 */
const loadTypeIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictRestaurantType(params).then(res => {
      resolve({
        dataList: res.getList().map(item => {
          return {
            id: item.id + '',
            name: item.name,
          };
        }),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 店铺种类选中值改变
 */
const onTypeIdValueChange = (value) => {
  formData.RestaurantInfo.typeId = (value || []).join(',');
};
// 店铺种类配置参数
const typeIdOptions: DropdownOptions<DictData> = {
  loadData: loadTypeIdDropdownList,
  isTree: false,
};
// 店铺种类选中数据
const typeIdSelect = ref<Array<string | number>>([]);
// 店铺种类下拉组件
const typeIdWidget = useDropdown(typeIdOptions);
const { dropdownList: typeIdWidgetDropdownList } = typeIdWidget
/**
 * 是否优选新店下拉数据获取函数
 */
const loadIsBestNewShopDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsBestNewShop.getList(),
  });
};
// 是否优选新店配置参数
const isBestNewShopOptions: DropdownOptions<DictData> = {
  loadData: loadIsBestNewShopDropdownList,
  isTree: false,
};
// 是否优选新店下拉组件
const isBestNewShopWidget = useDropdown(isBestNewShopOptions);
const { dropdownList: isBestNewShopWidgetDropdownList } = isBestNewShopWidget
/**
 * 是否精选好店下拉数据获取函数
 */
const loadIsSelectShopDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsSelectShop.getList(),
  });
};
// 是否精选好店配置参数
const isSelectShopOptions: DropdownOptions<DictData> = {
  loadData: loadIsSelectShopDropdownList,
  isTree: false,
};
// 是否精选好店下拉组件
const isSelectShopWidget = useDropdown(isSelectShopOptions);
const { dropdownList: isSelectShopWidgetDropdownList } = isSelectShopWidget
/**
 * 是否美味店铺下拉数据获取函数
 */
const loadIsDeliciousShopDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsDeliciousShop.getList(),
  });
};
// 是否美味店铺配置参数
const isDeliciousShopOptions: DropdownOptions<DictData> = {
  loadData: loadIsDeliciousShopDropdownList,
  isTree: false,
};
// 是否美味店铺下拉组件
const isDeliciousShopWidget = useDropdown(isDeliciousShopOptions);
const { dropdownList: isDeliciousShopWidgetDropdownList } = isDeliciousShopWidget
/**
 * 是否推荐店铺下拉数据获取函数
 */
const loadIsRecommendedShopDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsRecommendedShop.getList(),
  });
};
// 是否推荐店铺配置参数
const isRecommendedShopOptions: DropdownOptions<DictData> = {
  loadData: loadIsRecommendedShopDropdownList,
  isTree: false,
};
// 是否推荐店铺下拉组件
const isRecommendedShopWidget = useDropdown(isRecommendedShopOptions);
const { dropdownList: isRecommendedShopWidgetDropdownList } = isRecommendedShopWidget

/**
 * 是否启用下拉数据获取函数
 */
const loadEnableDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 是否启用配置参数
const enableOptions: DropdownOptions<DictData> = {
  loadData: loadEnableDropdownList,
  isTree: false,
};
// 是否启用下拉组件
const enableWidget = useDropdown(enableOptions);
const { dropdownList: enableWidgetDropdownList } = enableWidget
/**
 * 店铺图片上传成功
 */
const onUrlUploadSuccess = (
  response: ANY_OBJECT,
  file: UploadFile,
  fileList: UploadFile[],
) => {
  if (response.success) {
    file.downloadUri = response.data.downloadUri;
    file.filename = response.data.filename;
    file.uploadPath = response.data.uploadPath;
    file.url = URL.createObjectURL(file.raw);
    urlWidget.onFileChange(file, fileList);
    formData.RestaurantInfo.url = fileListToJson(urlWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除店铺图片
 */
const onUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  urlWidget.onFileChange(file, fileList);
  formData.RestaurantInfo.url = fileListToJson(urlWidgetFileList.value);
};
// 店铺图片上传文件组件
const urlWidget = useUploadWidget(1);
const { fileList: urlWidgetFileList, maxCount: urlWidgetMaxCount } = urlWidget;
/**
 * 店铺环境图片上传成功
 */
const onEnvironmentImageUploadSuccess = (
  response: ANY_OBJECT,
  file: UploadFile,
  fileList: UploadFile[],
) => {
  if (response.success) {
    file.downloadUri = response.data.downloadUri;
    file.filename = response.data.filename;
    file.uploadPath = response.data.uploadPath;
    file.url = URL.createObjectURL(file.raw);
    environmentImageWidget.onFileChange(file, fileList);
    formData.RestaurantInfo.environmentImage = fileListToJson(environmentImageWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除店铺环境图片
 */
const onEnvironmentImageRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  environmentImageWidget.onFileChange(file, fileList);
  formData.RestaurantInfo.environmentImage = fileListToJson(environmentImageWidgetFileList.value);
};
// 店铺环境图片上传文件组件
const environmentImageWidget = useUploadWidget(3);
const { fileList: environmentImageWidgetFileList, maxCount: environmentImageWidgetMaxCount } = environmentImageWidget;
/**
 * banner图片上传成功
 */
const onRestaurantBannerUploadSuccess = (
  response: ANY_OBJECT,
  file: UploadFile,
  fileList: UploadFile[],
) => {
  if (response.success) {
    file.downloadUri = response.data.downloadUri;
    file.filename = response.data.filename;
    file.uploadPath = response.data.uploadPath;
    file.url = URL.createObjectURL(file.raw);
    restaurantBannerWidget.onFileChange(file, fileList);
    formData.RestaurantInfo.restaurantBanner = fileListToJson(restaurantBannerWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除banner图片
 */
const onRestaurantBannerRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  restaurantBannerWidget.onFileChange(file, fileList);
  formData.RestaurantInfo.restaurantBanner = fileListToJson(restaurantBannerWidgetFileList.value);
};
// banner图片上传文件组件
const restaurantBannerWidget = useUploadWidget(1);
const { fileList: restaurantBannerWidgetFileList, maxCount: restaurantBannerWidgetMaxCount } = restaurantBannerWidget;

const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditRestaurant = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditRestaurant = () => {
  refreshFormEditRestaurant();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditRestaurant();
};
/**
 * 保存
 */
const onSaveClick = () => {
  formEditRestaurantRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.RestaurantInfo
      };
    formData.typeIdDictMap = findItemFromList(typeIdWidgetDropdownList, formData.typeId, 'id');
    formData.deptIdDictMap = findTreeNode(deptIdWidgetDropdownList, formData.deptId, 'id');
    formData.isBestNewShopDictMap = findItemFromList(isBestNewShopWidgetDropdownList, formData.isBestNewShop, 'id');
    formData.isSelectShopDictMap = findItemFromList(isSelectShopWidgetDropdownList, formData.isSelectShop, 'id');
    formData.isDeliciousShopDictMap = findItemFromList(isDeliciousShopWidgetDropdownList, formData.isDeliciousShop, 'id');
    formData.isRecommendedShopDictMap = findItemFromList(isRecommendedShopWidgetDropdownList, formData.isRecommendedShop, 'id');
    formData.enableDictMap = findItemFromList(enableWidgetDropdownList, formData.enable, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      restaurantInfoDto: {
        id: formData.RestaurantInfo.id,
        deptId: formData.RestaurantInfo.deptId,
        deliveryCharge: formData.RestaurantInfo.deliveryCharge,
        minCharge: formData.RestaurantInfo.minCharge,
        name: formData.RestaurantInfo.name,
        tag: formData.RestaurantInfo.tag,
        isSelectShop: formData.RestaurantInfo.isSelectShop,
        isRecommendedShop: formData.RestaurantInfo.isRecommendedShop,
        isDeliciousShop: formData.RestaurantInfo.isDeliciousShop,
        isBestNewShop: formData.RestaurantInfo.isBestNewShop,
        restaurantBanner: formData.RestaurantInfo.restaurantBanner,
        deliveryTime: formData.RestaurantInfo.deliveryTime,
        typeId: formData.RestaurantInfo.typeId,
        announcement: formData.RestaurantInfo.announcement,
        workTime: formData.RestaurantInfo.workTime,
        address: formData.RestaurantInfo.address,
        enable: formData.RestaurantInfo.enable,
        url: formData.RestaurantInfo.url,
        environmentImage: formData.RestaurantInfo.environmentImage,
        contactInformation: formData.RestaurantInfo.contactInformation,
        longitude: formData.RestaurantInfo.longitude,
        latitude: formData.RestaurantInfo.latitude,
        totalSales: formData.RestaurantInfo.totalSales,
        createUserId: formData.RestaurantInfo.createUserId,
        contry: formData.RestaurantInfo.contry,
        createTime: formData.RestaurantInfo.createTime,
        city: formData.RestaurantInfo.city,
        updateUserId: formData.RestaurantInfo.updateUserId,
        updateTime: formData.RestaurantInfo.updateTime,
        recommendationRate: formData.RestaurantInfo.recommendationRate,
      }
    };

    let httpCall = isEdit.value ? RestaurantInfoController.update : RestaurantInfoController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadRestaurantInfoData().then(res => {
    deptIdWidget.onVisibleChange(true).then(res => {
      // TODO: 获取级联选中路径
      deptIdPath.value = findTreeNodePath(res, formData.RestaurantInfo.deptId);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    typeIdWidget.onVisibleChange(true).then(res => {
      // TODO: 获取多选选中值
      typeIdSelect.value = formData.RestaurantInfo.typeId ? formData.RestaurantInfo.typeId.split(',') : [];
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    isBestNewShopWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isSelectShopWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isDeliciousShopWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isRecommendedShopWidget.onVisibleChange(true).catch(e => {console.error(e)});
    enableWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let environmentImage_copyDownloadParams = {
      id: formData.RestaurantInfo.id,
      fieldName: 'environmentImage',
      asImage: true
    };
    // console.log(formData.RestaurantInfo);
    // let urlDownloadParams = {
    //   id: formData.RestaurantInfo.id,
    //   fieldName: 'url',
    //   asImage: true
    // };
    // urlWidgetFileList.value = parseUploadData(formData.RestaurantInfo.url, urlDownloadParams);
    // console.log(urlWidgetFileList.value);
    // console.log(formData.RestaurantInfo)
    environmentImage_copyWidgetFileList.value = parseUploadData(formData.RestaurantInfo.environmentImage, environmentImage_copyDownloadParams);
    let urlDownloadParams = {
      id: formData.RestaurantInfo.id,
      fieldName: 'url',
      asImage: true
    };
    urlWidgetFileList.value = parseUploadData(formData.RestaurantInfo.url, urlDownloadParams);
    let restaurantBannerDownloadParams = {
      id: formData.RestaurantInfo.id,
      fieldName: 'restaurantBanner',
      asImage: true
    };

    restaurantBannerWidgetFileList.value = parseUploadData(formData.RestaurantInfo.restaurantBanner, restaurantBannerDownloadParams);
    if (isEdit.value) refreshFormEditRestaurant();

  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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