<template>
  <div>
    <!-- 映射 -->
    <div v-loading="loading">
      <div class="header">
        <el-divider content-position="left">{{ $t('form.basic') }}</el-divider>
        <div>
          <el-row>
            <el-col :span="12">
              <span>
                {{ $t('form.db_table_name') }}：
                <el-select
                  v-model="tableName"
                  :placeholder="$t('placeholder.select')"
                  size="mini"
                  @change="changeDBColumnData"
                >
                  <el-option
                    v-for="item in dbOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  ></el-option>
                </el-select>
              </span>
            </el-col>
            <el-col :span="12">
              <span>
                {{ $t('form.sync_data') }}:
                <el-button size="mini" @click="synchronousDBData">{{
                  $t('btns.sync_data')
                }}</el-button>
              </span>
            </el-col>
          </el-row>
        </div>
        <el-divider content-position="left">{{ $t('form.config') }}</el-divider>
      </div>
      <div class="content">
        <el-table :data="mappingtb" :height="mappingHeight">
          <el-table-column min-width="60%" :label="$t('form.field_name')">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.fieldName"
                :placeholder="$t('placeholder.select')"
                size="small"
                class="px-2"
                @change="selectDBField(scope.row)"
              >
                <el-option
                  value="MAPPINGID"
                  :label="$t('form.key')"
                ></el-option>
                <el-option
                  v-for="item in scopeByFieldOption"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column min-width="60%" :label="$t('form.column_name')">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.columnName"
                :placeholder="$t('placeholder.select')"
                size="small"
                class="px-2"
                @change="selectColumnField(scope.row)"
              >
                <el-option
                  v-for="item in scopeByColumnOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <el-button
                size="small"
                @click="delDbParams(scope.$index)"
                type="danger"
                >{{ $t('btns.delete') }}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column :label="$t('form.op')" min-width="20%">
            <template slot="header">
              <el-button size="small" @click="addDbParams">{{
                $t('btns.add')
              }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 映射同步数据弹框 -->
    <el-dialog
      :title="$t('form.sync_data')"
      :visible.sync="synchronousDBDataDialog"
      width="30%"
      :before-close="cancelSynchronousDBData"
      :append-to-body="true"
    >
      <div>
        <span>{{ $t('form.domain') }}：</span>
        <el-select
          v-model="domainName"
          :placeholder="$t('placeholder.select')"
          size="mini"
        >
          <el-option
            v-for="item in domainOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSynchronousDBData" size="small">{{
          $t('btns.cancel')
        }}</el-button>
        <el-button
          type="primary"
          @click="confirmSynchronousDBData"
          size="small"
          >{{ $t('btns.sync_data') }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqDbTableMapping,
  getDbColumnMapping,
  reqSynchronousDBData,
  getModuleForm,
  getFieldData
} from '@/service/FormApi.js'

import { getDomainList } from '@/service/ReportApi.js'
export default {
  name: 'FormMapping',
  data() {
    return {
      tableName: '', // 数据库表格名称
      mappingtb: [], // 配置字段名称
      name: "", // 表单名称
      dbOptions: [],
      mappingHeight: 300,
      scopeByFieldOption: [], //字段名称选项
      scopeByColumnOption: [], // 	列名称选项

      synchronousDBDataDialog: false, // 同步数据弹框
      domainName: '', // 企业域值
      domainOptions: [], // 企业域选项值

      loading: false
    }
  },
  props: {
    type: Number, // 表单类型
    formId: String, // 表单id
    isEdit: Boolean
  },
  methods: {
    /**
     * 动态计算页面table高度
     */
    getScollerHeight() {
      setTimeout(() => {
        let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //60 头部， 32 面包屑， 41 第一层页签， 40 第二层页签， 50 列表标题， 71 查询， 20 父组件外边距, 40分页, 16 外边距
        //这个组件在父组件dialog中高度给的85%，54 弹窗标题 30 弹窗底部padding 50 第一季页签 20机动距离
        this.mappingHeight = clientHeight - 60 -32 -41 - 50 - 24*4 - 28; // 24: 分割线的margin， 28数据库表格名称
      }, 100);
    },
    /**
     * 校验表单
     */
    verifyMapping() {
      //todo
      if (this.mappingtb.length > 0 && this.type == 65536) {
        for (let i = 0; i < this.mappingtb.length; i++) {
          if (
            this.mappingtb[i].columnName == '' ||
            this.mappingtb[i].columnName == this.$t('btns.select')
          ) {
            this.$message.error(this.$t('placeholder.filed'))
            this.saveDisabled = false
            return false
          }
          if (
            this.mappingtb[i].fieldName == '' ||
            this.mappingtb[i].fieldName == this.$t('btns.select')
          ) {
            this.$message.error(this.$t('msg.choose_field'))
            this.saveDisabled = false
            return false
          }
        }
        let obj = {
          formName: this.name,
          tableName: this.tableName,
          columnMappings: this.mappingtb,
        }
        return JSON.stringify(obj)
      }

      let obj = {
        formName: this.name,
        tableName: this.tableName,
        columnMappings: this.mappingtb,
      }
      return JSON.stringify(obj)
    },
    /**
     * 映射 数据库值发生改变
     */
    changeDBColumnData() {
      this.getDbColumnMapping()
      this.mappingtb.forEach((elm) => {
        elm.columnName = this.$t('btns.select')
      })
    },

    /**
     * 映射 同步数据弹窗
     */
    synchronousDBData() {
      if (this.tableName === '') {
        return this.$message.error(this.$t('msg.select_db'))
      } else if (this.mappingtb.length === 0) {
        return this.$message.error(this.$t('msg.select_field'))
      } else if (
        this.mappingtb[0].field === '' ||
        this.mappingtb[0].column === ''
      ) {
        return this.$message.error(this.$t('placeholder.name'))
      }
      this.getDomainData()
      this.synchronousDBDataDialog = true
    },

    /**
     * 映射  企业域
     */
    getDomainData() {
      getDomainList({
        onSucess: (response) => {
          console.log(response)
          if (response.data.errcode == 0) {
            this.domainOptions = response.data.data
          }
        },
      })
    },

    /**
     * 映射数据库表格名称
     */
    getDbTableMapping() {
      let params = { appId: sessionStorage.getItem('appId') }
      reqDbTableMapping(params, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            let listObj = response.data.data
            let arr = []
            for (let i in listObj) {
              arr.push({
                value: listObj[i],
                label: listObj[i],
              })
            }
            this.dbOptions = arr
          }
        },
      })
    },

    /**
     * 映射 获取字段名称
     */
    getDBFieldOption() {
      let formId = this.formId
      getFieldData(formId, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            this.scopeByFieldOption = response.data.data
          }
        },
      })
    },

    /**
     * 映射 获取数据库列名称映射
     */
    getDbColumnMapping() {
      let params = {
        appId: sessionStorage.getItem('appId'),
        tableName: this.tableName,
      }
      getDbColumnMapping(params, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            let listObj = response.data.data
            let arr = []
            for (let i in listObj) {
              arr.push({
                value: listObj[i],
                label: listObj[i],
              })
            }
            this.scopeByColumnOption = arr
          }
        },
      })
    },

    /**
     * 添加
     */
    addDbParams() {
      this.mappingtb.push({ fieldName: '', columnName: '' })
    },
    /**
     * 删除
     */
    delDbParams(index) {
      this.mappingtb.splice(index, 1)
    },
    /**
     * 取消同步数据
     */
    cancelSynchronousDBData() {
      this.domainName === ''
      this.synchronousDBDataDialog = false
    },

    /**
     * 弹框确认数据
     */
    confirmSynchronousDBData() {
      if (this.domainName === '') {
        return this.$message.error(this.$t('msg.choose_domain'))
      }
      let params = {
        ...this.params,
        tableName: this.tableName,
        domainId: this.domainName,
        id: this.formId
      }
      reqSynchronousDBData(params, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            this.$message.success(this.$t('msg.sync_data_ss'))
          }
        },
      })
      this.synchronousDBDataDialog = false
    },

    /**
     * 表单映射-添加字段-选择字段名称
     */
    selectDBField(row) {
      let index = 0
      this.mappingtb.forEach((elm) => {
        if (elm.fieldName == row.fieldName && index != 0) {
          this.$message.error(this.$t('msg.field_occupied'))
        } else if (elm.fieldName == row.fieldName && index == 0) {
          index++
        }
      })
    },
    /**
     * 表单映射-添加字段-选择列名称
     */
    selectColumnField(row) {
      let index = 0
      this.mappingtb.forEach((elm) => {
        if (elm.columnName == row.columnName && index != 0) {
          this.$message.error(this.$t('msg.field_occupied'))
        } else if (elm.columnName == row.columnName && index == 0) {
          index++
        }
      })
    },

    /**
     * 获取表单映射详情
     */
    getMappingData(){
      this.loading = true
      getModuleForm(this.formId, {
        onSucess: (response) => {
          if (response.data.errcode == 0) {
            this.loading = false
            let data = response.data.data
            this.tableName = data.mappingStr ? JSON.parse(data.mappingStr).tableName : "", // 数据库表
            this.mappingtb = data.mappingStr ? JSON.parse(data.mappingStr).columnMappings : [] // 字段名称
            this.name = data.name

            if (this.tableName) this.getDbColumnMapping()
          }else{
            this.loading = false
          }
        },
      });
    }
  },
  mounted() {
    this.getScollerHeight()
    if(this.isEdit)
      this.getMappingData()
    this.getDbTableMapping()
    this.getDBFieldOption()
  },
}
</script>
<style lang='less' scoped>
</style>