<template>
  <view class="main">
	<view class="head" :class="headShow?'head_show':''" :style="{'opacity':headShow?opacity:'1','padding-top':statusBartop+'px'}">
	  	<view class="head_cont" :style="{'width': statusHeight+'px','height':statusHeight+'px'}">
	  		<view class="head_back"  @click="handleBack()" :style="{'width': statusHeight+'px','height':statusHeight+'px'}">
	  			<image class="head_back_img" src="https://zhkj1.oss-cn-shanghai.aliyuncs.com/newPD/zhBack.png" mode="widthFix"></image>
	  		</view>
	  		<view class="head_title" :style="{'width':pageWidth+'px','height':statusHeight+'px'}">申请售后</view>
	  	</view>
	</view>
	<view class="cont_view" :style="{'padding-top':statusBartop+statusHeight+10+'px'}">
		<view class="data_list" v-for="(item,index) in orderInfoList" :key="index">
			<view class="data_img">
				<image class="data_imgUrl" :src="item.image" mode="widthFix"></image>
			</view>
			<view class="data_text">
				<view class="data_title"><text>{{item.storeName}}</text></view>
				<view class="data_operate">
					<view class="data_num price">{{item.price}}</view>
					<view class="data_edit">
						<view class="data_edit_img border_l" @click="editAmount(1,item)">
							<image class="data_edit_imgurl" :class="item.amount == 0 ? 'opy':''" src="https://zhkj1.oss-cn-shanghai.aliyuncs.com/zhscMerchant/minus.png" mode="widthFix"></image>
						</view>
						<view class="data_number">{{item.amount}}</view>
						<view class="data_edit_img border_r" @click="editAmount(2,item)">
							<image class="data_edit_imgurl" :class="item.amount == item.cartNum ? 'opy':''" src="https://zhkj1.oss-cn-shanghai.aliyuncs.com/zhscMerchant/add.png" mode="widthFix"></image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="cont" >
			<textarea class="cont_textarea" :disable-default-padding="isIos" placeholder="请填写您的退款理由～" v-model="returnReason"></textarea>
		</view>
		<view class="cont cont_padding">
			<view class="cont_item">
				<view class="cont_item_l">
					<image class="cont_item_img" src="../../static/ass/money.png" mode="widthFix"></image>
					<view class="cont_item_text">退款金额</view>
				</view>
				<view class="cont_item_r"><input class="cont_item_input font_input" disabled="true" type="digit" placeholder="请输入金额" v-model="returnAmount"/><text>元</text></view>
			</view>
			<view class="cont_border"></view>
			<view class="cont_item">
				<view class="cont_item_l">
					<image class="cont_item_img" src="../../static/ass/phone.png" mode="widthFix"></image>
					<view class="cont_item_text">联系方式</view>
				</view>
				<view class="cont_item_r"><input class="cont_item_input" type="number" placeholder="请输入电话号码" v-model="contactPhone"/></view>
			</view>
			<view class="cont_border"></view>
			<view class="cont_item">
				<view class="cont_item_l">
					<image class="cont_item_img" src="../../static/ass/img.png" mode="widthFix"></image>
					<view class="cont_item_text">照片</view>
				</view>
			</view>
			<view class="cont_shop_text">请将菜品图上传</view>
			<view class="cont_shop_edit">
				<view class="cont_ul">
					<view class="cont_li" v-for="(img,i) in returnImage" :key="i">
						<view class="cont_upload_remove" @click="delImg(i)">
							<image class="cont_upload_remove_img" src="../../static/eval/closeImg.png" mode="widthFix"></image>
						</view>
						<image class="cont_li_img" :src="img" mode="aspectFill" @click="previewImage(i)"></image>
					</view>
					<view class="cont_li cont_upload" @click="chooseImage()" v-if="returnImage.length <= 5">
						<image class="cont_upload_img" src="../../static/ass/uploading.png" mode="widthFix"></image>
						<view class="cont_upload_text">添加照片</view>
					</view>
					
				</view>
			</view>
		</view>
	</view>
	<view style="height: 200rpx;"></view>
	<view class="footer">
		<view class="footer_btn" :class="!btnShow ? 'opy':''" @click="api_returnreturnApply()">{{!count?"退款数量必须有一项大于0":"提交(共退款"+count+"件)"}}</view>
	</view>
  </view>
