<template>
  <view>
    <view class="item" v-for="(tab, index) in resultArray" :key="index" @click="showDrawer('showLeft', tab)">
      {{ tab.groupName }}
    </view>
    <uni-drawer ref="showLeft" mode="left" :mask-click="true" @change="handleDrawerChange">

      <view class="drawer-content">
        <input class="styled-input" v-model="form.dishesName" placeholder="请输入菜品名" />
        <button @click="chooseImage" class="styled-button">选择图片</button>
        <view v-if="form.dishesImage">
          <image :src="'http://'+form.dishesImage" style="width:30px; height:30px;" />
        
        </view>
        <input class="styled-input" v-model="form.dishesPrice" type="number" step="0.01" placeholder="请输入菜品价格" />
        <button @click="addDishes" class="styled-button confirm">添加菜品</button>
        <view v-if="result !== null">{{ result }}</view>
      </view>
    </uni-drawer>
  </view>
</template>

<script>
import { apiImageUrl } from '../../API/api';

export default {
  data() {
    return {
      businessId: '', 
      resultArray: [],
      result: null,
      currentGroupId: '',
      form: {
        dishesName: '',
        dishesImage: '',
        dishesPrice: '',
        dishesGroup: '',
        inventoryStatus: 0,
        packPrice: 0,
        specificationsIds: [],
        status: 0,
      }
    };
  },
  mounted() {
    this.loadCurrentBusinessId();
    this.leftGroup();
  },
  methods: {
    loadCurrentBusinessId() {
      const storedBusinessId = uni.getStorageSync('businessId');
      if (storedBusinessId) {
        this.businessId = storedBusinessId;
      } else {
        console.error('currentBusinessId not found in storage');
      }
    },

    leftGroup() {
      const DishesGroupQueryRequest = {
        businessId: this.businessId
      };

      uni.request({
        url: apiImageUrl + '/api/dishesGroup/list/dishesGroup',
        method: 'POST',
        data: JSON.stringify(DishesGroupQueryRequest),
        header: {
          'Content-Type': 'application/json'
        }
      }).then((res) => {
        console.log(res); 
        if (res[1] && res[1].data && res[1].data.code === 0) {
          this.resultArray = res[1].data.data.map(item => ({
            id: item.id,
            groupName: item.groupName
          }));
          console.log(this.resultArray);
        } else {
          console.error('Unexpected response structure:', res);
        }
      }).catch((error) => {
        console.error('Error fetching dishes groups:', error);
      });
    },

    showDrawer(drawer, tab) {
      this.currentGroupId = tab.id; 
      this.form.dishesGroup = tab.id; 
      this.$refs[drawer].open();
    },

    closeDrawer() {
      this.$refs.showLeft.close();
    },

    chooseImage() {
      console.log('选择图片按钮被点击'); 
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], 
        sourceType: ['album', 'camera'], 
        success: (res) => {
          console.log('图片选择成功:', res); 
          const tempFilePaths = res.tempFilePaths;
          const filePath = tempFilePaths[0];
          this.uploadFile(filePath);
        },
        fail: (err) => {
          console.error('选择图片失败:', err); 
        }
      });
    },

    uploadFile(filePath) {
        console.log('开始上传图片:', filePath);
        uni.uploadFile({
          url: apiImageUrl + '/api/file/upload/server',
          filePath: filePath,
          name: 'file',
          formData: { biz: 'dishes' },
          success: (uploadFileRes) => {
            try {
              const responseData = JSON.parse(uploadFileRes.data);
              console.log('上传结果:', responseData);
              
              
              if (responseData && responseData.data) {
                this.form.dishesImage = responseData.data;
                console.log('上传成功，图片URL:', this.form.dishesImage);
              } else {
                console.error('未找到有效图片路径:', responseData);
              }
            } catch (e) {
              console.error('解析上传结果失败:', e);
            }
          },
          fail: (err) => {
            console.error('上传文件失败：', err);
          }
        });
      },

    addDishes() {
      const data = {
        businessId: this.businessId,
        dishesGroupId: parseInt(this.form.dishesGroup, 10),
        dishesImage: this.form.dishesImage,
        dishesName: this.form.dishesName,
        dishesPrice: parseFloat(this.form.dishesPrice),
        inventoryStatus: 0,
        packPrice: 0,
        specificationsIds: [],
        status: 0,
      };

      uni.request({
        url: apiImageUrl + '/api/dishes/add',
        method: 'POST',
        header: {
          'content-type': 'application/json' 
        },
        data: data,
        success: (res) => {
          console.log('成功返回：', res.data);
         
          this.result = '菜品添加成功！';
          this.closeDrawer();
          uni.showModal({
            title: '提示',
            content: '菜品添加成功！',
            showCancel: false
          });
        },
        fail: (err) => {
          console.error('请求失败：', err);
          
          this.result = '菜品添加失败，请重试。';
          uni.showModal({
            title: '提示',
            content: '菜品添加失败，请重试！',
            showCancel: false
          });
        }
      });
    }
  }
};
</script>



<style lang="scss">
.item {
	font-size: 13px;
  padding: 10px 20px;
  display: inline-block;
  background-color: rgba(245, 245, 220, 0.8); 
  margin: 10px; 
  border-radius: 20px;
  box-shadow: 0 4px #ccc, 0 6px 10px rgba(0,0,0,0.1), inset 0 2px #fff, inset 0 -2px 2px rgba(0,0,0,0.1); 
  transition: transform 0.2s; 

  &:hover {
    transform: translateY(-2px); 
    box-shadow: 0 6px #ccc, 0 8px 15px rgba(0,0,0,0.1), inset 0 4px #fff, inset 0 -2px 3px rgba(0,0,0,0.1);
  }
}
.styled-input {
	font-size: 14px;
	width: calc(100% - 20px);
	padding: 10px;
	margin: 10px 0; 
	display: block;
	background-color: rgba(245, 245, 220, 0.8);
	border-radius: 20px;
	box-shadow: 0 4px #ccc, 0 6px 10px rgba(0,0,0,0.1), inset 0 2px #fff, inset 0 -2px 2px rgba(0,0,0,0.1);
	border: none;
	outline: none;
	transition: box-shadow 0.2s;

	&:focus {
		box-shadow: 0 6px #ccc, 0 8px 15px rgba(0,0,0,0.1), inset 0 4px #fff, inset 0 -2px 3px rgba(0,0,0,0.1);
	}
}

.button-container {
	display: flex;
	justify-content: space-between;
}

.styled-button {
	font-size: 14px;
	flex: 1;
	margin: 5px;
	padding: 10px;
	background-color: rgba(173, 216, 230, 0.8);
	border: none;
	border-radius: 15px;
	box-shadow: 0 4px #ccc, 0 6px 10px rgba(0,0,0,0.1), inset 0 2px #fff, inset 0 -2px 2px rgba(0,0,0,0.1);
	cursor: pointer;
	transition: box-shadow 0.2s, background-color 0.2s;

	&:hover {
		background-color: rgba(173, 216, 230, 1); 
		box-shadow: 0 6px #ccc, 0 8px 15px rgba(0,0,0,0.1), inset 0 4px #fff, inset 0 -2px 3px rgba(0,0,0,0.1);
	}
}

.confirm {
	font-size: 14px;
	background-color: rgba(135, 206, 235, 0.8); 
}

.delete {
	font-size: 14px;
	background-color: rgba(255, 99, 71, 0.8); 
}
</style>