import { useWeAppAuthStore } from '@/common'
import { getApiLoading } from '@/common/libraries/apiLoading'
import { showToast } from '@/common/libraries/naviHelper'
import {
  navigateToMiniProgram,
  sendChatMessage
} from '@/common/libraries/sendWxWork'
import { Apis } from '@/gen/Apis'
import useModel from './model'
const auth = useWeAppAuthStore()
const handleGetList = () => {
  getApiLoading(Apis.Bill.HouseBills.List, { ...useModel?.formData?.value, type: 1 }).then(res => {
    res?.data?.map((i: any) => {
      i.checked = true
      i?.bills?.map((k: any) => {
        k.checked = true
      })
    })
    useModel.items.value = [...useModel.items.value, ...res?.data]
    useModel.metaData.value = res?.meta
  })
}

const getBillIds = () => {
  let bill_ids: number[] = []
  useModel?.items?.value?.map((res: any) => {
    if (res?.bills?.length) {
      res?.bills?.map((i: { id: number; checked: boolean }) => {
        if (i?.checked) {
          bill_ids?.push(i?.id)
        }
      })
    }
  })
  if (!bill_ids?.length) {
    showToast('请至少选择一个月账单！')
    return false
  }
  //计算总价
  setCalculateTotalPrice()
  return bill_ids
}

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

export default {
  handleGetList,
  handleCollapseClick: (index: number, res: any) => {
    let show = useModel?.items?.value[index]?.show
    useModel.items.value[index].show = !show
  },
  hanldeSearch: (res: any) => {
    useModel.items.value = []
    useModel.formData.value = { ...useModel?.formData?.value, ...res, page: 1 }
    handleGetList()
  },
   handleLoadMore(params: { page: number }) {
    useModel.formData.value.page = params?.page
    handleGetList()
  },
  handleCalculatePrice(index: number, idx: number, res: any) {
    let checked = res?.checked
    useModel.items.value[index].bills[idx].checked = !checked
    if (checked) {
      useModel.items.value[index].checked = false
    } else {
      let allChecked = useModel.items.value[index].bills?.every(
        (item: { checked: boolean }) => item?.checked
      )
      useModel.items.value[index].checked = allChecked
      console.log(allChecked)
    }
  },
  handleCollapseAllCheckedBtn: async (index: number, res: any) => {
    let checked = res?.checked
    useModel.items.value[index].checked = !checked
    useModel?.items?.value[index]?.bills?.map((i: any) => {
      i.checked = !checked
    })
  },
  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 = []
    useModel?.items?.value?.map((res: any) => {
      res?.bills?.map((k: any) => {
        k?.details?.map((i: any) => {
          if (k?.checked) {
            bill_ids.push(i?.id)
          }
        })
      })
    })
    if (!bill_ids?.length) {
      showToast('至少选择一个账单！')
      return
    }
    getApiLoading(Apis.HouseOrder.HouseOrders.Store, {
      bill_ids: bill_ids,
      amount: useModel?.total_amount?.value,
      total_payable_amount: useModel?.total_amount?.value
    }).then(res => {
      uni.navigateTo({
        url: `/INDEX/pay/index?id=${res?.data?.id}`
      })
    })
  },
  handleQRCode() {
    let bill_ids: number[] = getBillIds() || []
    if (bill_ids?.length) {
      getApiLoading(Apis.HouseOrder.HouseOrders.Store, {
        bill_ids: bill_ids || [],
        total_payable_amount: useModel?.total_amount?.value,
        amount: useModel?.total_amount?.value
      }).then(res => {
        uni.navigateTo({
          url: `/BILL/poster/index?id=${useModel.formData?.value?.asset_houses_id}&order_id=${res?.data?.id}&time=${res?.data?.created_at}&name=${useModel.formData?.value?.name}&amount=${useModel?.total_amount?.value || useModel?.total_amount?.value}`
        })
      })
    }
  },
  handleSelectExternalContact() {
    let bill_ids: number[] = getBillIds() || []
    console.log(bill_ids, 'bill_ids')
    if (!bill_ids?.length) {
      return false
    }
    if (auth?.data?.environment === 'wxwork') {
      uni.qy.getContext({
        success: function (res: any) {
          let entry = res.entry //返回进入小程序的入口类型
          if (entry === 'single_chat_tools') {
            sendChatMessage({
              page: `/INDEX/bill_order/index.html?bill_ids=${JSON.stringify(bill_ids)}&house_id=${useModel.formData.value.asset_houses_id}`,
              title: `分享给您${useModel?.formData?.value?.name}物业账单`,
              imgUrl:
                'https://pay-prod-1369486729.cos.ap-guangzhou.myqcloud.com/uploads/cs-test/01K5B5RY2TQQAJ1GT2RZSK426V.jpg'
            })
          } else {
            navigateToMiniProgram({
              path: '/pages/forward/index?source=OutstandingFeeList',
              envVersion: 'develop',
              extraData: { source: 'OutstandingFeeList' }
            })
          }
        }
      })
    } else {
      navigateToMiniProgram({
        path: '/pages/forward/index?source=OutstandingFeeList',
        envVersion: 'develop',
        extraData: { source: 'OutstandingFeeList' }
      })
    }
  }
}
