<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :visible.sync="dialogVisible"
      title="导入规则设置"
      append-to-body
      width="70%"
      class="export-dialog"
      top="8vh"
    >
      <div v-if="dialogVisible">
        <el-form :model="currentRow" :inline="false" ref="importSetting">
          <!-- <el-form-item label="导入类型" label-width="130px" prop="importType">
            <el-radio-group v-model="currentRow.importType">
              <el-radio label="main">主表</el-radio>
              <el-radio label="sub" :disabled="!importSubFields.length > 0"
                >主表与子表</el-radio
              >
              <el-radio label="sun" :disabled="!importSunFields.length > 0"
                >导入主表子表与孙表</el-radio
              >
            </el-radio-group>
          </el-form-item> -->
          <ht-form-item label-width="130px" label="导入主表">
            <el-tag>{{ boDef.boEnt.desc }}</el-tag>
          </ht-form-item>
          <el-form-item label="选择子表" label-width="130px" prop="importSub">
            <el-select
              v-model="importSub"
              placeholder="请选择"
              :multiple="true"
              value-key="name"
              style="width: 80%"
              @remove-tag="syncRemoeve"
            >
              <el-option
                v-for="item in importSubFields"
                :key="item.name"
                :label="item.desc"
                :value="{name: item.name, desc: item.desc}"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <ht-form-item
            v-if="sunEntList.length"
            label="选择孙表"
            label-width="130px"
            prop="importSun"
          >
            <el-select
              v-model="importSun"
              placeholder="请选择"
              :multiple="true"
              value-key="name"
              style="width: 80%"
            >
              <el-option
                v-for="item in sunEntList"
                :key="item.name"
                :label="item.desc"
                :value="{name: item.name, desc: item.desc}"
              >
              </el-option>
            </el-select>
          </ht-form-item>
          <el-form-item></el-form-item>

          <ht-form-item label="主键绑定" label-width="130px">
            <el-table
              :data="config"
              border
              stripe
              style="width: 80%"
              row-key="name"
              default-expand-all
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
              >
              <el-table-column
                label="实体"
                prop="desc"
                align="left"
              ></el-table-column>
              <el-table-column label="主键绑定" align="center" width="150px">
                <template slot-scope="scope">
                  <ht-select
                    v-model="scope.row.bindPk"
                    style="width: 120px"
                    :props="{key: 'name', value: 'desc'}"
                    :options="getOptions(scope.row.name)"
                  ></ht-select>
                </template>
              </el-table-column>
              <el-table-column label="表头行" width="180px">
                <template slot="header">
                  <el-tooltip
                    content="表头行坐标，从0开始，默认为0"
                    placement="top"
                    effect="dark"
                  >
                    <div>
                      表头行
                    </div>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <ht-input
                    style="width: 150px"
                    v-model="scope.row.rowIndex"
                  ></ht-input>
                </template>
              </el-table-column>
              <!-- <el-table-column label="列坐标" width="180px">
                <template slot="header">
                  <el-tooltip
                    content="表头行坐标，从0开始，默认为0"
                    placement="top"
                    effect="dark"
                  >
                    <div>
                      行起点
                    </div>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <ht-input
                    style="width: 150px"
                    v-model="scope.row.colIndex"
                  ></ht-input>
                </template>
              </el-table-column> -->
            </el-table>
          </ht-form-item>
          <ht-form-item label-width="130px">
            <template slot="label">
              <el-tooltip
                class="item"
                effect="dark"
                content="请先下载默认模板，在默认模板基础上修改。设置自定义模板时，请注意工作表sheet名称以及表头列主键和外键名称是否与默认模板一致，并且同一个sheet表避免出现相同列名称。"
                placement="top-end"
              >
                <i class="property-tip icon-notes" />
              </el-tooltip>
              <label>导入模板</label>
            </template>
            <ht-file
              v-model="currentRow.file"
              simplicity
              accept="xlsx"
              :limit="1"
            ></ht-file>
            <br />
            <el-button
              type="primary"
              icon="el-icon-download"
              style="margin-left: 10px"
              @click.stop="downloadTemplate"
              >下载模板</el-button
            >
          </ht-form-item>
          <ht-form-item label="数据规则" label-width="130px">
            <ht-radio
              v-model="currentRow.importDataRule"
              :options="[
                {key: '0', value: '插入新数据'},
                {key: '1', value: '删除原数据'}
              ]"
            />
          </ht-form-item>
          <ht-form-item
            v-if="currentRow.importDataRule == '0'"
            label="更新规则"
            label-width="130px"
          >
            <ht-radio
              v-model="currentRow.updateDataRule"
              :options="[
                {key: '0', value: '覆盖更新'},
                {key: '1', value: '重复跳过'}
              ]"
            />
          </ht-form-item>
          <ht-form-item label="导入行数限制" label-width="130px">
            <el-input-number
              style="width: 120px; margin-right: 10px"
              size="small"
              controls-position="right"
              v-model="currentRow.limit"
              :min="1"
              :max="20000"
              :step="10"
            ></el-input-number>
          </ht-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelImport">取 消</el-button>
        <el-button type="primary" @click="importOk()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'import-btn-setting-dialog',
  props: {
    boDef: {
      type: Object,
      default: () => {
        return {}
      }
    },
    templateKey: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      importSubFields: [],
      importSunFields: [],
      selectData: [],
      config: [],
      importSub: [],
      importSun: [],
      processing: false,
      currentRow: null
    }
  },
  watch: {
    importSub: {
      handler(args) {
        this.syncConfig.call(this, args)
      }
    },
    importSun: {
      handler(args) {
        this.syncConfig.call(this, args)
      }
    }
  },
  computed: {
    pkBindList() {
      let ret = []
      let mainEnt = this.boDef.boEnt
      ret.push({
        desc: `${mainEnt.desc}(主表)`,
        name: mainEnt.name
      })
      if (this.currentRow.importSub && this.currentRow.importSub.length) {
        this.currentRow.importSub.forEach(sub => {
          let subEnt = this.importSubFields.filter(
            item => item.name === sub.name
          )[0]
          subEnt &&
            ret.push({
              desc: `${subEnt.desc}(子表)`,
              name: subEnt.name
            })
        })
      }
      if (this.currentRow.importSun && this.currentRow.importSun.length) {
        this.currentRow.importSun.forEach(sun => {
          let sunEnt = this.importSunFields.filter(
            item => item.name === sun.name
          )[0]
          sunEnt &&
            ret.push({
              desc: `${sunEnt.desc}(孙表)`,
              name: sunEnt.name
            })
        })
      }
      return ret
    },
    header() {
      return {
        Authorization: `Bearer ${this.$store.state.login.currentUser.token}`
      }
    },
    actionUrl() {
      return window.context.portal + '/system/file/v1/upload'
    },
    sunEntList() {
      let {importSub} = this
      let ret = []
      if (!importSub || !importSub.length) {
        return ret
      }
      const this_ = this
      importSub.forEach(item => {
        let subEnt = this_.importSubFields.filter(
          option => option.name === item.name
        )[0]
        if (subEnt && subEnt.childEnts) {
          subEnt.childEnts.forEach(sun => {
            ret.push(sun)
          })
        }
      })
      return ret
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  },
  methods: {
    showDialog(row) {
      this.currentRow = row
      if (!this.currentRow.importDataRule) {
        this.$set(this.currentRow, 'importDataRule', '0')
      }
      if (!this.currentRow.updateDataRule) {
        this.$set(this.currentRow, 'updateDataRule', '0')
      }
      this.dialogVisible = true
      this.config = JSON.parse(JSON.stringify(row.config || []))
      this.importSub = JSON.parse(JSON.stringify(row.importSub || []))
      this.importSun = JSON.parse(JSON.stringify(row.importSun || []))
      this.syncConfig()
      this.initSubFields()
    },
    cancelImport() {
      this.dialogVisible = false
    },
    importOk() {
      this.currentRow.config = this.config
      this.currentRow.importSub = this.importSub
      this.currentRow.importSun = this.importSun
      this.dialogVisible = false
    },
    initSubFields() {
      this.importSubFields = this.boDef.boEnt.childEnts || []
      this.importSubFields.forEach(subEnt => {
        subEnt.childEnts &&
          subEnt.childEnts.forEach(sun => {
            this.importSunFields.push(sun)
          })
      })
    },
    handleRemove(file, fileList) {
      if (!fileList || fileList.length == 0) {
        delete this.currentRow.fileId
        delete this.currentRow.fileName
      }
    },
    beforeUpload() {},
    success(response) {
      const {fileId, fileName} = response
      this.currentRow.fileId = fileId
      this.currentRow.fileName = fileName
    },
    syncRemoeve(event) {
      let {name} = event
      let subEnt = this.importSubFields.filter(item => item.name === name)[0]
      if (!subEnt.childEnts || !subEnt.childEnts.length) {
        return
      }
      const sunNames = subEnt.childEnts.map(sun => sun.name)
      if (this.currentRow.importSun) {
        this.currentRow.importSun = this.currentRow.importSun.filter(
          item => !sunNames.includes(item.name)
        )
      }
    },
    getOptions(name) {
      let ent = null
      if (this.boDef.boEnt.name === name) {
        ent = this.boDef.boEnt
      } else {
        ent = []
          .concat(this.importSubFields)
          .concat(this.importSunFields)
          .filter(item => item.name === name)[0]
      }
      if (!ent) {
        return []
      }
      const {pkKey, fk} = ent
      let ret1 = [
        {
          name: pkKey,
          desc: '主键'
        },
        {
          name: fk,
          desc: '外键'
        }
      ]
      return ret1.concat(ent.attributeList)
    },
    downloadTemplate() {
      if (this.currentRow.fileId) {
        this.$http.download(
          `${window.context.portal}/system/file/v1/downloadFile?fileId=${this.currentRow.fileId}`
        )
        return
      }
      let data = {...this.currentRow}
      data['config'] = this.config
      data['importSub'] = this.importSub
      data['importSun'] = this.importSun
      this.$http.request({
        method: 'post',
        responseType: 'arraybuffer',
        data,
        url: `${window.context.form}/form/dataTemplate/v1/downloadTemplate?templateKey=${this.templateKey}`
      })
    },
    syncConfig() {
      if (!this.processing) {
        this.processing = true
        this.$nextTick(() => {
          this.processSyncConfig()
        })
      }
    },
    processSyncConfig() {
      this.processing = false
      let mainEnt = this.boDef.boEnt
      let mainConfig = this.config[0]
      if (!mainConfig) {
        mainConfig = {
          name: mainEnt.name,
          desc: mainEnt.desc,
          bindPk: mainEnt.pkKey,
          children: []
        }
        this.config.push(mainConfig)
      }
      if (this.importSub && this.importSub.length) {
        this.importSub.forEach(subItem => {
          let subEnt = this.importSubFields.filter(
            item => item.name === subItem.name
          )[0]
          let subConfig
          if (!mainConfig.children.some(child => child.name == subEnt.name)) {
            subConfig = {...subItem}
            subConfig.bindPk = subEnt.pkKey
            subConfig.children = []
            mainConfig.children.push(subConfig)
          } else {
            subConfig = mainConfig.children.filter(
              child => child.name === subEnt.name
            )[0]
          }
          let importSun = this.importSun.filter(item =>
            (subEnt.childEnts || []).some(item2 => item2.name == item.name)
          )
          importSun.forEach(sunItem => {
            let sunEnt = this.importSunFields.filter(
              item => item.name === sunItem.name
            )[0]
            let sunConfig
            if (!subConfig.children.some(child => child.name == sunEnt.name)) {
              sunConfig = {...sunItem}
              sunConfig.bindPk = sunEnt.pkKey
              sunConfig.children = []
              subConfig.children.push(sunConfig)
            } else {
              sunConfig = subConfig.children.some(
                child => child.name == sunEnt.name
              )[0]
            }
          })
          subConfig.children = subConfig.children.filter(item =>
            importSun.some(item2 => item2.name === item.name)
          )
        })
      }
      mainConfig.children = mainConfig.children.filter(item =>
        this.importSub.some(item2 => item2.name === item.name)
      )
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-form-item--small .el-form-item__error {
  position: static !important;
}
</style>
