import { useWeAppAuthStore, useWorkStore } from '@/common'
import useModel from './model'
import { Apis } from '@/gen/Apis'
import { getApiLoading } from '@/common/libraries/apiLoading'
const auth = useWeAppAuthStore()
const work = useWorkStore()
import { showToastBack, showToast } from '@/common/libraries/naviHelper'
export default {
  init() {
    useModel.formData.value = {
      ...useModel.formData.value,
      reporter_phone: useModel.formData.value.reporter_phone || auth?.data?.user?.phone || '',
      reporter_name: useModel.formData.value.reporter_name || auth?.data?.user?.name || '',
      contact_phone: useModel.formData.value.contact_phone || auth?.data?.user?.phone
    }
    if (work?.selectWorkHouse?.asset_house) {
      useModel.formData.value = {
        ...useModel.formData.value,
        asset_houses_id: work?.selectWorkHouse?.asset_house?.id,
        full_name: work?.selectWorkHouse?.asset_house?.full_name
      }
    } else {
      useModel.formData.value = {
        ...useModel.formData.value,
        asset_houses_id: auth?.data?.selected_house?.id,
        full_name: auth?.data?.selected_house?.full_name
      }
    }
  },
  handleChangeType(e: { value: string }) {
    if (e?.value === 'Complaint') {
      useModel.formData.value.location = ''
    }
    console.log('handleChangeType', e)
  },
  handleSubmit() {
    console.log('handleSubmit', useModel.formData.value)
    if (!useModel?.formData?.value?.type) {
      return showToast('请选择工单类型！')
    }
    // if (useModel?.formData?.value?.type !== 'Complaint' && !useModel?.formData.value?.location) {
    //   return showToast('请选择报事位置！')
    // }
    if (
      useModel?.formData?.value?.location === 'MyHome' &&
      !useModel.formData.value.asset_houses_id
    ) {
      return showToast('请选择房屋！')
    }
    if (
      useModel?.formData?.value?.type === 'Complaint' &&
      !useModel?.formData.value?.complaint_type
    ) {
      return showToast('请选择投诉类型！')
    }
    if (!useModel.formData.value.content) {
      return showToast('请输入问题描述！')
    }
    if (
      useModel?.formData?.value?.location === 'MyHome' &&
      useModel?.formData?.value?.type !== 'Complaint' &&
      !useModel.formData.value.expect_start_time
    ) {
      return showToast('请选择上门时间！')
    }

    if (
      useModel?.formData?.value?.type !== 'Complaint' &&
      (!useModel?.formData.value?.reporter_phone || !useModel?.formData.value?.reporter_name)
    ) {
      return showToast('请输入联系人和电话！')
    }
    getApiLoading(Apis.WorkOrder.HouseWorkOrders.Store, useModel.formData.value).then(res => {
      showToastBack('提交成功！', 1, true)
      console.log(res)
    })
  },
  handleToSelectHouse() {
    uni.navigateTo({
      url: '/INDEX/asset_houses/index?type=work_add'
    })
  },
  handleSwitchChange(e: any) {
    useModel.formData.value.is_anonymous = e?.detail?.value
    console.log(e, 'e')
  }
}
