<template>
  <audit-form-top-banner :handel-save-form="saveForm" :form-data="mode" @handelSaveForm="saveForm">
    <template v-slot:beforebtn>
      <a-button
        :loading="connect"
        type="primary"
        :class="$style.connectBtn"
        @click="testConnection(mode)"
        >测试连接</a-button
      >
    </template>
    <sd-detail-form
      ref="docform"
      form-id="iamFinSysDatabase"
      page-id="dm/finsysdatabase/iamFinSysDatabase"
      :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
      :class="$style.form"
      :read-only="!saveFlag"
      @close="close(true)"
      @saved="saved"
      @sdFormReady="sdFormReady"
    >
      <template v-slot="{ model, fields }">
        <table>
          <tr>
            <td style="padding-left:5px;border:none">
              <audit-advanced-group
                :expand="basicExpand"
                :expand-str="'basicExpand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="basicExpand">
          <tr>
            <!-- 数据源名称 -->
            <sd-form-item-td name="name" />
            <!-- 数据源编码 -->
            <sd-form-item-td name="code">
              <a-form-model-item
                :rules="[
                  {
                    validator: validator,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="code"
              >
                <a-input v-model="model.code"></a-input>
              </a-form-model-item>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 数据库类型 -->
            <sd-form-item-td name="databaseType" @change="dbtypeChange" />
            <!-- 数据源类型 -->
            <sd-form-item-td name="databaseStatus" />
          </tr>
          <tr>
            <!-- IP地址 -->
            <sd-form-item-td name="host" />
            <!-- 端口号 -->
            <sd-form-item-td name="port" :input-props="{ style: 'width:100%' }" />
          </tr>
          <tr>
            <!-- 数据库名称 -->
            <sd-form-item-td name="useSchema" />
            <!-- 用户名 -->
            <sd-form-item-td name="userName" />
          </tr>
          <tr>
            <!-- 密码 -->
            <sd-form-item-td name="password" />
          </tr>
          <tr>
            <!-- 说明 -->
            <sd-form-item-td name="remark" :colspan="3">
              <a-textarea v-model="model.remark" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 维护人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 维护日期 -->
            <sd-form-item-td name="creationTime" />
          </tr>
        </table>
      </template>
    </sd-detail-form>
  </audit-form-top-banner>
</template>

<script>
import debounce from 'lodash.debounce'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { message } from '@/common/one-ui'
import axios from '@/common/services/axios-instance'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import components from './_import-components/iam-dm-database-form-import'

export default {
  name: 'IamDmDatabaseForm',
  metaInfo: {
    title: '数据源定义',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    auditFormTopBanner,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      mode: null,
      saveFlag: true,
      basicExpand: true,
      connect: false, // 测试连接按钮状态
    }
  },
  methods: {
    // 页面加载完成后
    sdFormReady() {
      this.mode = this.$refs.docform.formData.mode
    },
    // 保存
    saveForm() {
      this.$refs.docform.validateFields().then(() => {
        message.success('保存成功').then(() => {
          this.$refs.docform.saveBtnClick()
        })
      })
      // this.$refs.docform.saveBtnClick()
    },
    // 测试连接
    testConnection(model) {
      this.connect = true
      this.$refs.docform.$refs.form
        .validateFields()
        .then((flag) => {
          const databaseBean = {
            databaseType: this.$refs.docform.getFieldValue('databaseType'),
            host: this.$refs.docform.getFieldValue('host'),
            port: this.$refs.docform.getFieldValue('port'),
            useSchema: this.$refs.docform.getFieldValue('useSchema'),
            userName: this.$refs.docform.getFieldValue('userName'),
            password: this.$refs.docform.getFieldValue('password'),
          }
          axios({
            url: 'api/xcoa-mobile/v1/iamfinsysdatabase/testDbConnection',
            method: 'post',
            data: databaseBean,
          })
            .then((res) => {
              if (res.data.indexOf('成功') !== -1) {
                message.success(res.data, 1)
              } else {
                message.error(res.data, 1)
              }
              setTimeout(() => {
                this.connect = false
              }, 3000)
            })
            .catch((err) => {
              console.log(err)
              setTimeout(() => {
                this.connect = false
              }, 3000)
            })
        })
        .catch((err) => {
          console.log('必填校验失败：' + err)
          setTimeout(() => {
            this.connect = false
          }, 3000)
        })
    },
    // 编号验证是否重复
    validator(rule, value, callback) {
      value = encodeURIComponent(value)
      debounce(() => {
        axios
          .get(
            `api/xcoa-mobile/v1/iamfinsysdatabase/code?code=${value}&id=${this.$route.query
              .record || ''}`
          )
          .then((res) => {
            if (res?.data === true) {
              callback()
            } else {
              callback('数据源原编码已存在，不允许重复')
            }
          })
      }, 500)()
    },
    // 选择数据库之后生成对应的端口号
    // mysql:3306 oracle:1521 sql server:1433 db2:5000 postgresql:5432 dm:5236
    dbtypeChange(val) {
      if (val) {
        if (val.toUpperCase() === 'MYSQL') {
          this.$refs.docform.setFieldValue('port', 3306)
        } else if (val.toUpperCase() === 'DB2') {
          this.$refs.docform.setFieldValue('port', 5000)
        } else if (val.toUpperCase() === 'ORACLE') {
          this.$refs.docform.setFieldValue('port', 1521)
        } else if (val.toUpperCase() === 'SQLSERVER') {
          this.$refs.docform.setFieldValue('port', 1433)
        }
      }
    },
    saved() {
      this.close(true)
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';
.connect-btn {
  float: right;
  font-weight: 400;
  font-size: 16px;
  top: 8px;
  cursor: pointer;
  margin-right: 10px;
}
</style>
