<template>
  <view class="container safe-area-inset-bottom">
    <MessageNotification />
    <!-- 搜索框 -->
    <!-- <view class="search">
      <u-search placeholder="请输入药品名称" bg-color="#F1F5F9" border-color="#F1F5F9" :show-action="false"
        maxlength="686" height="66" :clearabled="true" shape="round" v-model="keyword" @search="toSearch">
      </u-search>
    </view> -->


    <!-- 头部 -->
    <view class="head">
      <u-tabs :list="list" :is-scroll="true" :current="current" @change="onTabChange"></u-tabs>
    </view>

    <swiper class="order-swiper" :current="current" @change="onSwiperChange">
      <swiper-item v-for="(tab, tabIdx) in list" :key="tabIdx">
        <!-- 适配局部下拉刷新 -->
        <scroll-view
            scroll-y
            class="order-scroll"
            @scrolltolower="onOrderScrollToLower"
            refresher-enabled="true"
            :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresherRefresh"
        >
          <block v-if="Number(current) === tabIdx">
            <!-- 空页  orderList.length==0 -->
            <view class="empty" v-if="orderList.length==0">
              <image src="https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk-client-wx/static/empty/orders.png" mode="aspectFit"></image>
              <text>还没有新的商品订单~</text>
            </view>

            <!-- 药品列表 -->
            <view class="list" v-for="(item,index) in orderList" :key="item.id" @click="next(item.id)">

              <!-- 卡片头部：改为门店位置 + 状态 -->
              <view class="yard">
                <view class="yard_name new_store_header">
                  <text class="iconfont icon-mendian"></text>
                  <!-- 还原原有渲染字段 -->
                  <text class="store_txt">{{item.store.name}}</text>
                  <u-tag
                      :text="item.prescription_type==1?'中药饮片':item.prescription_type==3?'保健食品':item.prescription_type==2?'西(中成)药':item.prescription_type==5?'产品服务包':item.prescription_type==7?'医疗器械':''"
                      :type="item.prescription_type==1?'success':item.prescription_type==3?'warning':'primary'"
                      size="mini"
                      style="margin-left: 16rpx; flex-shrink: 0;"
                      v-if="item.prescription_type"
                  />
                </view>
                <text class="status_txt">{{item.status_string}}</text>
              </view>

              <!-- 订单编号降级 -->
              <view class="order_no_box">
                订单编号：{{item.order_no}}
              </view>


              <!-- 药品信息 -->
              <!-- 中药-颗粒 -->
              <view class="item_info" v-if="item.prescription_type==1">
                <view class="info">
                  <view class="zy_">
                    <!-- 改用原生 v-show 保证安全渲染折叠 -->
                    <view class="zy_it" v-for="(it, idx) in item.items" :key="it.id" v-show="item._expanded || idx < 6">
                      <view class="zy_its">
                        <text class="zy_drug_name">{{it.drug_name}}</text>
                        <text class="zy_drug_num">x{{it.number}}</text>
                      </view>
                    </view>
                  </view>
                </view>

                <!-- 展开按钮 -->
                <view class="expand_box" v-if="item.items && item.items.length > 6" @click.stop="toggleExpand(item)">
                  <text>{{ item._expanded ? '收起药品' : `展开其余 ${item.items.length - 6} 种药品` }}</text>
                  <u-icon :name="item._expanded ? 'arrow-up' : 'arrow-down'" size="24" color="#999"></u-icon>
                </view>

                <view class="it_price">
                  <text class="num">共计：{{item.number}}件</text>
                  <view class="price">
                    总价：￥{{item.total_pay_price}}
                  </view>
                </view>
              </view>


              <!-- 西药 -->
              <view class="item_info" v-if="item.prescription_type==2||item.prescription_type==3||item.prescription_type==4||item.prescription_type==5||item.prescription_type==6||item.prescription_type==7">
                <!-- 改用原生 v-show 保证规格和数据安全渲染 -->
                <view class="info" v-for="(it, idx) in item.items" :key="it.id" v-show="item._expanded || idx < 2">
                  <view class="xy_">
                    <image :src="it.drug_image || 'https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk-client-wx/static/mine/zy_mr.jpg'" mode="aspectFill"></image>
                    <view class="infos">
                      <view class="name">
                        <text class="xy_drug_name">{{it.drug_name}}</text>
                        <view class="">
                          <text class="xy_price" v-if="it.price">￥{{it.price}}</text>
                        </view>
                      </view>
                      <view class="_specit">
                        <!-- 抛弃三元表达式，使用 v-if 防小程序编译 BUG -->
                        <text class="xy_func" v-if="it.drug && it.drug.function && canShowFunction(it.drug, false)">{{ it.drug.function }}</text>
                        <text class="xy_func" v-else></text>
                        <view class="number_specit">
                          <!-- 最原生、最安全的取值方式，确保多商品列表下规格渲染不会被吞 -->
                          <text class="xy_spec" v-if="it.drug && it.drug.specification">{{ it.drug.specification }}</text>
                          <text v-else></text>
                          <text class="xy_num">x{{it.number}}</text>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>

                <!-- 展开按钮 -->
                <view class="expand_box" v-if="item.items && item.items.length > 2" @click.stop="toggleExpand(item)">
                  <text>{{ item._expanded ? '收起药品' : `展开其余 ${item.items.length - 2} 种药品` }}</text>
                  <u-icon :name="item._expanded ? 'arrow-up' : 'arrow-down'" size="24" color="#999"></u-icon>
                </view>

                <view class="it_price">
                  <text class="num">共计：{{item.number}}件</text>
                  <view class="price">
                    总价：￥{{item.total_pay_price}}
                  </view>
                </view>
              </view>

              <!-- 按钮区完全保留你原有的判断逻辑 -->
              <view class="choose_btn">
                <view class="order_info active" v-if="item.is_pay==0 && item.status==0 && item.cancel_status==0"
                      @tap.stop="goCancel(item.id)">
                  取消
                </view>
                <view class="order_info active" v-if="item.status==1 && item.is_pay==1 && item.forbiddenRefund==0"
                      @tap.stop="toCancel(item.id,item.status,refundType)">
                  退款
                </view>
                <view class="order_info active" v-else-if="item.status==6||item.status==7  && item.forbiddenRefund==0"
                      @tap.stop="toCancel(item.id,item.status,refundType)">
                  申请售后
                </view>
                <view class="order_info active" v-else-if="item.status==0 && item.is_pay==0 && item.cancel_status==0"
                      @tap.stop="next(item.id)">
                  支付
                </view>
                <view class="order_info active" v-else-if="item.status==2 && item.is_pay==1" @tap.stop="getReceive(item.id)">
                  签收
                </view>
                <view class="order_info" v-else-if="item.status==9 || item.cancel_status==1">
                  已取消
                </view>
                <view class="order_info" v-else-if="item.status==4">
                  已退款
                </view>
                <view class="order_info color_red"
                      v-else-if="item.refund_status==4 && item.cancel_status==0 && item.is_pay==1">
                  退款被拒
                </view>
                <view class="order_info" v-else-if="item.status>=4&& item.is_pay==1&&item.status<=5 && item.prescription_type==2">
                  {{item.status==5&&'退款中' || item.status==4&&'已退款' }}
                </view>
                <view class="order_info active" v-if="(item.status===2||item.status===6||item.status===7) && item.is_pay==1  && item.cancel_status==0 && item.delivery_method === 0" @tap.stop="toDevilty(item.id)">
                  查看物流
                </view>

              </view>
            </view>
            <u-loadmore :status="loadMoreStatus" v-if="orderList.length!=0" margin-top="30" margin-bottom="30" />
          </block>
        </scroll-view>
      </swiper-item>
    </swiper>
    <u-back-top :scroll-top="scrollTop"></u-back-top>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
