import {
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NSpace,
  NButton,
  NTreeSelect,
  useMessage,
  NRadioGroup,
  NRadio
} from 'naive-ui'
import type { TreeSelectOption } from 'naive-ui'
import { defineComponent, onMounted, PropType, reactive, ref } from 'vue'
import { sysApplicationPage, sysApplicationSave, sysApplicationUpdate } from '../api'
export default defineComponent({
  name: 'city-operation',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    parentId: {
      type: Number,
      default: 0
    },
    data: {
      type: Object as PropType<any>,
      default: () => {}
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      applyType: props.parentId == 0 ? 0 : 1, // 顶级分类，子级分类
      parentId: props.parentId,
      appName: null,
      clientIds: null,
      permissionFlag: true,
      remark: null
    })

    const applyList = ref<any[]>([])
    const btnLoading = ref(false)

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

    const handleLoad = async (option: TreeSelectOption) => {
      try {
        console.log(option)
        const { data } = await sysApplicationPage({
          page: 1,
          rows: 999,
          parentId: option.key
        })
        const tempList = [] as any
        ;(data.rows || []).forEach((item: any) => {
          tempList.push({
            key: item.id,
            label: item.appName,
            isLeaf: item.number > 0 ? false : true
          })
        })
        option.children = [...tempList]
      } catch {}
    }

    const getApplyList = async (parentId = 0) => {
      try {
        const { data } = await sysApplicationPage({
          page: 1,
          rows: 999,
          parentId
        })
        const tempList = [] as any
        ;(data.rows || []).forEach((item: any) => {
          tempList.push({
            key: item.id,
            label: item.appName,
            isLeaf: item.number > 0 ? false : true
          })
        })
        return tempList
      } catch {}
    }

    const onSubmit = async () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return false
        try {
          btnLoading.value = true

          if (props.type === 'add') {
            await sysApplicationSave({
              appName: forms.appName,
              clientIds: forms.clientIds,
              parentId: forms.parentId,
              permissionFlag: forms.permissionFlag,
              remark: forms.remark
            })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await sysApplicationUpdate({ ...forms, id: props.data.id })
            message.success('修改成功')
          }

          btnLoading.value = false
          emit('close')
          emit('getList')
        } catch {}
      })
    }

    onMounted(async () => {
      applyList.value = await getApplyList()

      console.log(props.parentId)
      if (props.type === 'edit') {
        const data = props.data
        const tempList = await getApplyList(props.parentId)
        applyList.value.forEach((apply: any) => {
          if (apply.key == props.parentId) {
            apply.children = [...tempList]
          }
        })

        forms.appName = data.appName
        forms.clientIds = data.clientIds
        forms.permissionFlag = data.permissionFlag
        forms.remark = data.remark
      }
    })

    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="100">
          {props.type === 'add' && (
            <NFormItem
              label="应用类型"
              path="applyType"
              rule={[
                {
                  required: true,
                  message: '请选择应用类型'
                }
              ]}
            >
              <NRadioGroup v-model:value={forms.applyType}>
                <NSpace>
                  <NRadio value={0}>顶级应用</NRadio>
                  <NRadio value={1}>子级应用</NRadio>
                </NSpace>
              </NRadioGroup>
            </NFormItem>
          )}
          {forms.applyType > 0 && props.type === 'add' && (
            <NFormItem
              label="应用分类"
              path="parentId"
              rule={[
                {
                  required: true,
                  message: '请选择应用分类'
                }
              ]}
            >
              <NTreeSelect
                v-model:value={forms.parentId}
                options={applyList.value}
                showPath={true}
                allowCheckingNotLoaded={false}
                // checkStrategy={'child'}
                onLoad={handleLoad}
                placeholder="请选择应用分类"
                clearable
              ></NTreeSelect>
            </NFormItem>
          )}
          <NFormItem
            label="应用名称"
            path="appName"
            rule={[
              {
                required: true,
                message: '请输入应用名称'
              }
            ]}
          >
            <NInput
              v-model:value={forms.appName}
              placeholder="请输入应用名称"
              clearable
              maxlength={100}
            ></NInput>
          </NFormItem>
          <NFormItem
            label="权限客户端"
            path="clientIds"
            rule={[
              {
                required: true,
                message: '请输入权限客户端'
              }
            ]}
          >
            <NInput
              v-model:value={forms.clientIds}
              maxlength={200}
              placeholder="请输入权限客户端"
              clearable
            ></NInput>
          </NFormItem>
          <NFormItem
            label="权限认证"
            path="permissionFlag"
            rule={[
              {
                required: true,
                message: '请选择权限认证'
              }
            ]}
          >
            <NRadioGroup v-model:value={forms.permissionFlag}>
              <NSpace>
                <NRadio value={true}>是</NRadio>
                <NRadio value={false}>否</NRadio>
              </NSpace>
            </NRadioGroup>
          </NFormItem>
          <NFormItem
            label="备注"
            path="remark"
            rule={[
              {
                required: true,
                message: '备注'
              }
            ]}
          >
            <NInput
              v-model:value={forms.remark}
              maxlength={180}
              type="textarea"
              rows={3}
              placeholder="请输入备注"
            />
          </NFormItem>
        </NForm>

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