import { getApiLoading } from '@/common/libraries/apiLoading'
import { Apis } from '@/gen/Apis'
import useModel from './model'

const getList = () => {
  getApiLoading(Apis.Meter.HouseMeters.List, useModel?.formData?.value).then(res => {
    useModel.listData.value = [...useModel.listData.value, ...res?.data]
    useModel.metaData.value = res?.meta
  })
}


const getMenuList = () => {
  getApiLoading(Apis.Asset.AssetHouses.SelectPermissionUnit, useModel?.formData?.value).then(res => {
    useModel.listMenuData.value = res?.data
    if(res?.data?.length){
      if(!useModel?.currentTabs?.value){
          useModel.formData.value.asset_units_id = res?.data?.[0]?.id
      }
      handleTabSearch()
    }
  })
}
const handleTabSearch = () => {
  useModel.formData.value.page = 1
  useModel.listData.value = []
  getList()
}
export default {
  getList,
  getMenuList,
  handleSearch(){
    handleTabSearch()
  },
  handleChangeUsageTypeFilter(e:{value?:string}){
    useModel.formData.value.usage_type = e?.value || undefined
    handleTabSearch()
    console.log('e', e)
  },
  handleChangeOverdueDaysFilter(e:{value?:string,color:string}){

    if(useModel?.formData?.value?.overdue_days === e?.value){
      useModel.formData.value.overdue_days =  undefined
      useModel.activeColor.value = ""
    } else {
      useModel.formData.value.overdue_days = e?.value
      useModel.activeColor.value = e?.color
    }
    handleTabSearch()
  },
  handleChangeFilter(e:any){
    useModel.formData.value ={
      ...useModel.formData.value,
      ...e,
      page:1,
    }
    useModel.listData.value = []
    getList()
  },
  handleChangeFilterReadingStatus(e:any){
    useModel.formData.value ={
      ...useModel.formData.value,
      reading_status: e?.value || undefined,
    }
    useModel.listData.value = []
    getList()
  },
  handleChangeTabs(idx: number, e: any) {
    useModel.currentTabs.value = idx
    if(idx){
      useModel.formData.value = {
        meter_type: e?.value,
        asset_projects_id: useModel?.formData?.value?.asset_projects_id,
      }
    } else {
      useModel.formData.value = {
        meter_type: e?.value,
        asset_projects_id: useModel?.formData?.value?.asset_projects_id,
        asset_units_id: useModel?.listMenuData?.value?.[0]?.id,
      }
    }

    handleTabSearch()
  },
  handleLoad(res: any) {
    useModel.formData.value.page = res?.page
    getList()
  },
  handleToAdd(i: any) {
    uni.navigateTo({
      url: `/ME/instrument/add/index?id=${i?.id}`
    })
  },
  handleToLog(){
    uni.navigateTo({
      url: `/ME/instrument/log/index?id=`
    })
  }
}
