<template>
  <app-dialog
    v-model="visible"
    :loading="loading"
    :title="title"
    append-to-body
    class="detail-dialog"
    hide-footer
    width="60%"
    @cancel="onCancel"
    @confirm="onConfirm"
  >
    <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="16" 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>
        </el-row>
        <!--        <el-row :gutter="20">-->
        <!--          <app-filter-item :span="13" label="实体表中文名" prop="tableNameCh">-->
        <!--            <el-input v-model="form.tableNameCh" clearable placeholder="请输入" />-->
        <!--          </app-filter-item>-->
        <!--          <app-filter-item :span="12" label="实体表英文名" prop="tableNameEn">-->
        <!--            &lt;!&ndash;            <el-input v-model="form.tableNameEn" clearable placeholder="请输入" />&ndash;&gt;-->
        <!--            <el-input v-model="form.tableNameEn" clearable placeholder="请输入">-->
        <!--              <template #append>-->
        <!--                <el-button size="mini" type="primary" @click="checkAccount">验证</el-button>-->
        <!--              </template>-->
        <!--            </el-input>-->
        <!--          </app-filter-item>-->
        <!--        </el-row>-->
        <el-row :gutter="20">
          <app-filter-item :span="13" 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>
        </el-row>
        <el-row :gutter="20">
          <app-filter-item :span="20" label="实体表描述" prop="tableDesc">
            <el-input v-model="form.tableDesc" 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 API from '@/api/business/dataODSCatalog';
import dictUtils from '@/components/dict/DictSelectUtils.js';

export default {
  name: 'ManualDialog',
  mixins: [dialogMixin],
  props: {
    clusterId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      DICT,
      form: {
        tableType: '1',
      },
      parentDetail: {},
      rules: {
        name: [{ required: true, message: '资源名称不能为空' }],
        code: [{ 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][a-zA-Z0-9_]*$/, message: '必须以字母开头,中间可以包含数字、英文、下划线。' },
        ],
        tableType: [{ required: true, message: '请选择表类型' }],
      },
      loading: false,
      sysDict: {
        yjdj: dictUtils.getDictItemsFromCache('yjdj'),
      },
      isTableNameEnValidated: true,
    };
  },
  methods: {
    /**
     * @description: dialog每次显示时触发的init方法
     * @param {*} data 传入data
     * @return {*}
     */
    initData(data) {
      const orgForm = this.$options.data().form;
      this.form = { ...orgForm, ...data };

      this.dynamicArea = [];
      this.clusterId && this.getParentDetail();

      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    // 实体表验证
    async checkAccount() {
      const { tableNameEn } = this.form;
      if (!tableNameEn) {
        this.$message.error('请输入数据库表名');
        return;
      }
      try {
        this.loading = true;
        const { state } = await API.checkSurfaceName({ tableNameEn: tableNameEn });
        if (state) {
          this.isTableNameEnValidated = false;
        }
        this.$message.success('验证通过');
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
      // try {
      //   this.loading = true;
      //   await API.checkSurfaceCh({ tableNameEn: tableNameEn });
      //   this.$message.success('验证通过');
      // } catch (error) {
      //   console.log(error);
      // } finally {
      //   this.loading = false;
      // }
    },
    async getParentDetail() {
      try {
        this.loading = true;
        const data = await API.getCompanyDetail(this.clusterId);
        this.parentDetail = data;
        console.log(data);
      } 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 {
    //         // dbSourceId: this.parentDetail.databaseAlias
    //         const params = { ...this.form, odsCatalogsId: this.odsCatalogsId };
    //
    //         this.loading = true;
    //         params.id ? await API.updateSource(params) : await API.addSource(params);
    //
    //         this.$message.success('操作成功');
    //         this.onCancel();
    //         this.$emit('confirm', { ...params });
    //       } catch (e) {
    //         console.log(e);
    //       } finally {
    //         this.loading = false;
    //       }
    //     }
    //   });
    // },
    onConfirm() {
      this.loading = true;
      this.$refs.form.validate(async (valid, object) => {
        if (valid) {
          try {
            this.form.tableNameCh = this.form.name;
            let APIMethod;
            if (this.form?.id) {
              APIMethod = API.updateSource;
            } else {
              APIMethod = API.addSource;
            }
            const { state, message } = await APIMethod(this.form);
            if (state) {
              this.$message.success(this.form?.id ? '编辑' : '新增' + '贴源数据');
              this.$emit('confirm');
              this.visible = false;
            } else {
              this.$message.warning(message || '操作失败');
            }
          } catch (err) {
            this.$message.warning(err || '操作失败');
          } finally {
            this.loading = false;
          }
        } else {
          this.$message.warning(`有${Object.keys(object).length}个字段未通过校验，请正确填写表单。`);
          this.loading = false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-timeline {
  padding-left: 1px;

  ::v-deep {
    .el-timeline-item__node {
      background-color: #1890ff;
    }

    .el-timeline-item__tail {
      border-left: 0.10417vw solid #d8e5ff;
    }
  }
}

.custom-row {
}

::v-deep {
  .gz-dialog .el-form-item__error {
    left: 0;
  }

  .el-form-item {
    margin-bottom: 18px !important;

    //.el-form-item__content .el-input {
    //  max-width: 218px;
    //}
  }

  .el-input__suffix {
    right: 0;
  }
}

.form-content {
  width: 96%;
  //margin: 0 auto;
}

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

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