<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { FormSchema } from '/@/components/Table'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { getDeviceTypes, getAgriculturalBasic, createDevice } from '/@/api/sys/other'
  import { defaultsDeep } from 'lodash-es'

  const formSchema: FormSchema[] = [
    {
      field: 'type',
      component: 'Select',
      label: '设备类型',
      required: true,
      componentProps: {
        placeholder: '',
        options: [],
      },
    },
    {
      field: 'agricultural_base_id',
      component: 'Select',
      label: '基地',
      required: true,
      componentProps: {
        placeholder: '',
        options: [],
      },
    },
    {
      field: 'sn',
      label: '设备编号',
      required: true,
      component: 'Input',
    },
    {
      field: 'monitoring_point',
      label: '监控点',
      required: true,
      component: 'Input',
    },
    {
      field: 'extends.ip',
      label: '设备IP',
      required: true,
      component: 'Input',
      ifShow: ({ values }) => {
        return !!(values.type == 1)
      },
    },
    {
      field: 'extends.port',
      label: '设备端口',
      required: true,
      component: 'Input',
      ifShow: ({ values }) => {
        return !!(values.type == 1)
      },
    },
    {
      field: 'extends.rtsp_url',
      label: 'RTSP地址',
      required: true,
      component: 'Input',
      ifShow: ({ values }) => {
        return !!(values.type == 1)
      },
    },
    {
      field: 'extends.username',
      label: '设备登录名',
      required: true,
      component: 'Input',
      ifShow: ({ values }) => {
        return !!(values.type == 1)
      },
    },
    {
      field: 'extends.password',
      label: '设备登录密码',
      required: true,
      component: 'Input',
      ifShow: ({ values }) => {
        return !!(values.type == 1)
      },
    },
    {
      field: 'extends.passage',
      label: '设备播放通道',
      required: true,
      component: 'Input',
      ifShow: ({ values }) => {
        return !!(values.type == 1)
      },
    },
  ]

  function formatDataByObject(obj): any[] {
    const arr: any[] = []
    Object.keys(obj).forEach((e) => {
      arr.push({
        label: obj[e],
        value: e,
      })
    })
    return arr
  }

  function formatDataByArray(arr, label = 'name', value = 'id'): any[] {
    return arr.reduce((p, c) => {
      p.push({
        label: c[label],
        value: c[value],
      })
      return p
    }, [])
  }

  function setValue(keys, value) {
    const object = {}
    var last = keys.pop()
    keys.reduce((o, k) => (o[k] = o[k] || {}), object)[last] = value
    return object
  }

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true)

      const deviceTypesData = ref<[]>([])
      const agriculturalBasicData = ref<[]>([])

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 110,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      })

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields()
        setDrawerProps({ confirmLoading: false })
        isUpdate.value = !!data?.isUpdate

        if (unref(deviceTypesData).length === 0) {
          deviceTypesData.value = await getDeviceTypes()
          updateSchema({
            field: 'type',
            componentProps: {
              options: formatDataByObject(deviceTypesData.value),
            },
          })
        }
        if (unref(agriculturalBasicData).length === 0) {
          agriculturalBasicData.value = await getAgriculturalBasic()
          updateSchema({
            field: 'agricultural_base_id',
            componentProps: {
              options: formatDataByArray(agriculturalBasicData.value),
            },
          })
        }

        if (unref(isUpdate)) {
          console.log(data.record)

          // setFieldsValue({
          //   ...data.record,
          // })
        }
      })

      const getTitle = computed(() => (!unref(isUpdate) ? '新增设备' : '编辑设备'))

      async function handleSubmit() {
        try {
          const values = await validate()

          let params = {}
          for (const key in values) {
            params = defaultsDeep({}, params, setValue(key.split('.'), values[key]))
          }
          setDrawerProps({ confirmLoading: true })
          if (!unref(isUpdate)) {
            await createDevice(params)
          } else {
            await createDevice(params)
          }
          closeDrawer()
          emit('success')
        } finally {
          setDrawerProps({ confirmLoading: false })
        }
      }

      return {
        registerForm,
        registerDrawer,
        getTitle,
        handleSubmit,
      }
    },
  })
</script>
