<template>
  <view class="container">
    <view class="title">请选择退款原因</view>
    <scroll-view class="scrollView" scroll-y>
      <radio-group v-if="comePage !== 'food'" class="radio-group" @change="onReasonChange">
        <label class="radio-item" v-for="(item, index) in reasons" :key="index" :style="{
          alignItems: index + 1 === reasons.length ? 'flex-start' : '',
        }">
          <radio :value="item.value" :checked="item.checked" />
          <text>{{ item.label }}</text>
          <!-- <textarea
            v-if="item.value === 'other'"
            v-model="otherReason"
            class="other-input"
            placeholder="请输入具体原因"
            :disabled="selectedReason !== 'other'"
          /> -->
        </label>
      </radio-group>

      <view class="radio-group" v-else>
        <text style="display: block;margin-bottom: 16rpx;'">{{ item.label }}</text>
        <textarea v-model="otherReason" class="other-input" placeholder="请输入具体原因"
          :disabled="selectedChildrenReason !== selectedChildrenReason" />
      </view>

      <radio-group v-if="childrenReasons && childrenReasons.length > 0" class="radio-group" style="margin-top: 40rpx"
        @change="onChildrenReasonChange">
        <label class="radio-item" v-for="(item, index) in childrenReasons" :key="index" :style="{
          alignItems:
            item.value === 2099 || item.value === 1099 ? 'flex-start' : '',
        }">
          <radio :value="item.value" :checked="item.checked" />

          <view v-if="item.value === 2099 || item.value === 1099">
            <text style="display: block;margin-bottom: 16rpx;'">{{ item.label }}</text>
            <textarea v-model="otherReason" class="other-input" placeholder="请输入具体原因"
              :disabled="selectedChildrenReason !== selectedChildrenReason" />
          </view>
          <text v-else>{{ item.label }}</text>
        </label>
      </radio-group>
    </scroll-view>
    <view class="submit-btn" @click="onSubmit"> 确认退款 </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      selectedReason: "",
      selectedReasonText: "", // 选择的父集名称
      otherReason: "",
      reasons: [],
      orderInfo: {}, // 订单详情先拿到
      orderInternal: "", // 退款的id
      sellchildid: "", // 退款的id
      childrenReasons: [], // 子集原因列表
      selectedChildrenReason: "", // 选择的子集
      selectedChildrenText: "", // 选择的子集名称
      isClick: false,// 判断是否已经点击了 退款
      comePage: "",// 如果值为food  页面就显示一个原因即可
    };
  },
  computed: {
    ...mapGetters(["user"]),
  },
  async onLoad(query) {
    console.log('queryqueryquery', query)
    // 拿到要退款的订单id
    if (query.salebillId) {
      this.orderInternal = query.salebillId;
    }
    if (query.saleBillChildId) {
      this.sellchildid = query.saleBillChildId;
    }
    if (query.comePage) {
      this.comePage = query.comePage
    }
    // 退货的枚举类型
    this.handleServiceType();
    // 订单的详情
    await this.getOrderType();
    this.$utils.addUserBehaviorNew();
  },
  methods: {
    // 退货的枚举类型
    async handleServiceType() {
      uni.showLoading({
        title: "加载中...",
      });
      const data = await this.$api.$get(
        "/EShangApiMain/FrameWork/GetFieldEnumTree",
        { FieldExplainField: "AFTERSALE_TYPE" }
      );
      let list = this.$utils.wrapTreeNode(data.Result_Data.List);
      this.reasons = list;
      uni.hideLoading();
    },
    // 获取订单状态
    async getOrderType() {
      let _this = this;
      const res = await _this.$api
        .getCoop({
          action_type: "GetOrderDetail",
          salebillId: _this.orderInternal,
          // saleBillChildId: _this.sellchildid ? _this.sellchildid : "",
        })
      console.log('resresresresres', res)
      // .then((res) => {
      if (res.ResultCode === "100") {
        let _data = res.Data;

        if (_data.List && _data.List.length > 0) {
          _data.List.forEach((item) => {
            item.AVERAGE_PRICE = item.AVERAGE_PRICE.toFixed(2)
          })
        }

        _this.orderInfo = _data;
        console.log('_this.orderInfo_this.orderInfo_this.orderInfo', _this.orderInfo)
      }
      // });
    },

    onChildrenReasonChange(e) {
      this.selectedChildrenReason = Number(e.detail.value);

      let list = this.childrenReasons.filter(
        (item) => item.value === Number(e.detail.value)
      );

      this.selectedChildrenText = list[0].label;

      if (
        this.selectedChildrenReason !== "2099" &&
        this.selectedChildrenReason !== "1099"
      ) {
        this.otherReason = "";
      }
    },
    onReasonChange(e) {
      this.selectedReason = e.detail.value;
      let list = this.reasons.filter(
        (item) => item.value === Number(e.detail.value)
      );

      let childrenList = [];
      if (list && list.length > 0) {
        childrenList = list[0].children;
        this.selectedReasonText = list[0].label;
      }

      this.childrenReasons = childrenList;
      this.$forceUpdate();

      // if (this.selectedReason !== "other") {
      //   this.otherReason = "";
      // }
    },
    async onSubmit() {
      if (this.isClick) {
        return
      }
      if (this.comePage !== 'food') {
        if (!this.selectedReason) {
          uni.showToast({
            title: "请选择退款原因",
            icon: "none",
          });
          return;
        }
        if (!this.selectedChildrenReason) {
          uni.showToast({
            title: "请选择具体原因",
            icon: "none",
          });
          return;
        }
      }


      if (
        (this.selectedChildrenReason === 2099 ||
          this.selectedChildrenReason === 1099) &&
        !this.otherReason
      ) {
        uni.showToast({
          title: "请输入具体原因",
          icon: "none",
        });
        return;
      }


      this.isClick = true

      let _this = this;

      let openId = uni.getStorageSync("openId");
      let reqOrder = {
        action_type: "ScanOrder",
        salebillType: 3999,
        provinceCode: _this.user.PROVINCE_CODE || "530000",
        serverpartShopId: "5634",
        salebillDesc: this.comePage !== 'food' ? `${this.selectedReasonText}:${this.selectedChildrenText === "其他原因"
          ? this.otherReason
          : this.selectedChildrenText
          }` : this.otherReason,
        wechatOpenId: openId || "",
        oriSalebillCode: _this.orderInfo.SALEBILL_CODE,
        wechatUnionId: _this.user.USER_UNIONID || "",
        takeType: _this.orderInfo.TAKE_TYPE,
        t_saleorderdetail: JSON.stringify(_this.orderInfo.List),
        requestType: "application/x-www-form-urlencoded",
      };
      console.log('reqOrderreqOrderreqOrder', reqOrder)
      // return
      const orderData = await _this.$api.postCoop(reqOrder);

      if (orderData.ResultCode === "100") {
        const req = {
          action_type: "UpdateOrderState",
          action_data: _this.orderInfo.SALEBILL_ID,
          SALEBILL_STATE: 8000,
        };
        const data = await _this.$api.getCoop(req);
        // 提交退款申请逻辑
        uni.showToast({
          title: "退款申请已提交",
          icon: "success",
        });
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 1000);
        // if (data.error === 1) {
        //   _this.getOrderType();
        // }
      } else {
        uni.showToast({
          title: orderData.ResultDesc,
          icon: "none",
        });
        this.isClick = false
      }



    },
  },
};
</script>

<style lang="less" scoped>
.container {
  padding: 32rpx;
  background: #fff;
}

.title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.scrollView {
  width: 100%;
  height: calc(100vh - 84px - 37px - 46px);
  padding: 16px 0;
}

.scrollView ::-webkit-scrollbar {
  display: none;
  width: 0;
}

.radio-group {
  // margin-bottom: 30px;
  // height: 100%;
  padding: 12rpx;
  border-radius: 8rpx;
  background: #f6f6f6;
  box-sizing: border-box;
  padding-left: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;

  &:last-child {
    border-bottom: none;
  }

  text {
    margin-left: 10px;
    font-size: 14px;
  }

  .other-input {
    flex: 1;
    margin-left: 10px;
    padding: 5px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;

    &:disabled {
      background-color: #f5f5f5;
      border-color: #eee;
    }
  }
}

.submit-btn {
  width: 90vw;
  padding: 22rpx 0;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: "PingFangSC";
  font-weight: 400;
  font-size: 32rpx;
  color: #ffffff;
  line-height: 44rpx;
  text-align: right;
  font-style: normal;
  background: #1e9b4a;
  border-radius: 8rpx;
  position: fixed;
  bottom: 40px;
  left: 5vw;
}
</style>
