import { NForm, NFormItem, NInput, NSelect, NSpace, NButton, useMessage, NCascader } from 'naive-ui'
import type { TreeSelectOption } from 'naive-ui'
import { defineComponent, onMounted, PropType, reactive, ref } from 'vue'
import { helpCenterCatalogSave, helpCenterCatalogUpdate } from '../../api'

export default defineComponent({
  name: 'city-operation',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    data: {
      type: Object as PropType<any>,
      default: () => {}
    },
    areaList: {
      type: Array as PropType<Array<TreeSelectOption>>,
      default: () => []
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      name: null,
      parentId: 0
    })

    const btnLoading = ref(false)
    const formsRef = ref()
    const subsidyList = ref<any>([])
    const message = useMessage()

    // 提交记录
    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return
        try {
          btnLoading.value = true
          if (props.type === 'add') {
            await helpCenterCatalogSave({ ...forms })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await helpCenterCatalogUpdate({ ...forms, id: props.data.id })
            message.success('修改成功')
          }
          emit('getList')
          emit('close')
          setTimeout(() => {
            btnLoading.value = false
          }, 100)
        } catch {
          //
        }
      })
    }

    onMounted(async () => {
      // 初始化数据
      if (props.type === 'edit') {
        const data = props.data
        forms.name = data.name
        forms.parentId = data.parentId
      }
    })

    // 只能输入数字
    const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value)
    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="auto">
          <NFormItem
            label="分类名称"
            path="name"
            rule={[
              {
                required: true,
                message: '请输入分类名称'
              }
            ]}
          >
            <NInput v-model:value={forms.name} placeholder="请输入分类名称" clearable></NInput>
          </NFormItem>
        </NForm>

        <NSpace justify="end">
          <NButton type="default" onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            type="primary"
            onClick={() => onSubmit()}
            loading={btnLoading.value}
            disabled={btnLoading.value}
          >
            保存
          </NButton>
        </NSpace>
      </div>
    )
  }
})
