<script setup lang="ts">
import router from '@/router'

definePage({
  name: 'common-afterSales',
  islogin: true,
  style: {
    navigationBarTitleText: '申请售后',
  },
})
const afterSalesType = ref(1)
const isSeletAllGoods = ref(false)
const selectGoods = ref<number[]>([])
const fileList = ref<{ url: string }[]>([])
const showReson = ref(false)
const resonId = ref()
const resonName = ref('请选择退款原因')
const resonList = [
  { id: 1, name: '暂不需要商品(买错/多买/漏买)' },
  { id: 2, name: '冰品融化' },
  { id: 3, name: '订单中有商品发错' },
  { id: 4, name: '商品斤两不足' },
  { id: 5, name: '商品临期到期' },
  { id: 6, name: '商品破损/包装破损' },
  { id: 7, name: '其他' },
]
const orderList = ref<Api.xsbOmsOrderItem[]>([])
const remark = ref('')
onLoad((options: any) => {
  orderList.value = JSON.parse(options.order)
  orderList.value = orderList.value.map((item: Api.xsbOmsOrderItem) => {
    item.num = 1
    return item
  })
})
const refunMoney = ref(0)
const isSubmit = ref(false)

async function handleSubmit() {
  console.log(fileList.value, 'fileList')
  if (!selectGoods.value.length) {
    useGlobalToast().show({ msg: '请选择需要退款的商品' })
    return
  }
  if (!resonId.value) {
    useGlobalToast().show({ msg: '请选择退款原因' })
    return
  }
  if (!orderList.value[0].orderNumber) {
    useGlobalToast().show({ msg: '订单数据异常' })
    return
  }
  isSubmit.value = true
  try {
    const res = await cathcApplRefund()
    router.push({ name: 'common-afterSalesDetail', params: { refundNumber: res } })
    isSubmit.value = false
  }
  catch (e) {
    isSubmit.value = false
    console.log(e)
  }
  // router.push({ name: 'common-afterSalesDetail' })
}

function cathcApplRefund(): Promise<string> {
  uni.showLoading({ mask: true })
  return new Promise((resolve, reject) => {
    const filerData = orderList.value.filter(it => selectGoods.value.includes(Number(it.skuId)))
    Apis.xsb.applyRefund({
      data: {
        orderNumber: orderList.value[0].orderNumber,
        businessType: 1,
        applyType: afterSalesType.value,
        refundType: 2,
        buyerReason: resonName.value,
        buyerDesc: remark.value,
        photoFiles: fileList.value.map(it => it.url).join(','),
        orderRefundSkuList: filerData.map((it) => {
          return {
            orderItemId: it.orderItemId,
            productCount: it.num,
          }
        }),
      },
    }).then((res) => { resolve(res.data) }).catch((err) => {
      reject(err)
    }).finally(() => { uni.hideLoading() })
  })
}

function handleSelectReson() {
  if (!resonId.value)
    return uni.showToast({ title: '请选择退款原因', icon: 'none' })
  showReson.value = false
  resonName.value = resonList.find(item => item.id === resonId.value)?.name || '请选择退款原因'
}

function handleSelectGoods() {
  console.log(orderList.value, 'orderList', selectGoods.value)
  if (selectGoods.value.length === orderList.value.length) {
    isSeletAllGoods.value = true
  }
  else {
    isSeletAllGoods.value = false
    refunMoney.value = 0
  }
}
function handleChangeAll() {
  console.log(isSeletAllGoods.value, 'isSeletAllGoods')
  if (isSeletAllGoods.value) {
    selectGoods.value = orderList.value.map(it => it.skuId) as number[]
  }
  else {
    selectGoods.value = []
    refunMoney.value = 0
  }
}
watch(() => [selectGoods.value, orderList.value], () => {
  if (selectGoods.value.length) {
    getReufndMoney()
  }
})
async function getReufndMoney() {
  console.log(orderList.value[0].orderNumber, 'orderList.value')
  const filerData = orderList.value.filter(it => selectGoods.value.includes(Number(it.skuId)))
  const res = await Apis.xsb.calculateMoney({ data: {
    orderNumber: String(orderList.value[0].orderNumber),
    orderRefundSkuList: filerData.map((it) => {
      return {
        orderItemId: it.orderItemId,
        productCount: it.num,
      }
    }),
  } })
  refunMoney.value = res.data
}
function handleChangeMoney() {
  if (selectGoods.value.length) {
    getReufndMoney()
  }
}
</script>

