<template>
  <div class="data-form">
    <IxForm :control="formGroup"
        :control-col="{span:18}"
        :label-col="{span:6}"
        label-align="end"
        layout="horizontal"
        message-tooltip>
      <IxDivider dashed labelPlacement="start">基本信息</IxDivider>
      <IxRow>
        <IxCol :span="6">
          <IxFormItem :gutter="[0, 10]" label="单位编号">
            <IxInput control="sn"/>
          </IxFormItem>
        </IxCol>
        <IxCol :span="6">
          <IxFormItem :gutter="[0, 10]" label="单位名称">
            <IxInput control="tenantName"/>
          </IxFormItem>
        </IxCol>
        <IxCol :span="6">
          <IxFormItem :gutter="[0, 10]" label="状态">
            <IxSelect
                :data-source="tenantStatusList"
                control="status"
                get-key="val" label-key="txt"/>
          </IxFormItem>
        </IxCol>
      </IxRow>
    </IxForm>
  </div>
</template>

<script lang="ts" setup>
import {
  useFormGroup,
  Validators
} from '@idux/cdk'
import Utils from '@/common/utils'
import DictApi from '@/pages/sys/dict/dict-api.ts'

const props = withDefaults(defineProps<{ status?: 'create' | 'view' | 'edit' }>(),
    {
      status: 'create',
    }
)

const formGroup = useFormGroup<TenantTypes.Tenant>({
  sn: [ undefined, Validators.required ],
  tenantName: [ undefined, Validators.required ],
  status: [ undefined, Validators.required ],
})

const tenantStatusList = ref<DictTypes.SysDictItem[]>([])

function updateFormStatus() {
  if (props.status === 'view') {
    formGroup.disable()
  } else if (props.status === 'edit') {
    formGroup.enable()
  }
}

watch(() => props.status, updateFormStatus)

defineExpose({
  getValue() {
    return Utils.clone({
      ...formGroup.getValue(),
    } as TenantTypes.Tenant)
  },
  setValue(data: TenantTypes.Tenant) {
    formGroup.setValue(data)
  },
  reset() {
    formGroup.reset()
  }
})

onMounted(() => {
  updateFormStatus()
  DictApi.obtainDictData('tenant_status')
      .then(res => {
        tenantStatusList.value = res.data
      })
})

</script>

<style lang="stylus" scoped>
.data-form {
  width 100%
  padding 1rem
  margin 1rem 0

  :deep(.ix-row) {
    margin .5rem 0
  }
}

</style>
