<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditRestaurantFood"
        :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="RestaurantFoodInfo.restaurantId">
              <el-select
                class="input-item"
                v-model="formData.RestaurantFoodInfo.restaurantId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="restaurantIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in restaurantIdWidgetDropdownList"
                  :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="RestaurantFoodInfo.foodTypeId">
              <el-cascader
                class="input-item"
                v-model="foodTypeIdPath"
                :options="foodTypeIdWidgetDropdownList"
                placeholder=""
                :clearable="true"
                :filterable="true"
                :show-all-levels="false"
                :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
                @change="onFoodTypeIdValueChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="RestaurantFoodInfo.name">
              <el-input
                class="input-item"
                v-model="formData.RestaurantFoodInfo.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="RestaurantFoodInfo.url">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/restaurantFoodInfo/upload')"
                :data="{fieldName: 'url', asImage: true}"
                :on-success="onUrlUploadSuccess"
                :on-remove="onUrlRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="urlWidgetFileList && urlWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :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="12">
            <el-form-item label="是否启用" prop="RestaurantFoodInfo.enable">
              <el-radio-group
                class="input-item"
                v-model="formData.RestaurantFoodInfo.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="RestaurantFoodInfo.isHotFood">
              <el-select
                class="input-item"
                v-model="formData.RestaurantFoodInfo.isHotFood"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isHotFoodWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isHotFoodWidgetDropdownList"
                  :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="RestaurantFoodInfo.sales">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantFoodInfo.sales"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品价格" prop="RestaurantFoodInfo.price">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantFoodInfo.price"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格单位" prop="RestaurantFoodInfo.priceUnit">
              <el-input
                class="input-item"
                v-model="formData.RestaurantFoodInfo.priceUnit"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打包费" prop="RestaurantFoodInfo.balingCharge">
              <el-input-number
                class="input-item"
                v-model="formData.RestaurantFoodInfo.balingCharge"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </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: 'formEditRestaurantFood',
};
</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 { RestaurantFoodInfoData } from '@/api/generated/restaurantFoodInfoController';
import { RestaurantFoodInfoController } 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 formEditRestaurantFood = ref();
// 表单数据定义
type FormEditRestaurantFoodData = {
  RestaurantFoodInfo: RestaurantFoodInfoData;
};
// 表单数据
const formData = reactive<FormEditRestaurantFoodData>({
  RestaurantFoodInfo: {
    // 主键id
    id: undefined,
    // 饭馆美食种类id
    foodTypeId: undefined,
    // 菜品名称
    name: undefined,
    // 菜品图片
    url: undefined,
    // 是否启用，0禁用，1启用
    enable: undefined,
    // 菜品销量
    sales: undefined,
    // 菜品价格
    price: undefined,
    // 创建用户
    createUserId: undefined,
    // 价格单位
    priceUnit: undefined,
    // 创建时间
    createTime: undefined,
    // 用户所在部门Id
    deptId: undefined,
    // 餐馆id
    restaurantId: undefined,
    // 打包费
    balingCharge: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 超火美食标记 1是 2不是
    isHotFood: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'RestaurantFoodInfo.isHotFood': [
    {required: true, message: '请输入是否超火美食', trigger: 'blur'},
  ],
  'RestaurantFoodInfo.price': [
  ],
  'RestaurantFoodInfo.restaurantId': [
    {required: true, message: '请输入选择餐馆', trigger: 'blur'}
  ],
  'RestaurantFoodInfo.sales': [
  ],
  'RestaurantFoodInfo.name': [
    {required: true, message: '请输入菜品名称', trigger: 'blur'}
  ],
  'RestaurantFoodInfo.url': [
    {required: true, message: '请输入菜品图片', trigger: 'blur'}
  ],
  'RestaurantFoodInfo.enable': [
    {required: true, message: '请输入是否启用', trigger: 'blur'}
  ],
  'RestaurantFoodInfo.detpId': [
    {required: true, message: '请输入用户所在部门Id', trigger: 'blur'}
  ],
  'RestaurantFoodInfo.priceUnit': [
  ],
  'RestaurantFoodInfo.balingCharge': [
  ],
});

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

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

// 初始化页面数据
const loadRestaurantFoodInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.RestaurantFoodInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    RestaurantFoodInfoController.view(params).then(res => {
      formData.RestaurantFoodInfo = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 选择餐馆下拉数据获取函数
 */
const loadRestaurantIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictRestaurantInfo(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 选择餐馆配置参数
const restaurantIdOptions: DropdownOptions<DictData> = {
  loadData: loadRestaurantIdDropdownList,
  isTree: false,
};
// 选择餐馆下拉组件
const restaurantIdWidget = useDropdown(restaurantIdOptions);
const { dropdownList: restaurantIdWidgetDropdownList } = restaurantIdWidget
/**
 * 饭馆美食类型下拉数据获取函数
 */
const loadFoodTypeIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
      restaurantId: formData.RestaurantFoodInfo.restaurantId
    };
    DictionaryController.dictRestaurantFoodType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 饭馆美食类型选中值改变
 */
const onFoodTypeIdValueChange = (value) => {
  formData.RestaurantFoodInfo.foodTypeId = Array.isArray(value) ? value[value.length - 1] : value;
};
// 饭馆美食类型配置参数
const foodTypeIdOptions: DropdownOptions<DictData> = {
  loadData: loadFoodTypeIdDropdownList,
  isTree: true,
};
// 饭馆美食类型选中数据
const foodTypeIdPath = ref<Array<string | number>>([]);
// 饭馆美食类型下拉组件
const foodTypeIdWidget = useDropdown(foodTypeIdOptions);
const { dropdownList: foodTypeIdWidgetDropdownList } = foodTypeIdWidget
/**
 * 菜品图片上传成功
 */
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.RestaurantFoodInfo.url = fileListToJson(urlWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除菜品图片
 */
const onUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  urlWidget.onFileChange(file, fileList);
  formData.RestaurantFoodInfo.url = fileListToJson(urlWidgetFileList.value);
};
// 菜品图片上传文件组件
const urlWidget = useUploadWidget(1);
const { fileList: urlWidgetFileList, maxCount: urlWidgetMaxCount } = urlWidget;
/**
 * 是否启用下拉数据获取函数
 */
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 loadIsHotFoodDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsHotFood.getList(),
  });
};
// 是否超火美食配置参数
const isHotFoodOptions: DropdownOptions<DictData> = {
  loadData: loadIsHotFoodDropdownList,
  isTree: false,
};
// 是否超火美食下拉组件
const isHotFoodWidget = useDropdown(isHotFoodOptions);
const { dropdownList: isHotFoodWidgetDropdownList } = isHotFoodWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditRestaurantFood = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditRestaurantFood = () => {
  refreshFormEditRestaurantFood();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditRestaurantFood();
};
/**
 * 保存
 */
