<template>
  <div>
    <v-alert
      v-if="isEdit && itemData.credential_configured"
      dense
      text
      type="info"
      class="mx-3"
    >
      凭据已配置，用户名和密码留空将沿用当前凭据。
    </v-alert>
    <MForm ref="formData" :items="formData" v-model="formValues">
      <div class="pa-2 d-flex align-center justify-center">
        <v-btn
          v-for="(item, index) in buttons"
          :key="index"
          :loading="item.loading"
          rounded
          :color="item.color"
          class="buttons mr-3"
          @click="item.handler(item)"
        >
          {{ item.text }}
        </v-btn>
      </div>
    </MForm>
  </div>
</template>

<script>
import MForm from '@/components/MForm'
import {
  datasourceConnectTest,
  datasourceValid
} from '@/api/dataOrigin'

const SAFE_DEFINITION_FIELDS = [
  'uid',
  'name_zh',
  'name_en',
  'type',
  'host',
  'port',
  'database',
  'schema',
  'status',
  'desc'
]

export default {
  name: 'SourceEdit',
  components: { MForm },
  props: {
    itemData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      buttons: [
        {
          loading: false,
          text: '验证',
          color: 'primary',
          handler: this.handleValid
        },
        {
          loading: false,
          text: '连接测试',
          color: 'warning',
          handler: this.handleTest
        }
      ],
      formValues: {
        uid: null,
        name_zh: null,
        name_en: null,
        type: null,
        host: null,
        port: null,
        database: null,
        schema: null,
        username: null,
        password: null,
        status: true,
        desc: null
      }
    }
  },
  computed: {
    isEdit () {
      return Boolean(this.itemData && this.itemData.uid)
    },
    credentialRules () {
      return this.isEdit
        ? []
        : [value => !!value || '首次创建数据源时必须填写凭据']
    },
    formData () {
      return [
        {
          type: 'text',
          key: 'name_zh',
          label: '请输入数据源中文名称 *',
          outlined: true,
          dense: true,
          rules: [value => !!value || '请输入数据源中文名称']
        },
        {
          type: 'text',
          key: 'name_en',
          label: '请输入数据源英文名称 *',
          disabled: this.isEdit,
          outlined: true,
          dense: true,
          rules: [value => !!value || '请输入数据源英文名称']
        },
        {
          type: 'autocomplete',
          key: 'type',
          label: '请选择数据库类型 *',
          outlined: true,
          dense: true,
          items: [
            { label: 'PostgreSQL', value: 'postgresql' },
            { label: 'MySQL', value: 'mysql' }
          ],
          rules: [value => !!value || '请选择数据库类型']
        },
        {
          type: 'text',
          key: 'host',
          label: '请输入数据库服务器地址 *',
          col: 8,
          outlined: true,
          dense: true,
          rules: [value => !!value || '请输入数据库服务器地址']
        },
        {
          type: 'text',
          key: 'port',
          label: '请输入数据库服务器端口 *',
          col: 4,
          outlined: true,
          dense: true,
          rules: [value => !!value || '请输入数据库服务器端口']
        },
        {
          type: 'text',
          key: 'database',
          label: '请输入数据库名称 *',
          outlined: true,
          dense: true,
          col: 6,
          rules: [value => !!value || '请输入数据库名称']
        },
        {
          type: 'text',
          key: 'schema',
          label: '请输入数据库结构（schema）',
          outlined: true,
          dense: true,
          col: 6
        },
        {
          type: 'text',
          key: 'username',
          col: 6,
          label: this.isEdit ? '新用户名（留空沿用）' : '请输入用户名 *',
          outlined: true,
          dense: true,
          rules: this.credentialRules
        },
        {
          type: 'password',
          key: 'password',
          col: 6,
          label: this.isEdit ? '新密码（留空沿用）' : '请输入密码 *',
          outlined: true,
          dense: true,
          rules: this.credentialRules
        },
        {
          type: 'ifRadio',
          key: 'status',
          label: '状态',
          items: [
            { value: true, label: '启用' },
            { value: false, label: '关闭' }
          ]
        },
        {
          type: 'textarea',
          key: 'desc',
          outlined: true,
          label: '请输入描述'
        }
      ]
    }
  },
  created () {
    SAFE_DEFINITION_FIELDS.forEach(field => {
      if (this.itemData[field] !== undefined) {
        this.formValues[field] = this.itemData[field]
      }
    })
    this.formValues.username = null
    this.formValues.password = null
  },
  methods: {
    validate () {
      return this.$refs.formData.validate()
    },
    getQuery () {
      const payload = { ...this.formValues }
      if (!payload.username) delete payload.username
      if (!payload.password) delete payload.password
      return payload
    },
    async runConnectionAction (item, action) {
      item.loading = true
      try {
        const { data } = await action(this.getQuery())
        if (data.connected) {
          this.$snackbar.success(data.message)
        } else {
          this.$snackbar.error(data.message)
        }
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        item.loading = false
      }
    },
    handleTest (item) {
      return this.runConnectionAction(item, datasourceConnectTest)
    },
    handleValid (item) {
      return this.runConnectionAction(item, datasourceValid)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
