<template>
  <div class="page-view border-radius-5">
    <div class="flex-1 bg-white flex-col border-radius-5 pa-11">
      <el-page-header content="" @back="handleBack" />
      <el-form ref="form" :inline="false" :model="form" :rules="rules" class="demo-form" label-width="110px">
        <el-divider content-position="left">
          <i class="el-icon-document"
             style="color: rgb(24, 144, 255)"
          />
          <span
            class="divider-top"
          >{{ titlePage }}</span>
        </el-divider>
        <div class="form-content">
          <el-row v-if="pageKey" :gutter="20">
            <app-filter-item :span="10" label="指标名称" prop="name">
              <el-input v-model="form.name" clearable placeholder="请输入特征指标名称" />
            </app-filter-item>
            <app-filter-item :span="10" label="指标编码" prop="code">
              <el-input v-model="form.code"
                        placeholder="请输入指标编码"
                        @change="fromVerification"
              >
                <template #suffix>
                  <i v-if="!verificationResult" :style="{color:'#F56C6C'}" class="el-icon-circle-close" />
                  <i v-else :style="{color:'#67C23A'}" class="el-icon-circle-check" />
                </template>
              </el-input>
            </app-filter-item>
            <app-filter-item :span="4" label="">
              <el-button type="primary" @click="uniqueVerification">唯一验证</el-button>
            </app-filter-item>
            <app-filter-item :span="20" label="指标描述" prop="description">
              <el-input v-model="form.description" :autosize="{ minRows: 4, maxRows: 6 }" placeholder="请输入指标描述"
                        size="small" type="textarea"
              />
            </app-filter-item>
          </el-row>
          <el-row v-else>
            <app-filter-item :span="20" label="指标名称">
              <span style="font-weight: 600">{{ form.name }}</span>
            </app-filter-item>
            <app-filter-item :span="20" label="指标编码">
              <span style="font-weight: 600">{{ form.code }}</span>
            </app-filter-item>
            <app-filter-item :span="20" label="指标描述">
              <span style="font-weight: 600">{{ form.description }}</span>
            </app-filter-item>
          </el-row>
        </div>
        <el-divider content-position="left">
          <i class="el-icon-connection"
             style="color: rgb(24, 144, 255)"
          />
          <span
            class="divider-top"
          >数据字段关联</span>
        </el-divider>
        <div class="form-content">
          <el-row :gutter="24">
            <app-filter-item :span="9" label="归属数据库" prop="tableClass">
              <el-radio-group v-model="form.tableClass">
                <el-radio-button v-for="(item, index) in sqlList" :key="index" :label="item.value" class="mb-10">
                  {{ item.label
                  }}
                </el-radio-button>
              </el-radio-group>
            </app-filter-item>
            <app-filter-item :span="4" label="">
              <el-button icon="el-icon-setting" type="success" @click="tablesAndFields">字段选择</el-button>
            </app-filter-item>
            <app-filter-item v-if="form.tableNameCh" :span="24" label="数据库表名" prop="tableNameCh">
              <span style="font-weight: 600">{{ form.tableNameCh + '(' + form.tableCode + ')' }}</span>
            </app-filter-item>
            <app-filter-item v-if="form.fieldName" :span="24" label="字段名" prop="fieldName">
              <span style="font-weight: 600">{{ form.fieldName + '(' + form.fieldCloumn + ')' }}</span>
            </app-filter-item>
          </el-row>
          <el-row :gutter="20">
            <app-filter-item v-if="form.fieldValueType && form.fieldValueType !== 1" :span="10" label="字段值">
              <div v-if="form.fieldValueType === 2" class="flex flex-gap-6">
                <el-tag v-for="item in form.dimensionJson" :key="item.id" size="medium">{{ item.name }}</el-tag>
              </div>
              <div v-if="form.fieldValueType === 3">
                <el-button type="primary" @click="checkDictionary">数据浏览</el-button>
              </div>
            </app-filter-item>
          </el-row>
        </div>
      </el-form>
      <div class="dialog-footer">
        <el-button size="small" type="primary" @click="okButtonChange">确 定</el-button>
        <el-button size="small" @click="handleBack">取 消</el-button>
      </div>
    </div>

    <!--   字段选择 -->
    <table-drawer v-if="drawerVisible" v-model="drawerVisible" :data-row="form" :sheet-page="sheetPage"
                  :sheet-page-size="sheetPageSize" :sheet-tree-id="sheetTreeId" :table-class="form.tableClass"
                  :table-id="tableId" :table-instance-id="tableInstanceId"
                  @confirm="confimChange"
    />
    <!--  查看多维字典  -->
    <sub-tree-drawer v-model="treeVisible" :code="form.dimensionId" title="多维字典" />
  </div>
</template>

<script>
import dialogMixin from '@/mixins/dialog.js';
import TableDrawer from './TableDrawer.vue';
import SubTreeDrawer from './SubTreeDrawer.vue';
import API from '@/api/business/arithmeticInfo';
import { getDictionaryByCode } from '@/utils/dictionary.js';