import {
  confirmAccept,
  getCancle,
  getOrdlist,
  getPayConfig,
  postRefundBased
} from '../../../request/api/api';
import { canShowFunction } from '@/common/utils/drug';

export default {
  data() {
    return {
      isRefreshing: false, // 局部下拉刷新状态控制
      loadMoreStatus: 'nomore',
      tabChanging: false,
      list: [{
        name: '全部'
      },
        {
          name: '待付款',
        },
        {
          name: '待发货',
        }, {
          name: '待收货',
        },
        {
          name: '已完成'
        },
        {
          name: '退款'
        },
        {
          name: '已取消'
        }
      ],
      keyword: "",
      status: -1,
      current: 0, // 状态
      orderList: [], // 订单列表
      id: "", // 订单id
      page: 1, // 当前页数
      total: "", // 总条数
      last: "", // 总页数
      pageSize: 15, // 每页条数
      order_id: 0, // 订单id
      actionList: [], // 列表,
      actionSheetList: [],
      showed: false,
      reason: "", //原因
      remark: "退货退款", // 备注
      refund_images: "",
      refundType: '',
      scrollTop: 0
    }
  },
  onLoad(e) {
    this.order_id = e.id
    const tabIndex = parseInt(e.index, 10);
    this.change(Number.isNaN(tabIndex) ? 0 : tabIndex);
  },
  computed: {

  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  methods: {
    canShowFunction,
    // scroll-view 专用下拉刷新响应
    onRefresherRefresh() {
      this.isRefreshing = true;
      this.page = 1;
      this.orderList = [];
      this.getList(() => {
        this.isRefreshing = false;
      });
    },
    // 修复小程序中模板内联 $set 导致状态无法折叠回去的兼容性方法
    toggleExpand(item) {
      this.$set(item, '_expanded', !item._expanded);
    },
    // 数量
    // getnum(obj) {
    // 	let list = obj
    // 	let num = 0
    // 	list.map((it) => {
    // 		num += it.number
    // 	})
    // 	return num
    // },
    onTabChange(index) {
      if (this.tabChanging) return;
      this.tabChanging = true;
      this.change(index);
      this.$nextTick(() => {
        this.tabChanging = false;
      });
    },
    onSwiperChange(e) {
      if (this.tabChanging) return;
      this.tabChanging = true;
      this.change(e.detail.current);
      this.$nextTick(() => {
        this.tabChanging = false;
      });
    },
    // 点击切换
    change(index) {
      const tabIndex = Number(index) || 0;
      this.current = tabIndex;
      const statusMap = ['', 'unpaid', 'wait_send', 'wait_accept', 'finished', 'refund', 'cancel'];
      this.status = statusMap[tabIndex] ?? '';
      this.orderList = []
      this.page = 1
      this.getList()
    },

    toDevilty(e) {
      uni.navigateTo({
        url: '/subPackages/shop/logistics?id=' + e
      })
    },

    next(id) {
      this.id = id
      // console.log(id,'id')
      uni.navigateTo({
        url: '/subPackages/my/my-drug/drug-info?id=' + this.id
      })

    },
    // 列表 (增加 callback 供局部下拉刷新调用)
    getList(callback) {
      let list = {
        keyword: this.keyword,
        store_id: uni.getStorageSync('store_id') || '11001',
        type: this.status,
        page: this.page
      }
      getOrdlist({
        method: "post",
        data: list
      }).then((res) => {
        console.log(res, 'lb-res');
        if (res.data.errcode == 0) {
          this.last = res.data.data.pagination.totalPage
          this.total = res.data.data.pagination.total
          this.pageSize = res.data.data.pagination.pageSize
          if (this.page > 1) {
            this.orderList = [...this.orderList, ...res.data.data.list]
          } else {
            this.orderList = res.data.data.list
          }
          console.log(this.orderList, 'lb-lb');
        }
        if (typeof callback === 'function') callback();
      }).catch(() => {
        if (typeof callback === 'function') callback();
      })
    },

    // 搜索
    toSearch() {
      console.log(111);
      this.getList()
    },

    // 点击actionSheet回调
    actionSheetCallback(index) {
      this.reason = this.actionSheetList[index].text;
    },

    // 去支付
    gopay(id) {
      this.id = id
      // 获取支付配置
      getPayConfig({
        method: "post",
        data: {
          order_id: this.id,
          store_id: uni.getStorageSync('store_id') || 11001,
        }
      }).then((res) => {
        // console.log(res, 'pay');

        if (res.data.errcode == 0) {
          if (!res.data.data.appId) {
            setTimeout(() => {
              that.flag = false
              uni.navigateTo({
                url: '/subPackages/my/my-drug/drug-list'
              })
              uni.hideLoading();
            }, 300)
            return;
          }
          uni.requestPayment({
            provider: res.data.data.appId,
            timeStamp: res.data.data.timestamp,
            nonceStr: res.data.data.nonceStr,
            package: res.data.data.package,
            signType: res.data.data.signType,
            paySign: res.data.data.paySign,
            success: function(res) {
              // console.log('success:' + JSON.stringify(res));
              uni.showToast({
                title: '支付成功',
                duration: 1500,
                mask: false,
                icon: 'success'
              })
              this.getList()
            },
            fail: function(err) {
              // console.log('fail:' + JSON.stringify(err));
              uni.showToast({
                title: '支付失败',
                duration: 1500,
                mask: false,
                icon: 'error'
              })
            }
          })
        } else {

          // uni.showToast({
          // 	title: res.data.msg,
          // 	duration: 1500,
          // 	mask: false,
          // 	icon: 'error'
          // })
          this.$refs.uToast.show({
            title: res.data.msg,
            type: 'default',
            icon: false
          })

          setTimeout(() => {
            this.id = id
            uni.navigateTo({
              url: '/subPackages/my/my-drug/drug-info?id=' + this.id
            })
          }, 1800)
        }
        this.getList()
      })
    },
    // 取消订单
    goCancel(id) {
      this.id = id
      getCancle({
        method: "post",
        data: {
          order_id: this.id,
          store_id: uni.getStorageSync('store_id') || 11001,
        }
      }).then((res) => {
        // console.log(res, 'cancle');

        if (res.data.errcode == 0) {
          setTimeout(() => {
            uni.showToast({
              title: '取消成功',
              duration: 1500,
              mask: false,
              icon: 'success'
            })
          }, 400)
          // this.$refs.uToast.show({
          // 	title: '取消成功',
          // 	type: 'default',
          // 	icon: false
          // })
        } else {
          // uni.showToast({
          // 	title: res.data.msg,
          // 	duration: 1500,
          // 	mask: false,
          // 	icon: 'error'
          // })
          this.$refs.uToast.show({
            title: res.data.msg,
            type: 'default',
            icon: false
          })
        }
        this.getList()
      })
    },

    // 退款
    toCancel(id, refundType) {
      this.id = id
      this.refundType = refundType
      uni.navigateTo({
        url: '/subPackages/shop/after-sales?id=' + id + '&&refundType=' + refundType
      })
    },

    // 退款提交 售后
    // payCancel(id, status) {
    // 	if (status == 3) {
    // 		// this.showed = true
    // 		uni.navigateTo({
    // 			url: '/subPackages/shop/after-sales?id=' + id
    // 		})
    // 	}
    // 	postRefundBased({
    // 		method: "post",
    // 		data: {
    // 			order_id: id,
    // 			refund_images: this.refund_images,
    // 			reason: this.reason,
    // 			remark: this.remark,
    // 			store_id: uni.getStorageSync('store_id') || 11001,
    // 		}
    // 	}).then((res) => {
    // 		// console.log(res, 'cancle');
    // 		if (res.data.errcode == 0) {
    // 			uni.showToast({
    // 				title: "退款成功",
    // 				duration: 1500,
    // 				mask: false,
    // 				icon: 'success'
    // 			})
    // 		}

    // 		this.getList()
    // 	})
    // },

    // 签收
    getReceive(id) {
      confirmAccept({
        method: "post",
        data: {
          order_id: id,
          store_id: uni.getStorageSync('store_id') || 11001,
        }
      }).then((res) => {
        // console.log(res, 'cancle');
        if (res.data.errcode == 0) {
          uni.showToast({
            title: "签收成功",
            duration: 1500,
            mask: false,
            icon: 'success'
          })
        }
        this.getList()
      })
    },
    onOrderScrollToLower() {
      this.onReachBottomLoadMore();
    },
    onReachBottomLoadMore() {
      if (this.page < this.last) {
        this.page += 1
        uni.showToast({
          title: "加载中",
          duration: 600,
          mask: false,
          icon: 'loading'
        })
        setTimeout(() => {
          this.getList()
        }, 700)
      }
    }
  },
  // 触底触发
  onReachBottom() {
    this.onReachBottomLoadMore();
  },
  onPullDownRefresh() {
    // console.log("触发了下拉刷新")
    if (this.page <= 1) {
      this.getList()
      setTimeout(() => {
        uni.stopPullDownRefresh()
      }, 300)
    }
    this.page = 1
    this.orderList = []
    this.getList(() => uni.stopPullDownRefresh())

    //重置一下数据
    // this.page = 1
    // //重新发起请求
    // this.getOrder(() => uni.stopPullDownRefresh())
  },
  mounted() {

  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #F8FAFC;
  padding-bottom: env(safe-area-inset-bottom);
  box-sizing: border-box;

  .search {
    width: 750rpx;
    background-color: #fff;
    height: 98rpx;
    margin: 0 auto;
    padding: 16rpx 30rpx;

    .u-search {
      width: 686rpx;
      height: 66rpx;
      margin: 0 auto;
    }
  }

  .empty {
    width: 440rpx;
    height: 393rpx;
    margin: 200rpx auto;
    text-align: center;

    image {
      width: 100%;
      height: 100%;
      z-index: 10;
      margin-bottom: 10rpx;
    }
  }

  .head {
    width: 750rpx;
    height: 80rpx;
    flex-shrink: 0;
    z-index: 99;
  }

  .order-swiper {
    flex: 1;
    height: 0;
    min-height: 0;
  }

  .order-scroll {
    height: 100%;
    box-sizing: border-box;
  }

  /* 以下为卡片优化后的新UI样式 */
  .list {
    width: 702rpx;
    margin: 24rpx auto;
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 28rpx 32rpx;
    box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.03); /* 增加微柔和阴影，去AI感 */
    box-sizing: border-box;

    .yard {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;

      .new_store_header {
        display: flex;
        align-items: center;
        flex: 1;
        overflow: hidden;

        .iconfont {
          color: #333333;
          font-size: 32rpx;
          margin-right: 12rpx;
        }
        .store_txt {
          font-size: 30rpx;
          font-weight: bold;
          color: #333333;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 65%;
        }
      }

      .status_txt {
        font-size: 28rpx;
        font-weight: 500;
        color: #5F71FE;
        flex-shrink: 0;
      }
    }

    .order_no_box {
      font-size: 24rpx;
      color: #9E9FA6;
      padding-bottom: 24rpx;
      border-bottom: 1rpx dashed #F0F0F0; /* 虚线分割更有质感 */
    }

    .item_info {
      margin: 24rpx 0 0 0;

      .info {
        margin-top: 10rpx;

        .zy_ {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          margin: 0 -10rpx;

          .zy_it {
            width: 33.33%;
            padding: 10rpx;
            box-sizing: border-box;

            .zy_its {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .zy_drug_name {
                font-size: 28rpx;
                font-weight: 500;
                color: #333333;
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                padding-right: 10rpx;
              }
              .zy_drug_num {
                font-size: 26rpx;
                font-weight: 400;
                color: #999999;
                flex-shrink: 0;
              }
            }
          }
        }

        .xy_ {
          display: flex;
          margin: 24rpx 0;
          align-items: stretch;

          image {
            width: 136rpx;
            height: 136rpx;
            border-radius: 16rpx;
            margin-right: 24rpx;
            background: #F8FAFC;
            flex-shrink: 0;
          }

          .infos {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            overflow: hidden;

            .name {
              display: flex;
              align-items: flex-start;
              justify-content: space-between;

              .xy_drug_name {
                font-size: 28rpx;
                font-weight: bold;
                color: #333333;
                line-height: 40rpx;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                overflow: hidden;
                flex: 1;
              }
              .xy_price {
                font-size: 28rpx;
                font-weight: 500;
                color: #333333;
                margin-left: 20rpx;
                flex-shrink: 0;
              }
            }

            ._specit {
              font-size: 24rpx;

              .xy_func {
                color: #999999;
                display: block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                margin-top: 6rpx;
              }

              .number_specit {
                margin-top: 8rpx;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .xy_spec {
                  color: #666666;
                  background: #F5F7FA;
                  padding: 2rpx 10rpx;
                  border-radius: 6rpx;
                  font-size: 22rpx;
                }
                .xy_num {
                  color: #999999;
                  font-size: 24rpx;
                }
              }
            }
          }
        }
      }

      .expand_box {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 16rpx 0;
        margin: 16rpx 0;
        background: #FAFAFA;
        border-radius: 12rpx;
        font-size: 24rpx;
        color: #999999;

        text {
          margin-right: 6rpx;
        }
      }

      .it_price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 24rpx;
        padding-top: 20rpx;

        .num {
          font-size: 26rpx;
          color: #666666;
        }

        .price {
          font-size: 32rpx;
          font-family: PingFang SC-Bold, PingFang SC;
          font-weight: bold;
          color: #FF5050;
        }
      }
    }

    .choose_btn {
      display: flex;
      justify-content: flex-end;
      margin-top: 32rpx;
      flex-wrap: wrap;

      .order_info {
        font-size: 26rpx;
        font-weight: 400;
        color: #666666;
        padding: 12rpx 32rpx;
        border: 2rpx solid #E5E5E5;
        border-radius: 64rpx;
        margin-left: 16rpx;
        margin-bottom: 10rpx;
        background: #FFFFFF;
        transition: all 0.2s;
      }

      .color_red {
        color: #FF5050;
        border: 2rpx solid #FF5050;
        background: #FFF5F5;
      }

      .active {
        color: #5F71FE;
        border: 2rpx solid #5F71FE;
        background: #F4F5FF; /* 淡化主色调背景，提升质感 */
        font-weight: 500;
      }
    }
  }
}
</style>