<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { accountFormSchema } from './management.data'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { defaultsDeep } from 'lodash-es'
  import { createDevice, getDeviceTypes, updateDevice } from '/@/api/sys/other'
  const emits = defineEmits(['success', 'register'])
  const isUpdate = ref(false)
  const getTitle = computed(() => (!isUpdate.value ? '新增设备' : '编辑设备'))
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      const obj = Object.assign({}, { ...data, ...data?.extends })
      const deviceTypes = await getDeviceTypes()
      await setFieldsValue({
        ...obj,
        agricultural_base_id: obj.base_id,
        type: formatDataByObject(deviceTypes).find((e) => e.label == obj.type)?.value,
      })
    }
  })
  const formatDataByObject = (obj) => {
    const arr: any[] = []
    Object.keys(obj).forEach((e) => {
      arr.push({
        label: obj[e],
        value: e,
      })
    })
    return arr
  }
  const setValue = (keys: any, value: any) => {
    const object = {}
    var last = keys.pop()
    keys.reduce((o, k) => (o[k] = o[k] || {}), object)[last] = value
    return object
  }
  const handleSubmit = async () => {
    // 根据老系统快速添加
    // const obj = {}

    // obj?.result?.records?.forEach(async (e) => {
    //   const { bigdataCameraParams } = e
    //   const params = {
    //     type: 1,
    //     agricultural_base_id: 26,
    //     sn: e.number,
    //     monitoring_point: e.monitoringPoint,
    //     extends: {
    //       ip: bigdataCameraParams.ip,
    //       port: bigdataCameraParams.port + '',
    //       rtsp_url: bigdataCameraParams.url,
    //       username: bigdataCameraParams.username,
    //       password: bigdataCameraParams.password,
    //       passage: bigdataCameraParams.nchannelId + '',
    //     },
    //   }

    //   try {
    //     await createDevice(params)
    //   } catch (e) {
    //     console.log(params)

    //     console.log('错误')

    //     console.log(e)
    //   }
    // })
    // // const values = await validate()

    // return

    try {
      const values = await validate()
      let params = {}
      for (const key in values) {
        params = defaultsDeep({}, params, setValue(key.split('.'), values[key]))
      }
      setDrawerProps({ confirmLoading: true })
      if (values.id) {
        // 修改
        await updateDevice(values.id, params)
      } else {
        // 新增
        await createDevice(params)
      }
      closeDrawer()
      emits('success')
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