</template>
<script setup>
import { url }  from '@/server/config.js'
import { loads } from '@/utils/index.js'
import { computed,ref,onMounted,onUnmounted,getCurrentInstance,nextTick } from 'vue';
import { useCounterStore } from '@/store/counter'; // 引入 Pinia Store
import { storeToRefs } from 'pinia';//实现解构付值
import { onLoad,onShow,onPullDownRefresh,onPageScroll,onReachBottom,onReady } from "@dcloudio/uni-app"
import { returngetOrder,returncomputedPrice,returnreturnApply } from "@/server/api.js"
const counterStore = useCounterStore(); // 使用 Store
const { proxy } = getCurrentInstance();
//使用pinia：storeToRefs方法包裹(保持响应式更新，不使用视图无法更新)
const {statusHeight,headerHeight,statusBartop,ButtonWidth,ButtonHeight,token } = storeToRefs(counterStore);
const headShow = ref(false);
const showBack = ref(false);
const pageWidth = ref(0);
const opacity = ref(1);
const timeImg = ref('');
const isIos = ref(false);
const orderId = ref("");
const returnAmount = ref(0);
const returnImage = ref([]);
const returnReason = ref('');
const contactPhone = ref('');
const orderInfoList = ref([]);
const id = ref('');
const System = () =>{
	const phone = wx.getSystemInfoSync();
	if (phone.platform == 'ios') {
	    isIos.value = true
	} else if (phone.platform == 'android') {
	    isIos.value = false
	}
}
// 获取页面宽度
const updatePageWidth = () => {
  const systemInfo = uni.getSystemInfoSync();
  pageWidth.value = systemInfo.windowWidth;
}
const searchWidth = computed(() => {
	return pageWidth.value - statusHeight.value - ButtonWidth.value - 35;
})
const count = computed(() => {
	const count = orderInfoList.value.filter(item => item.amount > 0);
	return count.length
});

