<template>
  <app-dialog
    v-model="visible"
    :loading="loading"
    :title="title"
    append-to-body
    class="detail-dialog"
    hide-footer
    width="70%"
    @cancel="onCancel"
    @confirm="onConfirm"
  >
    <el-form ref="form" :disabled="data && !!data.deployed" :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="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>
          <app-filter-item :span="24" label="资源提供方式" prop="source">
            <el-radio-group v-model="form.source">
              <el-radio-button v-for="radio in DICT.SOURCE_PROVIDED_TYPE" :key="radio.value" :label="radio.value">
                {{ radio.label }}
              </el-radio-button>
            </el-radio-group>
          </app-filter-item>
        </el-row>
        <el-row :gutter="20">
          <app-filter-item :span="12" label="实体表类型" prop="tableType">
            <el-radio-group v-model="form.tableType">
              <el-radio-button v-for="radio in DICT.TABLE_TYPE" :key="radio.value" :label="radio.value">{{ radio.label
              }}
              </el-radio-button>
            </el-radio-group>
          </app-filter-item>
          <app-filter-item :span="20" label="实体表描述" prop="tableDesc">
            <el-input v-model="form.tableDesc" :rows="4" clearable placeholder="请输入" type="textarea" />
          </app-filter-item>
        </el-row>
      </div>
    </el-form>
    <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 DICT from '@/utils/dict';
import companyApi from '@/api/business/dataCollectCompany';
import dictUtils from '@/components/dict/DictSelectUtils.js';

export default {
  name: 'ManualDialog',
  mixins: [dialogMixin],
  props: {
    clusterId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      DICT,
      form: {
        source: '1',
        tableType: '1',
        sourceType: '1',
      },
      parentDetail: {},
      rules: {
        name: [{ required: true, message: '单位名称不能为空' }],
        code: [{ required: true, message: '单位类型不能为空' }],
        source: [{ required: true, message: '资源提供方式不能为空' }],
        sourceType: [{ required: true, message: '系统编码不能为空' }],
        tablePrefixCode: [{ required: true, message: '提供方表前缀名不能为空' }],
        tableNameCh: [
          { required: true, message: '实体中文名表不能为空' },
          { pattern: /[\u4e00-\u9fa5]/g, message: '必须为汉字' },
        ],
        tableNameEn: [
          { required: true, message: '数据库表名不能为空' },
          {
            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
            message: '必须以字母开头,中间可以包含数字、英文、下划线。',
          },
        ],
        tableCode: [
          { required: true, message: '数据库表名不能为空' },
          { pattern: /^[A-Za-z]+$/g, message: '必须为英文' },
        ],
        tableType: [{ required: true, message: '请选择实体表类型' }],
      },
      loading: false,
      sysDict: {
        yjdj: dictUtils.getDictItemsFromCache('yjdj'),
      },
      isTableNameEnValidated: true,
    };
  },
  methods: {
    async checkAccount() {
      const { tableNameEn } = this.form;
      if (!tableNameEn) {
        this.$message.error('请输入数据库表名');
        return;
      }
      try {
        this.loading = true;
        const { state } = await companyApi.checkSurfaceName({ tableNameEn: tableNameEn, clusterId: this.clusterId });
        if (state) {
          this.isTableNameEnValidated = false;
        }
        this.$message.success('验证通过');
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    initData(data) {
      const orgForm = this.$options.data().form;
      this.form = { ...orgForm, ...data };

      data && this.getParentDetail();
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    async getParentDetail() {
      try {
        this.loading = true;
        this.parentDetail = await companyApi.getSourceDetail(this.data.id);
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    onCancel() {
      this.isTableNameEnValidated = true;
      this.visible = false;
    },
    async onConfirm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.form.tableNameCh = this.form.name;
            const params = { ...this.form, clusterId: this.clusterId, dbSourceId: this.parentDetail.databaseAlias };
            this.loading = true;
            params.id ? await companyApi.updateSource(params) : await companyApi.addSource(params);
            this.$message.success('操作成功');
            this.onCancel();
            this.$emit('confirm', { ...params });
          } catch (e) {
            console.log(e);
          } finally {
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form-content {
  width: 96%;
}

.demo-form {
  border: solid 1px #eff0f5;
  height: 95%;
  overflow: hidden;
}

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