<template>
  <app-dialog v-model="visible" :loading="dialogLoading" :title="title" append-to-body class="detail-dialog" hide-footer
              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 mr-150" label-width="130px">
        <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="code">
              <el-input v-model="form.code" clearable placeholder="请输入" />
            </app-filter-item>
            <app-filter-item :span="13" label="共享数据源" prop="databaseId">
              <el-select v-model="form.databaseId" clearable placeholder="请选择数据源" @change="setDatabase">
                <el-option v-for="items in sqloptions" :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="13" label="资源级别" prop="level">
              <el-radio-group v-model="form.level">
                <el-radio-button v-for="(radio, index) in levelList" :key="index" :label="radio">{{ radio }}
                </el-radio-button>
              </el-radio-group>
            </app-filter-item>
            <app-filter-item :span="20" label="资源更新周期" prop="updateRate">
              <el-radio-group v-model="form.updateRate">
                <el-radio-button v-for="(radio, index) in rateList" :key="index" :label="radio" class="mb-10">{{ radio
                }}
                </el-radio-button>
              </el-radio-group>
            </app-filter-item>
            <app-filter-item :span="13" label="数据库表名(唯一)" prop="tableNameEn">
              <el-input v-model="form.tableNameEn" clearable placeholder="请输入">
                <template #append>
                  <el-button size="mini" type="primary" @click="checkAccount">验证</el-button>
                </template>
              </el-input>
              <span style="color:#f56c6c">（注：验证通过之后，才能进行新增）</span>
            </app-filter-item>
            <div style="display: flex;width: 100%">
              <app-filter-item :span="6" label="是否库表共享" prop="isDatabase">
                <el-switch v-model="form.isDatabase" active-text="是" active-value="1" inactive-text="否"
                           inactive-value="0"
                />
              </app-filter-item>
              <app-filter-item :span="6" label="是否文件共享" prop="isFile">
                <el-switch v-model="form.isFile" active-text="是" active-value="1" inactive-text="否"
                           inactive-value="0"
                />
              </app-filter-item>
              <app-filter-item :span="6" label="是否接口共享" prop="isApi">
                <el-switch v-model="form.isApi" active-text="是" active-value="1" inactive-text="否"
                           inactive-value="0"
                />
              </app-filter-item>
            </div>
            <app-filter-item :span="20" label="数据资源描述" prop="description">
              <el-input
                v-model="form.description"
                :autosize="{ minRows: 2, maxRows: 4}"
                placeholder="请输入资源描述"
                type="textarea"
              />
            </app-filter-item>
          </el-row>
        </div>
      </el-form>
    </div>
    <div ref="dialogFooter" slot="footer" class="gz-dialog-footer text-l">
      <el-button :disabled="isTableNameEnValidated" :loading="loading" class="confirm_btn"
                 type="primary" @click="onConfirm"
      >确
      定
      </el-button>
      <el-button class="cancel_btn" @click="onCancel">取 消</el-button>
    </div>
  </app-dialog>
</template>

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

export default {
  name: 'AddEditDialog',
  mixins: [dialogMixin],
  data() {
    return {
      id: '',
      catalogId: '',
      rules: {
        name: [{ required: true, message: '资源名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '资源编码不能为空', trigger: 'blur' }],
        databaseId: [{ required: true, message: '请选择共享数据源', trigger: 'change' }],
        level: [{ required: true, message: '请选择资源项级别', trigger: 'change' }],
        updateRate: [{ required: true, message: '请选择资源项更新周期', trigger: 'change' }],
        tableNameCh: [{ required: true, message: '中文名称不能为空', trigger: 'blur' }],
        tableNameEn: [{ required: true, message: '数据库表名不能为空', trigger: 'blur' }],
      },
      form: {
        isDatabase: '0',
        isFile: '0',
        isApi: '0',
      },
      sqloptions: [],
      levelList: ['低', '中', '较高', '高'],
      rateList: ['仅一次', '实时', '每天', '每周', '每月', '每季度', '每年'],
      dialogLoading: false,
      isTableNameEnValidated: true,
    };
  },
  methods: {
    initData(data) {
      this.getDataSource();
      this.form.catalogId = data.catalogId;
      data?.id && (this.id = data.id, this.getDetail());
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    // 数据源下拉事件
    setDatabase(v) {
      const item = this.sqloptions.find(item => item.id === v);
      this.form.dbAlias = item.alias;
      // const { alias: databaseAlias, dbType: databaseType, settingJson } = item;
      // const settingJson_ = JSON.parse(settingJson.replace(/[\\]/g, ''));
      //
      // settingJson_.forEach(item => {
      //   const { name, value } = item;
      //   name === 'url' && (this.form['databaseUrl'] = value);
      // });
      //
      // this.form = {
      //   ...this.form,
      //   databaseAlias,
      //   databaseType,
      // };
    },

    // 数据源下拉
    async getDataSource() {
      const data = await sourceApi.getList(4);
      this.sqloptions = data || [];
    },

    // 获取详情
    async getDetail() {
      try {
        this.loading = true;
        const param = new FormData();
        param.append('id', this.id);
        const { value } = await API.getCompanyDetail(param);
        this.form = { ...value };
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },

    // 验证
    async checkAccount() {
      const { tableNameEn, databaseId, dbAlias } = this.form;
      if (!tableNameEn || !databaseId) {
        this.$message.error('请选择数据源，并填写数据库表名');
        return;
      }
      try {
        this.loading = true;
        const param = new FormData();
        param.append('tableId', this.id);
        param.append('tableNameEn', tableNameEn);
        param.append('dbAlias', dbAlias);
        const { state } = await API.checkSurfaceName(param);
        if (state) {
          this.isTableNameEnValidated = false;
        }
        this.$message.success('验证通过');
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },

    onCancel() {
      this.form = {
        isDatabase: '0',
        isFile: '0',
        isApi: '0',
      };
      this.visible = false;
      this.isTableNameEnValidated = true;
    },

    onConfirm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.loading = true;
            const { state } = this.form.id ? await API.demandSideEdit(this.form) : await API.demandSideAdd(this.form);
            state && (this.$message.success('操作成功'), this.onCancel(), this.$emit('confirm'));
          } 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;
}

.gz-dialog-footer {
  padding: 11px 11px 0 11px;
  text-align: right;
}
</style>