export default {
  name: 'AddEditPage',
  components: { SubTreeDrawer, TableDrawer },
  mixins: [dialogMixin],
  data() {
    return {
      defaultProps: {
        value: 'id',
        label: 'name',
      },
      form: {
        enableStatus: '1',
        tableClass: '1',
      },
      rules: {
        name: [{ required: true, message: '指标名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '指标编码不能为空', trigger: 'blur' }],
        tableClass: [{ required: true, message: '请选择实体表归属数据库实例', trigger: 'change' }],
      },
      tableList: [{ label: '测试表名1', value: '1' }, { label: '测试表名2', value: '2' }],
      fieldList: [{ label: '字段1', value: '1' }, { label: '字段2', value: '2' }],
      levelList: [{ label: '外在', value: 1 }, { label: '内在', value: 0 }],
      rateList: ['普通字段', '枚举字典', '多维字典项'],
      sqlList: [{
        label: 'ODS贴源层',
        value: '1',
      }, {
        label: 'DWD明细层',
        value: '2',
      }, {
        label: 'APP应用库',
        value: '3',
      }],
      drawerVisible: false,
      tableInstanceId: '1',
      treeVisible: false,
      verificationResult: false,
      tableId: '',
      sheetTreeId: '',
      sheetPage: 0,
      sheetPageSize: 0,
    };
  },
  computed: {
    titlePage() {
      let title = '';
      switch (this.$route.query.pageKey) {
        case '1':
          title = '新增';
          break;
        case '2':
          title = '编辑';
          break;
        default:
          title = '';
      }
      const typeMapping = {
        '1': '结果',
        '2': '问题',
        '3': '属性',
      };
      return `${title}${typeMapping[this.$route.query.type] || '属性'}指标`;
    },
    pageKey() {
      return !!(this.$route.query.pageKey === '1' || this.$route.query.pageKey === '2');
    },
  },
  mounted() {
    if (this.$route.query.id !== '') {
      this.getDetail();
    }
  },
  methods: {
    getDictionaryByCode,
    // 根据id获取详情
    async getDetail() {
      try {
        this.verificationResult = true;
        this.form = await API.getDetailedData(this.$route.query.id);
        if (this.form.fieldName) {
          this.sheetPage = Number(this.form.sheetPage);
          this.sheetPageSize = Number(this.form.sheetPageSize);
          this.sheetTreeId = this.form.sheetTreeId;
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 确定事件
    okButtonChange() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            console.log(this.verificationResult, this.pageKey, '-------');
            if (!this.verificationResult && this.pageKey) {
              this.$message.warning('请先进行指标编码唯一性验证！');
              return false;
            } else {
              this.loading = true;
              this.form.level = this.$route.query.type;
              this.form.dimensionJson = JSON.stringify(this.form.dimensionJson);
              const { state } = await API.saveAlgorithmCatalogsIndex(this.form);
              if (state) {
                this.$message.success('保存成功');
                this.$router.push({
                  name: 'arithmeticInfo',
                  query: {
                    activeName: this.$route.query.type === '1' ? 'Provider' : this.$route.query.type === '2' ? 'Resource' : 'Gound',
                  },
                });
              }
            }
          } catch (e) {
            console.log(e);
          } finally {
            this.loading = false;
          }
        }
      });
    },
    // 验证事件
    uniqueVerification() {
      this.$refs.form.validateField('code', async (valid) => {
        if (valid) {
          this.verificationResult = false;
          this.$message.error('验证错误');
          return false;
        } else {
          const param = new FormData();
          param.append('code', this.form.code);
          param.append('id', '');
          const { state } = await API.queryExistsByCode(param);
          if (state) {
            this.$message.success('验证成功');
            this.verificationResult = true;
          }
        }
      });
    },
    handleBack() {
      this.$router.push({
        name: 'arithmeticInfo',
        query: {
          activeName: this.$route.query.type === '1' ? 'Provider' : this.$route.query.type === '2' ? 'Resource' : 'Gound',
        },
      });
    },

    tablesAndFields() {
      if (this.form.tableNameCh) {
        this.sheetTreeId = this.form.sheetTreeId;
        this.sheetPage = this.form.sheetPage;
        this.sheetPageSize = this.form.sheetPageSize;
        this.tableId = this.form.tableId;
      }
      this.drawerVisible = true;
    },
    fromVerification() {
      this.$refs.form.validateField('code', (valid) => {
        if (valid) {
          return false;
        }
      });
    },
    checkDictionary() {
      this.treeVisible = true;
    },
    confimChange(data) {
      // 表值
      this.form.tableId = data.id;
      this.form.tableNameCh = data.tableNameCh;
      this.form.tableCode = data.tableNameEn;
      // 字段值
      this.form.fieldValueType = Number(data.fieldValueType);
      this.form.dimensionId = data.dimensionId;
      this.form.fieldName = data.fieldName;
      this.form.fieldCloumn = data.fieldCode;
      // 表回显选中
      this.form.sheetTreeId = data.sheetTreeId;
      this.form.sheetPage = data.sheetPage;
      this.form.sheetPageSize = data.sheetPageSize;

      // 当字段为枚举时 获取枚举值
      if (this.form.fieldValueType === 2) {
        this.form.dimensionJson = getDictionaryByCode(data.dimensionId);
      } else if (this.form.fieldValueType === 3) {
        this.form.dimensionId = data.dimensionId;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form .el-divider--horizontal:first-child {
  margin-top: 30px;
}

::v-deep .el-textarea__inner {
  padding: 5px 10px !important;
}

.demo-form {
  padding: 0 120px;
  box-sizing: border-box;
}

.form-content {
  margin: 40px 50px 0 50px;
  padding: 0 40px;
  box-sizing: border-box;
}

.dialog-footer {
  text-align: center;
  margin-top: 40px;
  position: fixed;
  bottom: 30px;
  padding: 0 150px;
  width: calc(100% - 300px);
  box-sizing: border-box;
}
</style>
