<template>
  <app-dialog
    v-model="visible"
    :loading="loading"
    append-to-body
    class="detail-dialog"
    hide-footer
    title="发布资源"
    width="60%"
    @cancel="onCancel"
    @confirm="onConfirm"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <div class="form-content">
        <el-row :gutter="20" type="flex">
          <app-filter-item :span="12" label="发布方式" prop="isIssue">
            <el-radio-group v-model="form.isIssue">
              <el-radio-button v-for="item in getIssueChange" :key="item.value" :label="item.value">
                {{ item.name }}
              </el-radio-button>
            </el-radio-group>
            <div>
              <i class="el-icon-warning-outline" style="color:#E6A23C" />
              {{ !form.isIssue ? '未有表发布：在汇聚层数据库新建一张表' : '已有表发布：已有表发布则是在数据交换库中已经创建了表的情况下进行发布关联。'
              }}
            </div>
          </app-filter-item>
        </el-row>
        <el-row :gutter="20">
          <app-filter-item v-if="!form.isIssue && form.tableClass === '1'" :span="20" label="SQL建表语句"
                           prop="tableSql"
          >
            <code-editor v-model="form.tableSql" :full-screen="true" language="sql" style="min-height: 100px;" />
          </app-filter-item>

          <app-filter-item v-if="!form.isIssue && form.tableClass === '2'" :span="20" label="主表建表语句"
                           prop="tableSql"
          >
            <code-editor v-model="form.tableSql" :full-screen="true" language="sql"
                         style="min-height: 100px;width:36vw"
            />
          </app-filter-item>
          <app-filter-item v-if="!form.isIssue && form.tableClass === '2'" :span="20" label="明细表建表语句"
                           prop="detailTablesql"
          >
            <code-editor v-model="form.detailTablesql" :full-screen="true" language="sql"
                         style="min-height: 100px;width:36vw"
            />
          </app-filter-item>

          <app-filter-item v-if="!!form.isIssue" :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>
          </app-filter-item>
          <!--          <app-filter-item :span="12" label="是否创建触发器" prop="createTrigger">-->
          <!--            <el-switch v-model="form.createTrigger" active-text="是" active-value="1" inactive-text="否" inactive-value="0" is-api is-database is-mq />-->
          <!--          </app-filter-item>-->
        </el-row>
      </div>
    </el-form>

    <div ref="dialogFooter" slot="footer" class="gz-dialog-footer text-l">
      <el-button :disabled="!!form.isIssue && !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 codeEditor from '@/components/codeEditor/index.vue';
import API from '@/api/business/dataDWCatalog';

export default {
  name: 'PutOutDialog',
  components: { codeEditor },
  mixins: [dialogMixin],
  data() {
    return {
      DICT,
      tableId: '',
      loading: false,
      form: {
        isIssue: 0,
        tableSql: '',
        detailTablesql: '',
      },
      rules: {
        isIssue: [{ required: true, message: '单位名称不能为空' }],
        tableSql: [{ required: true, message: 'SQL建表语句不能为空', trigger: 'change' }],
        detailTablesql: [{ required: true, message: '明细表建表语句不能为空', trigger: 'change' }],
        tableNameEn: [{ required: true, message: '关联的表名不能为空' }],
      },
      getIssueChange: [
        {
          name: '未有表发布',
          value: 0,
        },
        {
          name: '已有表发布',
          value: 1,
        },
      ],
      isTableNameEnValidated: false,
    };
  },
  methods: {
    initData(data) {
      const orgForm = this.$options.data().form;
      this.form = { ...orgForm, ...data };
      if (this.form.tableClass === '2') {
        this.form.tableNameEn = `DWD_BIZ_${this.form.tableNameEn}_DATA`;
      }
      this.tableId = data.id;
      this.getSqlDetail();
      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.checkSurfaceCh({ tableNameEn: tableNameEn, type: '1' });
        if (state) {
          this.isTableNameEnValidated = true;
          this.$message.success('验证通过');
        }
      } catch (error) {
        this.isTableNameEnValidated = false;
      } finally {
        this.loading = false;
      }
    },
    async getSqlDetail() {
      try {
        this.loading = true;
        if (this.form.tableClass === '1') {
          const { value } = await API.physicalTable(this.tableId);
          this.form.tableSql = value;
        } else {
          const { value } = await API.dynamicTable(this.tableId);
          this.form.tableSql = value.dwdMainSql;
          this.form.detailTablesql = value.dwdDetailSql;
        }
      } catch (error) {
        this.loading = false;
      } finally {
        this.loading = false;
      }
    },
    onCancel() {
      this.isTableNameEnValidated = false;
      this.visible = false;
    },
    async onConfirm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.loading = true;
            if (this.form.isIssue) {
              // 已有表
              const param = new FormData();
              param.append('tableId', this.tableId);
              await API.existingTablePublishing(param);
            } else {
              // 未有表
              const param = new FormData();
              param.append('tableId', this.tableId);
              param.append('tableSql', this.form.tableSql);
              param.append('detailTableSql', this.form.detailTablesql);
              await API.unpublishedTable(param);
            }
            this.$message.success('操作成功');
            this.onCancel();
            this.$emit('confirm');
          } catch (e) {
            console.log(e);
          } finally {
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

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

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