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 setCalculateTotalPrice = () => {
  //计算总价
  let total_amount = 0
  useModel?.houseBillsData?.value?.map((res: any) => {
    res?.bills?.map((k: any) => {
      if (k?.checked) {
        total_amount += parseFloat(k.amount || 0)
      }
    })
  })
  useModel.total_amount.value = parseFloat(total_amount?.toFixed(2)) //计算总价
}

const getHouseBills = (type: number) => {
  getApiLoading(Apis.Bill.HouseBills.List, {
    ...useModel?.formData?.value,
    type: type
  }).then((res: any) => {
    console.log(res?.data, 'res')
    res?.data?.map((k: any) => {
      k.checked = true
      k?.bills?.map((i: any) => {
        i.checked = true
      })
    })
    useModel.houseBillsData.value = [...useModel.houseBillsData.value, ...res?.data]
    useModel.metaData.value = res?.meta
    setCalculateTotalPrice()
  })
}

const getHouseWorkOrders = () => {
  getApiLoading(Apis.WorkOrder.HouseWorkOrders.GetHouseWorkOrders, useModel?.formData?.value).then(
    res => {
      useModel.listData.value = [...useModel.listData.value, ...res?.data]
      useModel.metaData.value = res?.meta
    }
  )
}

const getBillIds = () => {
  let bill_ids: number[] = []
  useModel?.houseBillsData?.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
  }
  return bill_ids
}

const getHouseOccupants = () => {
  let ownerArr: any = []
  let noOwnerArr: any = []
  getApiLoading(Apis.Archive.HouseOccupants.List, useModel?.formData?.value).then(res => {
    res.data?.map((i: any) => {
      if (i?.house_relation === 'Owner') {
        ownerArr?.push(i)
      } else {
        noOwnerArr?.push(i)
      }
    })
    useModel.listData.value = [
      { label: '产权人', list: ownerArr },
      { label: '非产权人', list: noOwnerArr }
    ]
  })
}

export default {
  getShow: (id: number) => {
    getApiLoading(Apis.Bill.HouseBills.HouseArrearageAmount, { asset_houses_id: id }).then(res => {
      useModel.showData.value = res?.data
    })
  },
  getHouseBills,
  loadMore(page: number) {
    useModel.formData.value.page = page
    if (useModel.tabsCurrent.value === 0) {
      getHouseBills(1)
    }
    if (useModel.tabsCurrent.value === 1) {
      getHouseWorkOrders()
    }
    if (useModel.tabsCurrent.value === 2) {
      getHouseOccupants()
    }
  },
  handleTabsChange(idx: number) {
    useModel.tabsCurrent.value = idx
    useModel.formData.value.page = 1
    if (idx === 0) {
      useModel.houseBillsData.value = []
      getHouseBills(1)
    }
    if (idx === 1) {
      useModel.listData.value = []
      getHouseWorkOrders()
    }
    if (idx === 2) {
      useModel.listData.value = []
      getHouseOccupants()
    }
  },
  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.showData?.value?.id}&order_id=${res?.data?.id}&time=${res?.data?.created_at}&name=${useModel.showData?.value?.full_name}&amount=${useModel?.total_amount?.value || useModel?.showData?.value?.total_pending_amount}`
        })
      })
    }
  },
  // handleSelect(idx: number) {
  //   let isAll = true
  //   let is = useModel.dataList.value[idx].is_select
  //   useModel.dataList.value[idx].is_select = !is
  //   useModel.dataList.value?.map((res: { is_select: boolean }) => {
  //     if (!res.is_select) {
  //       isAll = false
  //     }
  //   })
  //   useModel.allSelectStatus.value = isAll
  // },
  // handleAllSelect() {
  //   useModel.allSelectStatus.value = !useModel?.allSelectStatus?.value
  //   useModel.dataList.value?.map((res: any) => {
  //     res.is_select = useModel.allSelectStatus.value
  //   })
  // },
  handleSetContact(res: any) {
    //设置常用联系人
    getApiLoading(Apis?.Archive?.HouseOccupants?.ChangeContact, {
      house_occupants_id: res?.id,
      is_contact: !res?.is_contact
    }).then(res => {
      useModel.listData.value = []
      getHouseOccupants()
    })
  },
  handleNotice(res: { id: string; total_pending_amount: string }) {
    let arr = [
      {
        asset_houses_id: res?.id,
        total_unpaid_amount: parseFloat(res?.total_pending_amount)
      }
    ]
    uni.navigateTo({
      url: `/BILL/information_template/index?data=${JSON.stringify(arr)}`
    })
  },
  setCalculateTotalPrice,
  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?.showData?.value?.full_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' }
      })
    }
  }
}
