<template>
  <app-dialog v-model="visible" :loading="loading" :title="title" append-to-body class="detail-dialog" width="70%"
              @cancel="onCancel" @confirm="onConfirm"
  >
    <div ref="scroll-box" class="h-100 overflow-y pr-10" style="scroll-behavior: smooth">
      <el-form ref="form" :model="form" :rules="rules" class="demo-form ml-150" label-width="120px">
        <el-divider content-position="left"><i class="el-icon-document" style="color: rgb(24, 144, 255)" /><span
          class="divider-top"
        >基础信息</span>
        </el-divider>
        <div class="form-content ml-120">
          <el-row :gutter="20">
            <app-filter-item :span="13" label="调用者名称" prop="name">
              <el-input v-model="form.name" clearable placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label="系统名称" prop="appName">
              <el-input v-model="form.appName" clearable placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label="调用者编码" prop="code">
              <el-input v-model="form.code" clearable placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" clearable placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label="联系方式" prop="contactPhone">
              <el-input v-model="form.contactPhone" clearable placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label=" 备注" prop="memo">
              <el-input v-model="form.memo" type="textarea" />
            </app-filter-item>
          </el-row>
          <el-row :gutter="20" class="custom-row">
            <app-filter-item :span="6" label="开通库表" prop="isOpenDb">
              <el-switch
                v-model="form.isOpenDb"
                active-text="是"
                active-value="1"
                inactive-text="否"
                inactive-value="0"
              />
            </app-filter-item>

            <app-filter-item :span="6" label="API接口" prop="isOpenApi">
              <el-switch
                v-model="form.isOpenApi"
                active-text="是"
                active-value="1"
                inactive-text="否"
                inactive-value="0"
              />
            </app-filter-item>

          </el-row>
        </div>
        <el-divider v-if="form.isOpenDb === '1'" content-position="left"><i class="el-icon-document"
                                                                            style="color: rgb(24, 144, 255)"
        /><span
          class="divider-top"
        >数据库信息</span>
        </el-divider>
        <div v-if="form.isOpenDb === '1'" class="form-content ml-120">
          <el-row :gutter="20">
            <app-filter-item :span="13" label="数据源" prop="databaseId">
              <el-select v-model="form.databaseId" clearable placeholder="请选择数据源" @change="setDatabase">
                <el-option v-for="items in dataSourceList" :key="items.id" :label="items.name" :value="items.id">
                  <span style="float: left">{{ items.name }} </span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ items.dbType }}</span>
                </el-option>
              </el-select>
            </app-filter-item>

            <app-filter-item :span="10" class="text-color-light" label-width="200px">
              <template #label>
                <span class="text-color-light">注意: (请先选择数据源)</span>
              </template>
            </app-filter-item>
          </el-row>
          <el-row :gutter="20">
            <app-filter-item
              :rules="[{ required: form.isOpenDb === '1', message: '不能为空（请先选择数据源）' }]"
              :span="13"
              label="数据库别名"
              prop="dbAlias"
            >
              <el-input v-model="form.dbAlias" disabled />
            </app-filter-item>

            <app-filter-item
              :rules="[{ required: form.isOpenDb === '1', message: '不能为空（请先选择数据源）' }]"
              :span="13"
              label="数据库类型"
              prop="databaseType"
            >
              <el-input v-model="form.databaseType" disabled />
            </app-filter-item>

            <app-filter-item
              :rules="[{ required: form.isOpenDb === '1', message: '不能为空（请先选择数据源）' }]"
              :span="13"
              label="数据库实例"
              prop="dataBaseName"
            >
              <el-input v-model="form.dataBaseName" disabled />
            </app-filter-item>

            <app-filter-item
              :rules="[{ required: form.isOpenDb === '1', message: '不能为空（请先选择数据源）' }]"
              :span="24"
              label="连接地址"
              prop="databaseUrl"
            >
              <el-input v-model="form.databaseUrl" disabled type="textarea" />
            </app-filter-item>
            <app-filter-item
              :rules="[{ required: form.isOpenDb === '1', message: '用户名不能为空' },{ pattern: /^[a-zA-Z]+$/, message: '只能输入英文', trigger: 'blur' }]"
              :span="13"
              label="用户名" prop="databaseUser"
            >
              <el-input v-model="form.databaseUser" :disabled="!!form.id" clearable placeholder="请输入">
                <template #append>
                  <el-button size="mini" type="primary" @click="checkAccount">验证</el-button>
                </template>
              </el-input>
            </app-filter-item>

            <app-filter-item :rules="[{ required: form.isOpenDb === '1', message: '密码不能为空' },{
                               pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/,
                               message: '长度至少8个字符，至少包含大小写字母、数字和特殊字符',
                               trigger: 'blur',
                             }]" :span="13"
                             label="密码" prop="databasePwd"
            >
              <el-input v-model="form.databasePwd" clearable placeholder="请输入" show-password />
            </app-filter-item>

          </el-row>
        </div>
        <el-divider v-if="form.isOpenApi === '1' && form.id" content-position="left"><i class="el-icon-document"
                                                                                        style="color: rgb(24, 144, 255)"
        /><span
          class="divider-top"
        >接口信息</span>
        </el-divider>
        <div v-if="form.isOpenApi === '1' && form.id" class="form-content ml-120">
          <el-row :gutter="20">
            <app-filter-item :span="13" label="accessKey" prop="accessKey">
              <el-input v-model="form.accessKey" clearable disabled placeholder="请输入" />
            </app-filter-item>

            <app-filter-item :span="13" label="secretKey" prop="secretKey">
              <el-input v-model="form.secretKey" clearable disabled placeholder="请输入" />
            </app-filter-item>
          </el-row>
        </div>
      </el-form>
    </div>
  </app-dialog>