const onSaveClick = () => {
  formEditRestaurantFood.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.RestaurantFoodInfo
      };
    formData.restaurantIdDictMap = findItemFromList(restaurantIdWidgetDropdownList, formData.restaurantId, 'id');
    formData.foodTypeIdDictMap = findTreeNode(foodTypeIdWidgetDropdownList, formData.foodTypeId, 'id');
    formData.enableDictMap = findItemFromList(enableWidgetDropdownList, formData.enable, 'id');
    formData.isHotFoodDictMap = findItemFromList(isHotFoodWidgetDropdownList, formData.isHotFood, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      restaurantFoodInfoDto: {
        id: formData.RestaurantFoodInfo.id,
        priceUnit: formData.RestaurantFoodInfo.priceUnit,
        restaurantId: formData.RestaurantFoodInfo.restaurantId,
        balingCharge: formData.RestaurantFoodInfo.balingCharge,
        foodTypeId: formData.RestaurantFoodInfo.foodTypeId,
        name: formData.RestaurantFoodInfo.name,
        url: formData.RestaurantFoodInfo.url,
        enable: formData.RestaurantFoodInfo.enable,
        sales: formData.RestaurantFoodInfo.sales,
        price: formData.RestaurantFoodInfo.price,
        createUserId: formData.RestaurantFoodInfo.createUserId,
        createTime: formData.RestaurantFoodInfo.createTime,
        updateUserId: formData.RestaurantFoodInfo.updateUserId,
        updateTime: formData.RestaurantFoodInfo.updateTime,
        isHotFood: formData.RestaurantFoodInfo.isHotFood,
      }
    };

    let httpCall = isEdit.value ? RestaurantFoodInfoController.update : RestaurantFoodInfoController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadRestaurantFoodInfoData().then(res => {
    restaurantIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    foodTypeIdWidget.onVisibleChange(true).then(res => {
      // TODO: 获取级联选中路径
      foodTypeIdPath.value = findTreeNodePath(res, formData.RestaurantFoodInfo.foodTypeId);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    let urlDownloadParams = {
      id: formData.RestaurantFoodInfo.id,
      fieldName: 'url',
      asImage: true
    };
    urlWidgetFileList.value = parseUploadData(formData.RestaurantFoodInfo.url, urlDownloadParams);
    enableWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isHotFoodWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshFormEditRestaurantFood();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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