<template>
  <page-meta :page-style="showReson ? 'overflow: hidden;' : '' " />
  <view class="page-xsb">
    <view class="box-border w-full flex items-center bg-#f8e3ca px24rpx py12rpx">
      <wd-icon name="info-circle-filled" size="22px" color="#FF941A" />
      <view class="ml16rpx text-28rpx">
        部分退款时，有积分消费的，优先返还积分。
      </view>
    </view>
    <view class="px24rpx py24rpx">
      <view class="rounded-16rpx bg-white px24rpx py28rpx">
        <view class="mb24rpx text-32rpx font-semibold">
          售后类型
        </view>
        <wd-radio-group v-model="afterSalesType" shape="dot" inline>
          <wd-radio :value="1">
            <view>
              <view class="text-left text-28rpx font-semibold">
                我要退款
              </view>
              <view class="mt16rpx text-24rpx text-#AAAAAA">
                没收到货，货已收到货与商家协商后无需退货只退款
              </view>
            </view>
          </wd-radio>
          <view class="mt24rpx">
            <wd-radio :value="2">
              <view>
                <view class="text-left text-28rpx font-semibold">
                  我要退货退款
                </view>
                <view class="mt16rpx text-24rpx text-#AAAAAA">
                  已收到货，需要退还已收到的商品
                </view>
              </view>
            </wd-radio>
          </view>
        </wd-radio-group>
      </view>
      <view class="mt20rpx rounded-16rpx bg-white px24rpx py28rpx">
        <view class="flex items-center justify-between">
          <view class="text-32rpx font-semibold">
            退款商品
          </view>
          <view class="text-28rpx text-#FF4D3A font-semibold">
            退款金额：￥{{ refunMoney }}
          </view>
        </view>
        <view class="mt24rpx">
          <wd-checkbox v-model="isSeletAllGoods" @change="handleChangeAll">
            全选
          </wd-checkbox>
        </view>
        <view class="mt24rpx h2rpx w-full bg-#F0F0F0" />
        <view class="goods mt24rpx">
          <CollapsePanel :line-height="150">
            <wd-checkbox-group v-model="selectGoods" @change="handleSelectGoods">
              <template v-for="item in orderList" :key="item.skuId">
                <view class="flex items-center justify-between">
                  <wd-checkbox :model-value="item.skuId" />
                  <view class="box-border w-full flex items-center">
                    <image :src="item.pic" class="h120rpx w120rpx flex-shrink-0" />
                    <view class="ml20rpx box-border flex-1">
                      <view class="w-full flex justify-between">
                        <view class="max-w-320rpx whitespace-pre-wrap break-words break-all text-28rpx">
                          {{ item.prodName }}
                        </view>
                        <view class="w30% flex-shrink-0 text-32rpx text-#FF4D3A font-semibold">
                          ￥{{ item.productTotalAmount }}
                        </view>
                      </view>
                      <view class="text-24rpx text-#AAAAAA">
                        规格：{{ item.spec }}
                      </view>
                      <view class="flex items-center justify-between">
                        <view class="text-24rpx text-#AAAAAA">
                          单价：￥{{ item.price }}
                        </view>
                        <view>
                          <wd-input-number v-model="item.num" :max="item.prodCount" :min="1" @change="handleChangeMoney" />
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="my20rpx h2rpx w-full bg-#F0F0F0" />
              </template>
            </wd-checkbox-group>
          </CollapsePanel>
        </view>
      </view>
      <view class="mt20rpx rounded-16rpx bg-white px24rpx py28rpx">
        <view class="flex items-center justify-between">
          <view class="text-32rpx font-semibold">
            退款原因
          </view>
          <view class="flex items-center text-28rpx" @click="showReson = true">
            <view class="text-#AAAAAA">
              {{ resonName }}
            </view> <wd-icon name="arrow-right" size="18px" color="#aaa" />
          </view>
        </view>
        <view class="mt20rpx rounded-16rpx bg-#F6F6F6 p24rpx">
          <wd-textarea v-model="remark" placeholder="请填写退款原因" show-word-limit :maxlength="200" />
          <view class="upload mt18rpx">
            <Zupload v-model:value="fileList" />
          </view>
        </view>
      </view>
    </view>
    <Zpopup v-model="showReson">
      <view class="p24rpx">
        <view class="w-full text-center text-32rpx font-semibold">
          选择退款原因
        </view>
        <view class="mt20rpx flex items-center rounded-16rpx bg-#f8e3ca px24rpx py12rpx">
          <wd-icon name="info-circle-filled" size="22px" color="#FF941A" />
          <view class="ml16rpx text-28rpx">
            部分退款时，有积分消费的，优先返还积分。
          </view>
        </view>
        <view class="mt20rpx rounded-32rpx bg-white p24rpx">
          <view class="mb20rpx text-28rpx font-semibold">
            请选择退款原因 <text class="text-#AAAAAA">
              (必选)
            </text>
          </view>
          <wd-radio-group v-model="resonId" shape="dot">
            <wd-radio v-for="item in resonList" :key="item.id" :value="item.id">
              <view class="w-full text-24rpx">
                {{ item.name }}
              </view>
            </wd-radio>
          </wd-radio-group>
        </view>
      </view>
      <template #footer>
        <wd-button block @click="handleSelectReson">
          确定
        </wd-button>
      </template>
    </Zpopup>
    <view class="h200rpx" />
    <view
      class="ios fixed bottom-0 z-10 box-border w-full w-full rounded-t-32rpx bg-white px32rpx pt-16rpx"
    >
      <wd-button block :loading="isSubmit" @click="handleSubmit">
        提交
      </wd-button>
    </view>
  </view>
</template>

<style scoped lang="scss">
.page-xsb {
  :deep() {
    .goods .wd-checkbox{
      display: flex;
      align-items: center;
      .wd-checkbox__shape{
        flex-shrink: 0;
      }
      .wd-checkbox__label {
      width:100%;
      .wd-checkbox__txt{
        width: 100%;
      }
    }
    }
    .wd-textarea{
      background: #F6F6F6 !important;
      .wd-textarea__value{
        background: #F6F6F6 !important;
      }
      .wd-textarea__count{
        background: #F6F6F6 !important;
      }
    }

  }
}
</style>
