import { ref } from 'vue'
import model from './model'
import { getApiLoading } from '@/common/libraries/apiLoading'
import { Apis } from '@/gen/Apis'
import { showToastBack, showToast } from '@/common/libraries/naviHelper'
const handleGetList = () => {
  model.billsLength.value = 0
  getApiLoading(Apis.Bill.HouseBills.MyBillYearList, model?.formData?.value).then(res => {
    res?.data?.map((i: any) => {
      model.billsLength.value += i?.bills?.length || 0
      i?.bills?.map((k: any) => {
        k.checked = true
        k?.details?.map((m: any) => {
          m.checked = true
        })
      })
    })
    model.items.value = [...model.items.value, ...res?.data]
    setCalculateTotalPrice()
  })
}

const setCalculateTotalPrice = () => {
  //计算总价
  let total_amount = 0
  model?.items?.value?.map((res: any) => {
    res?.bills?.map((k: any) => {
      total_amount += parseFloat(k.amount || 0)
    })
  })
  model.total_amount.value = parseFloat(total_amount.toFixed(2)) //计算总价
}

export default {
  handleGetList,
  handleCollapseClick: (index: number, idx: number, res: any) => {
    let show = model?.items?.value[index]?.bills[idx]?.show
    model.items.value[index].bills[idx].show = !show
    // if(show) return
    // getApiLoading(Apis.Bill.HouseBills.MyBillList, res).then(json => {
    //   json?.data?.map((i:any) => {
    //     i.checked = checked
    //   })
    //   model.items.value[index].bills[idx].list = json?.data || []
    // })
  },
  hanldeSearch: (res: any) => {
    model.items.value = []
    model.formData.value = { ...model?.formData?.value, ...res, page: 1 }
    handleGetList()
  },
  handleCalculatePrice(index: number, idx: number, idxs: number, res: any) {
    if (model.currentTabs.value) {
      return
    }
    let checked = res?.checked
    let total_amount = parseFloat(model?.items?.value[index]?.bills[idx]?.amount)
    let amount = parseFloat(
      model?.items?.value[index]?.bills[idx]?.details[idxs]?.total_payable_amount
    )
    model.items.value[index].bills[idx].details[idxs].checked = !checked
    model.items.value[index].bills[idx].amount = !checked
      ? total_amount + amount
      : total_amount - amount
    if (model.items.value[index].bills[idx].amount <= 0) {
      model.items.value[index].bills[idx].checked = false
    } else {
      if (!model?.items?.value[index]?.bills[idx]?.checked) {
        model.items.value[index].bills[idx].checked = true
      }
    }
    setCalculateTotalPrice() //计算总价
  },
  handleCollapseAllCheckedBtn: async (index: number, idx: number, res: any) => {
    let checked = res?.checked
    let total_amount = 0
    model.items.value[index].bills[idx].checked = !checked
    if (checked) {
      model.items.value[index].bills[idx].amount = 0
    }
    model?.items?.value[index]?.bills[idx]?.details?.map((i: any) => {
      i.checked = !checked
      if (!checked) {
        total_amount += parseFloat(i.total_payable_amount)
      }
      model.items.value[index].bills[idx].amount = total_amount
    })
    setCalculateTotalPrice() //计算总价
    console.log(index, idx)
  },
  handleQuery(res: { asset_houses_id: string; month: string }) {
    uni.navigateTo({
      url: `/INDEX/bill/show/index?asset_houses_id=${res?.asset_houses_id}&month=${res?.month}`
    })
    console.log(res, 'res')
  },
  handleSubmitOrder() {
    let bill_ids: any = []
    let selectedHouseName = '' // 记录选中的房屋名称
    let hasSelectedBills = false // 是否有选中的账单
    console.log(model?.items?.value,'model?.items?.value')

    model?.items?.value?.map((res: any) => {
      res?.bills?.map((k: any) => {
        k?.details?.map((i: any) => {
          if (k?.checked) {
            // 检查是否跨房屋
            if (!hasSelectedBills) {
              // 第一次选中，记录房屋名称
              selectedHouseName = res?.house_name
              hasSelectedBills = true
            } else if (selectedHouseName !== res?.house_name) {
              // 发现跨房屋的情况
              showToast('不能跨房屋提交账单，请选择同一房屋的账单进行支付！')
              return
            }
            bill_ids.push(i?.id)
          }
        })
      })
    })

    console.log(bill_ids)
    if (!bill_ids?.length) {
      showToast('至少选择一个账单！')
      return
    }

    // 再次检查是否跨房屋（双重检查）
    const houseSet = new Set<string>()
    model?.items?.value?.forEach((res: any) => {
      res?.bills?.forEach((k: any) => {
        if (k?.checked) {
          houseSet.add(res?.house_name)
        }
      })
    })

    if (houseSet.size > 1) {
      showToast('不能跨房屋提交账单，请选择同一房屋的账单进行支付！')
      return
    }

    getApiLoading(Apis.HouseOrder.HouseOrders.Store, {
      bill_ids: bill_ids,
      amount: model?.total_amount?.value,
      total_payable_amount: model?.total_amount?.value
    }).then(res => {
      uni.navigateTo({
        url: `/INDEX/pay/index?id=${res?.data?.id}`
      })
    })
  }
}