const btnShow = computed(() => {
	let show = false;
	if(count.value && returnReason.value && contactPhone.value && returnImage.value.length){
		show = true
	}else{
		show = false
	}
	return show;
})
// 判断是否有上一页
const getPages = () => {
  const pages = getCurrentPages();
  return pages.length > 1;
}
const handleBack = () => {
  if (getPages()) {
    // 如果有上一页，返回上一页
    uni.navigateBack();
  } else {
    // 如果没有上一页，返回首页
    uni.switchTab({
      url: '/pages/index/index',
    });
  }
}
const editAmount =(e,list)=>{
	const { productId,cartNum,amount } = list;
	if(e == 1 && amount == 0) return false;
	if(e == 2 && cartNum == amount) return false;
	orderInfoList.value.forEach(item=>{
		if(item.productId == productId){
			if(e == 1){
				item.amount = item.amount - 1;
			}else{
				item.amount = item.amount + 1;
			}
		}
	})
	api_returncomputedPrice();
}
//删除上传图片
const delImg = (i) =>{
	const item = returnImage.value.slice()
	item.splice(i, 1)
	returnImage.value = item;
}
//获取可退款商品
const api_returngetOrder=()=>{
	loads('', true)
	return returngetOrder(orderId.value).then(({data}) => {
		uni.hideLoading();
		data.orderInfoList.forEach(item=>{
			item.amount = 1
		})
		orderInfoList.value = data.orderInfoList
		id.value = data.id
	})
	.then(()=>api_returncomputedPrice())
	.catch(({message}) => {
		uni.hideLoading();
		uni.showModal({
			content:message,
			showCancel: false,
			success: () => {
				uni.navigateBack({
					delta:1
				})
			}
		})
	})
}
//获取退款计算
const api_returncomputedPrice=()=>{
	//过滤出选中的对象
	const items = orderInfoList.value.filter(item => item.amount > 0);
	// 提取 name 和 age 组成新数组
	const request = items.map(item => ({
	  productId: item.comment,
	  returnNum: item.amount,
	  unique:item.attrId
	}));
	const params = {
		orderNo:orderId.value,
		returnInfo:request
	}
	loads('', true)
	return returncomputedPrice(params).then(({data}) => {
		uni.hideLoading();
		returnAmount.value = data.returnAmount;
	}).catch(({message}) => {
		uni.hideLoading();
		uni.showModal({
			content:message,
			showCancel: false
		})
	})
}
//提交退款
const api_returnreturnApply=()=>{
	if(!count.value){
		return false;
	}
	if(!returnReason.value){
		uni.showToast({
			title:'输入退款理由',
			icon:'error'
		})
		return false;
	}
	if(!contactPhone.value){
		uni.showToast({
			title:'输入联系方式',
			icon:'error'
		})
		return false;
	}
	if(!returnImage.value.length){
		uni.showToast({
			title:'上传退款凭证',
			icon:'error'
		})
		return false;
	}
	//过滤出选中的对象
	const items = orderInfoList.value.filter(item => item.amount > 0);
	//提取 name 和 age 组成新数组
	const request = items.map(item => ({
	  productId: item.comment,
	  returnNum: item.amount,
	  unique:item.attrId
	}));
	const params = {
		contactPhone:contactPhone.value,
		id:id.value,
		orderNo:orderId.value,
		returnImage:returnImage.value.toString(),
		returnReason:returnReason.value,
		returnInfo: request
	}
	loads('', true)
	return returnreturnApply(params).then(({message}) => {
		uni.hideLoading();
		uni.showToast({
			title:message,
			icon:'success',
			success: () => {
				setTimeout(()=>{
					uni.redirectTo({
						url:`/order/assList/assList?type=1`
					})
				},1400)
			}
		})
	}).catch(({message}) => {
		uni.hideLoading();
		uni.showModal({
			content:message,
			showCancel: false
		})
	})
}
//查看上传图片
const previewImage = (i)=>{
	let picture = returnImage.value;
	uni.previewImage({
	    current: i,
	    urls:picture
	});
}
//选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 6, // 最多选择6张
    sizeType: ['original', 'compressed'], // 可选择原图或压缩图
    sourceType: ['album', 'camera'], // 可从相册或相机选择
    success: (res) => {
	  api_uploadimage(res.tempFilePaths);
    },
    fail: (err) => {
      console.error('选择图片失败:', err);
    }
  });
}
//接口上传图片拿到图片url
const api_uploadimage = (tempFilePaths) =>{
  loads('上传中', true)
  uni.uploadFile({
    url:`${url}/api/front/user/upload/image`, // 替换为你的接口地址
    filePath: tempFilePaths[0], // 图片临时路径
    name: 'multipart', // 后端接收文件的字段名
	header: {
		'Authori-zation':token.value ,// 身份令牌
		'Content-Type': 'multipart/form-data'
	},
    formData: { // 附加的其他参数
      model: 'wechat',
      pid: '8'
    },
    success: (res) => {
	  uni.hideLoading()
      const data = JSON.parse(res.data); // 解析后端返回的数据
	  returnImage.value.push(data.data.url);
    },
    fail: (err) => {
	  uni.hideLoading()
      console.error('上传失败:', err);
    }
  })
}
onLoad((options) => {
	System();
	//初始化时判断是否显示返回按钮
	showBack.value = getPages();
	updatePageWidth();
	if(options.orderId){
		orderId.value = options.orderId;
		api_returngetOrder()
	}
})
onShow(() => {});
onPageScroll((e)=>{
	const top = e.scrollTop;
	//导航条颜色透明渐变
	if (top <= 50) {
	  headShow.value = false
	} else {
	  if( 50 < top && top <= 200 ){ 
		opacity.value = top / 200
	  }else{
		opacity.value = 1
	  }
	  headShow.value = true
	}
})
onReady(()=>{})
onPullDownRefresh(()=>{})
onReachBottom(()=>{})
</script>

<style lang="scss">
	@import './style.scss';
</style>