</template>

<script>
import API from '@/api/business/shareDataCall';
import sourceApi from '@/api/business/changeDataSource';
import dialogMixin from '@/mixins/dialog.js';

export default {
  name: 'AddEditDialog',
  mixins: [dialogMixin],
  props: {
    selectedRows: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      id: '',
      form: {
        isOpenDb: '1',
      },
      rules: {
        name: [{ required: true, message: '调用者名称不能为空' }],
        code: [{ required: true, message: '调用者编码不能为空' }],
        appName: [{ required: true, message: '系统名称不能为空' }],
        databaseId: [{ required: true, message: '请选择数据源', trigger: 'change' }],
      },
      loading: false,
      dataSourceList: [],
    };
  },
  methods: {
    initData(data) {
      this.getDataSource();
      data?.id && (this.id = data.id, this.getDetail());
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    // 获取详情
    async getDetail() {
      try {
        this.loading = true;
        const data = await API.getCompanyDetail(this.id);
        this.form = { ...data.value };
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    async checkAccount() {
      const { dbAlias, databaseUser } = this.form;
      if (!databaseUser || !dbAlias) {
        this.$message.error('请选择数据源，并填写用户名');
        return;
      }
      try {
        this.loading = true;
        const formData = new FormData();
        formData.append('dbAlias', dbAlias);
        formData.append('user', databaseUser);
        await API.checkDataUserIsExist(formData);
        this.$message.success('验证通过，该用户名可以使用');
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    // 数据源下拉
    async getDataSource() {
      const data = await sourceApi.getList(4);
      this.dataSourceList = data || [];
    },
    setDatabase(v) {
      const item = this.dataSourceList.find((item) => item.id === v);
      const { alias: dbAlias, dbType: databaseType, settingJson } = item;
      const settingJson_ = JSON.parse(settingJson.replace(/[\\]/g, ''));

      settingJson_.forEach((item) => {
        const { name, value } = item;
        if (name === 'url') {
          this.form['databaseUrl'] = value;
          const end = value.indexOf('?'); // 找到 '?' 的位置
          const start = value.lastIndexOf('/', end) + 1;
          this.form['dataBaseName'] = value.substring(start, end);
        }
      });

      this.form = {
        ...this.form,
        dbAlias,
        databaseType,
      };
    },
    onCancel() {
      this.form = {
        isOpenDb: '1',
      };
      this.visible = false;
    },
    async onConfirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const { state } = this.id ? await API.demandSideEdit(this.form) : await API.demandSideAdd(this.form);
            state && (this.$message.success('操作成功'), this.onCancel(), this.$emit('confirm'));
          } catch (e) {
            console.log(e);
          } finally {
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form-item {
    margin-bottom: 18px !important;
  }

  .el-input__suffix {
    right: 0;
  }
}

.demo-form {
  border: solid 1px #eff0f5;
}
</style>
