import { positionArray } from '@/utils/searchArray'
import { NForm, NFormItem, NInput, NSelect, NSpace, NButton, useMessage } from 'naive-ui'
import { defineComponent, onMounted, PropType, reactive, ref } from 'vue'
import { sysPositionSave, sysPositionUpdate } from '../api'
export default defineComponent({
  name: 'role-operation',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    data: {
      type: Object as PropType<any>,
      default: () => {}
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const forms = reactive({
      roleName: null,
      jobType: null
    })

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

    const formsRef = ref()
    const message = useMessage()

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

          if (props.type === 'add') {
            await sysPositionSave({
              ...forms
            })
            message.success('添加成功')
          } else if (props.type === 'edit') {
            await sysPositionUpdate({ ...forms, id: props.data.id })
            message.success('修改成功')
          }

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

    onMounted(async () => {
      if (props.type === 'edit') {
        const data = props.data
        forms.roleName = data.roleName
        forms.jobType = data.jobType
      }
    })

    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="auto">
          <NFormItem
            label="岗位名称"
            path="roleName"
            rule={[
              {
                required: true,
                message: '请输入岗位名称'
              }
            ]}
          >
            <NInput
              v-model:value={forms.roleName}
              placeholder="请输入岗位名称"
              clearable
              maxlength={100}
            ></NInput>
          </NFormItem>
          <NFormItem
            label="岗位类型"
            path="jobType"
            rule={[
              {
                required: true,
                message: '岗位类型'
              }
            ]}
          >
            <NSelect
              v-model:value={forms.jobType}
              placeholder="请选择岗位类型"
              options={positionArray}
              clearable
              options-line
              style={{ width: '100%' }}
            />
          </NFormItem>
        </NForm>

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