import { Apis } from '@/gen/Apis'
import useModel from './model'
import { useWeAppAuthStore } from '@/common'
import { getApiLoading } from '@/common/libraries/apiLoading'
import { showCurrentTime } from '@/common/libraries/day'
const auth = useWeAppAuthStore()

const getList = () => {
  getApiLoading(Apis.Visitor.VisitorApplies.Codes, {}).then(res => {
    let data = res?.data?.map((i: any) => {
      return {
        asset_house_id: i?.asset_house?.id,
        full_name: i?.asset_house?.full_name,
        id: i?.id,
        renovation_workers: i?.renovation_workers?.length
          ? i?.renovation_workers[0]?.worker_photo?.[0]
          : {},
        remark: i?.remark,
        visit_start_time: i?.visit_start_time,
        code_expired_at: i?.code_expired_at,
        type: 2
      }
    })
    useModel.listData.value = [...useModel.listData.value, ...data]
    if (useModel.listData.value?.length) {
      useModel.currentHouse.value = useModel?.listData?.value[0]
       getQrCode()
      // if (useModel?.currentHouse?.value?.type === 2) {
      //   getQrCode()
      // }
      // if (useModel?.currentHouse?.value?.type === 1) {
      //   getQrCode()
      // }
    }
  })
}

const getQrCode = () => {
  let url = useModel?.currentHouse?.value?.type === 2?Apis.Visitor.VisitorApplies.VisitorQrCode:Apis.Visitor.VisitorApplies.ResidentQrCode
  getApiLoading(url, {
    id: useModel?.currentHouse?.value?.id,
    asset_houses_id: useModel?.currentHouse?.value?.id
  }).then(res => {
    useModel.qrCode.value = res?.data?.qr_code
    console.log(res)
  })
}

const getHouseList = () => {
  getApiLoading(Apis.Archive.HouseOccupants.List, {}).then(res => {
    let data = res?.data?.map((i: any) => {
      return {
        ...i?.asset_house,
        house_relation: i?.house_relation,
        type: 1
      }
    })
    useModel.listData.value = data || []
    getList()
  })
}

const getShowCurrentTime = () => {
  useModel.showCurrentTime.value = showCurrentTime()
  useModel.timeoutObj.value = setTimeout(() => {
    getShowCurrentTime()
  }, 1000)
}

export default {
  getList,
  getHouseList,
  getQrCode,
  getShowCurrentTime
}
