<template>
  <div class="relation-select">
    <el-select
      :modelValue="modelValue"
      style="width: 100%;"
      :disabled="disabled"
      :size="size"
      :clearable="clearable"
      :placeholder="placeholder"
      :popper-append-to-body="false"
      popper-class="relation-select-popper"
      @visible-change="onVisibleChange"
      @remove-tag="onRemoveTag"
      @clear="onClear"
    >
      <el-option
        v-for="item in selectedItems"
        :key="item[props.value]"
        :label="item[props.label]"
        :value="item[props.value]"
      />
    </el-select>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formSelectType',
};
</script>

<script setup lang="ts">
import { getUUID } from '@/common/utils';
import { RestaurantFoodTypeData } from '@/api/generated/restaurantFoodTypeController';
import { RestaurantFoodTypeController } from '@/api/generated';
import FormSelectType from '@/pages/generated/formSelectType/formSelectType.vue';
import { ANY_OBJECT } from '@/types/generic';
import { Dialog } from '@/components/Dialog';
import { ElMessage } from 'element-plus';

const emit = defineEmits<{
  'update:modelValue': [string | number | RestaurantFoodTypeData[]];
  change: [string | number | RestaurantFoodTypeData[], string | number | RestaurantFoodTypeData[]];
}>();

const pps = withDefaults(
  defineProps<{
    modelValue: string | number | RestaurantFoodTypeData[] | undefined;
    props?: ANY_OBJECT;
    disabled?: boolean;
    size?: '' | 'default' | 'large' | 'small';
    clearable?: boolean;
    placeholder?: string;
  }>(),
  {
    props: () => {
      return {
        label: 'name',
        value: 'id',
        restaurantId:'restaurantId'
      };
    },
    disabled: false,
    clearable: false,
  },
);

const widgetId = getUUID();
const selectedItems = ref<ANY_OBJECT[]>([]);
const selectedValue = ref<string | number | RestaurantFoodTypeData[] | undefined>(pps.modelValue);

const handlerEditOperate = (item: RestaurantFoodTypeData) => {
  selectedItems.value = [];
  if (item) selectedItems.value.push(item);
  if (!checkSelectChange()) return;
  emitChange();
};

const onVisibleChange = (visible: boolean) => {
  if (visible) {
  if(pps.props.restaurantId == null || pps.props.restaurantId == undefined){
    ElMessage.warning('请先选餐馆,再选择种类');
    return;
  }
    Dialog.show<ANY_OBJECT>(
      '选择餐馆美食类型',
      FormSelectType,
      {
        area: ['1200px', '650px'],
        offset: '100px',
      },
      {
        modelValue: selectedItems.value,
        props: pps.props,
        path: 'formSelectType/' + widgetId
      },
      {
        width: '1200px',
        height: '650px',
        pathName: '/thirdParty/formSelectType'
      },
    ).then(res => {
      handlerEditOperate(res);
    });
  }
};

const onRemoveTag = (val: ANY_OBJECT) => {
  selectedItems.value = selectedItems.value.filter(item => {
    return item[pps.props.value] !== val;
  });
  emitChange();
};
const onClear = () => {
  selectedItems.value = [];
  emitChange();
};

const emitChange = () => {
  let tempValue;
  tempValue = selectedItems.value[0] || {};
  emit('update:modelValue', tempValue[pps.props.value]);
  emit('change', tempValue[pps.props.value], selectedItems.value[0]);
};
const checkSelectChange = () => {
  let valueIdString = pps.modelValue || '';
  let selectedItemsString = selectedItems.value
    .sort((item1, item2) => {
      if (item1[pps.props.value] === item2[pps.props.value]) return 0;
      return item1[pps.props.value] < item2[pps.props.value] ? -1 : 1;
    })
    .map(item => item[pps.props.value])
    .join(',');
  return valueIdString !== selectedItemsString;
};
const getSelectItemList = () => {
  if (pps.modelValue == null || pps.modelValue === '') {
    selectedItems.value = [];
  } else {
    let params: ANY_OBJECT = {
      id: pps.modelValue,
    };
    RestaurantFoodTypeController.view(params)
      .then(res => {
        if (res.data) {
          selectedItems.value = [res.data];
        }
      })
      .catch(e => {
        console.log(e);
      });
  }
};

watch(
  () => pps.modelValue,
  newVal => {
    selectedValue.value = newVal;
    getSelectItemList();
  },
  {
    immediate: true,
  },
);
</script>

<style scoped>
  .relation-select ::v-deep .relation-select-popper {
    display: none;
  }

  .relation-select ::v-deep .el-dialog__header {
    height: 42px;
    line-height: 42px;
    padding: 0px 20px;
    background-color: #F8F8F8;
  }
  .relation-select ::v-deep .el-dialog__title {
    color: #333;
    font-size: 14px;
  }
  .relation-select ::v-deep .el-dialog__headerbtn {
    top: 12px;
  }
  .relation-select ::v-deep .el-dialog__body {
    padding: 25px;
  }
</style>
