<template>
  <ui-dialog
    class="mm-dialog--built-in"
    :on-confirm="confirmHandler"
    v-bind="dialogProps"
    v-on="dialogListeners">
    <type-icon
      v-if="type"
      :type="type"></type-icon>
    <message
      :is-html="messageIsHtml"
      :content="message">
    </message>
    <ui-form
      ref="form"
      layout="vertical"
      :data="model"
      v-bind="formProps">
      <slot :model="model">
        <ui-form-field
          name="value"
          field="value"
          v-bind="fieldProps">
          <ui-input
            ref="input"
            v-model="model.value"
            v-bind="inputProps"></ui-input>
        </ui-form-field>
      </slot>
    </ui-form>
  </ui-dialog>
</template>

<script>
import pick from "lodash/pick"
import omit from "lodash/omit"
import Dialog from "./dialog"
import TypeIcon from "./type-icon"
import Message from "./message"
import Input from "../input"
import Form from "../form"
import Field from "../form-field"
import visible from "../../mixins/visible"
import { t } from "../../locale"

export default {
  name: "mm-dialog-prompt",
  components: {
    "ui-dialog": Dialog,
    "type-icon": TypeIcon,
    "message": Message,
    "ui-input": Input,
    "ui-form": Form,
    "ui-form-field": Field,
  },
  mixins: [visible],
  inheritAttrs: false,
  props: {
    ...Dialog.props,
    title: {
      type: String,
      default() {
        return t("ui.dialog.title.prompt")
      },
    },
    type: TypeIcon.props.type,
    message: {
      type: [String, Array, Object],
      default: "",
    },
    messageIsHtml: {
      type: Boolean,
      default: false,
    },
    formProps: {
      type: Object,
      default() {
        return {}
      },
    },
    fieldProps: {
      type: Object,
      default() {
        return {}
      },
    },
    defaultValue: {
      type: String,
      default: "",
    },
    inputProps: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      model: {
        value: this.defaultValue,
      },
    }
  },
  computed: {
    dialogProps() {
      return {
        ...pick(this.$props, Object.keys(omit(Dialog.props, ["onConfirm"]))),
        visible: this.localVisible,
      }
    },
    dialogListeners() {
      return {
        ...this.$listeners,
      }
    },
  },
  watch: {
    localVisible: {
      immediate: true,
      handler(value) {
        this.$nextTick(() => {
          const input = this.$refs.input
          if (value && input) {
            input.focus()
          }
        })
      },
    },
  },
  methods: {
    confirmHandler(event) {
      return this.$refs.form.validate().then(() => {
        return this.onConfirm({ event, value: this.$scopedSlots.default ? this.model : this.model.value })
      })
    },
  },
}
</script>
