<template>
  <div class="card">
    <div class="card__header">
      <div class="card__button">
        <el-button @click="addEntRows()" type="primary">添加实体</el-button>
        <el-button @click="addEntExts()">添加外部表</el-button>
      </div>
    </div>
    <div class="card__body">
      <el-scrollbar class="scrollbar-fullheight">
        <div
          class="card__ent"
          v-for="(item, index) in formData.ents"
          :key="index"
          :class="{active: item.isCheck && currentSunIndex < 0}"
        >
          <div>
            <div class="card__ent--header flex">
              <div class="card__ent--title" @click="getEntsByIndex(index)">
                {{ item.show }}
              </div>
              <div class="card__ent--btngroup flex">
                <div style="display:flex">
                  <span
                    v-if="item.isExternal == '1'"
                    class="el-icon-search"
                    title="查看外部表详情"
                    @click.stop="addEntExts(index)"
                  ></span>
                  <span
                    v-if="item.isExternal != '1' && item.relation != 'main'"
                    class="el-icon-plus"
                    title="添加孙实体"
                    @click.stop="addGrandSonEnt(index)"
                  ></span>
                  <span
                    class="el-icon-copy-document"
                    title="复制"
                    @click.stop="copyEnt(item)"
                  ></span>
                </div>
                <div class="delete-btn__wrap" style="marginLeft: 10px">
                  <el-popconfirm
                    title="确定删除吗？"
                    @onConfirm="deleteEntRows(index)"
                    @confirm="deleteEntRows(index)"
                    v-if="!item.id || !deployed"
                  >
                    <span
                      title="删除"
                      class="el-icon-delete"
                      slot="reference"
                    ></span>
                  </el-popconfirm>
                  <el-popconfirm
                    class="external-delete"
                    title="确定删除吗？此操作会把子实体下的所有孙实体一并删除并且不可逆转且表单需要重新配置！"
                    icon="el-icon-info"
                    icon-color="red"
                    @onConfirm="deleteEnt(index)"
                    @confirm="deleteEnt(index)"
                    v-if="
                      item.id && item.isExternal == 1 && item.type != 'main'
                    "
                  >
                    <span
                      title="删除"
                      class="el-icon-delete"
                      slot="reference"
                    ></span>
                  </el-popconfirm>
                </div>
              </div>
            </div>
            <div class="card__ent--body">
              <ht-form-item
                label="实体描述"
                class="is-required"
                label-width="90px"
              >
                <ht-input
                  v-model="item.comment"
                  placeholder="请输入内容"
                  :id="'changeEntsDesc' + index"
                  type="textarea"
                  class="ent-desc-textarea"
                  autosize
                  @input="
                    chineseFormat(
                      'entName' + index,
                      formData.ents,
                      'name',
                      index,
                      item.comment,
                      'comment'
                    )
                  "
                  :maxlength="50"
                  :showWordLimit="true"
                  :validate="{required: true}"
                  @blur="entBlur(index)"
                ></ht-input>
              </ht-form-item>

              <ht-form-item
                label="实体名称"
                class="is-required"
                label-width="90px"
                custom-colon
              >
                <ht-input
                  :disabled="item.id && deployed"
                  v-model="item.name"
                  placeholder="请输入内容"
                  :id="'entName' + index"
                  :name="'entName' + index"
                  :validate="{
                    required: true,
                    regex: {
                      exp: '^[a-zA-Z][a-zA-Z0-9_]{0,28}$',
                      message:
                        '只能输入字母、数字、下划线，且以字母开头,长度不能超过28'
                    }
                  }"
                  :maxlength="28"
                  :showWordLimit="true"
                  @blur="entBlur(index)"
                ></ht-input>
              </ht-form-item>

              <ht-form-item
                v-if="item.relation != 'main'"
                label="实体关系"
                label-width="90px"
                custom-colon
              >
                <ht-radio
                  option-layout="horizontal"
                  :disabled="item.id && deployed"
                  :options="relationData"
                  v-model="item.relation"
                ></ht-radio>
              </ht-form-item>
            </div>
          </div>
          <div v-if="item.children && item.children.length > 0" class="sun_ent">
            <el-collapse v-model="activeNames" accordion>
              <el-collapse-item
                v-for="(v, i) in item.children"
                :class="{active: currentActiveKey === `${index}_${i}`}"
                :key="i"
                :name="`${index}_${i}`"
              >
                <div
                  class="flex card__acd--header"
                  slot="title"
                  @click="getGrandSonEntsByIndex(i, index, v)"
                >
                  <span class="card__acd--title">{{ v.show }}</span>
                  <div class="card__acd--btngroup sun-top-operate">
                    <span
                      v-if="item.isExternal == '1' && i == currentSunIndex"
                      class="el-icon-search"
                      title="查看外部表详情"
                      @click.stop="addEntExts(index, i)"
                    ></span>
                    <span
                      v-if="
                        i == currentSunIndex &&
                          currentActiveKey === `${index}_${i}`
                      "
                      class="el-icon-copy-document"
                      title="复制"
                      @click.stop="copyEnt(v)"
                    ></span>
                    <el-popover
                      placement="top"
                      width="160"
                      trigger="manual"
                      v-if="
                        (!deployed || !v.id) &&
                          i == currentSunIndex &&
                          currentActiveKey === `${index}_${i}`
                      "
                      v-model="popoverVisible"
                    >
                      <p class="warn-icon-wrap">
                        <i class="el-icon-question"></i>确定删除吗？
                      </p>
                      <div style="text-align: right; margin: 0">
                        <el-button
                          size="mini"
                          type="text"
                          @click="popoverVisible = false"
                          >取消</el-button
                        >
                        <el-button
                          type="primary"
                          size="mini"
                          @click="deleteGrandSonEntRows(i, index)"
                          >确定</el-button
                        >
                      </div>
                      <span
                        title="删除"
                        class="el-icon-delete"
                        slot="reference"
                        @click.stop="handleDelSun"
                      ></span>
                    </el-popover>
                  </div>
                </div>
                <div class="card__acd--body">
                  <ht-form-item
                    label="实体描述"
                    class="is-required"
                    label-width="90px"
                    custom-colon
                  >
                    <ht-input
                      v-model="v.desc"
                      placeholder="请输入内容"
                      class="ent-desc-textarea"
                      :id="'changeGrandSonEntsDesc_' + index + '_' + i"
                      @blur="entBlur(i)"
                      @input="
                        chineseFormat(
                          'changeGrandSonEntsName_' + index + '_' + i,
                          formData.ents[index].children,
                          'name',
                          i,
                          v.desc,
                          'desc'
                        )
                      "
                      :validate="{required: true}"
                      :maxlength="50"
                      :showWordLimit="true"
                    ></ht-input>
                  </ht-form-item>

                  <ht-form-item
                    label="实体名称"
                    class="is-required"
                    label-width="90px"
                    custom-colon
                  >
                    <ht-input
                      :disabled="v.id && deployed"
                      v-model="v.name"
                      placeholder="请输入内容"
                      :id="'changeGrandSonEntsName_' + index + '_' + i"
                      :name="'changeGrandSonEntsName_' + index + '_' + i"
                      :validate="{
                        required: true,
                        regex: {
                          exp: '^[a-zA-Z][a-zA-Z0-9_]{0,28}$',
                          message:
                            '只能输入字母、数字、下划线，且以字母开头,长度不能超过28'
                        }
                      }"
                      :maxlength="28"
                      :showWordLimit="true"
                    ></ht-input>
                  </ht-form-item>
                  <ht-form-item
                    label="实体关系"
                    label-width="90px"
                    custom-colon
                  >
                    <ht-radio
                      :disabled="v.id && deployed"
                      :options="relationData"
                      v-model="v.relation"
                    ></ht-radio>
                  </ht-form-item>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <el-dialog
      width="30%"
      title="实体复制"
      :visible="copyDialogVisible"
      :destroy-on-close="true"
      append-to-body
      :close-on-click-modal="false"
      :before-close="() => (copyDialogVisible = false)"
    >
      <form v-form data-vv-scope="copyForm">
        <ht-form-item label="新实体描述">
          <ht-input
            v-model="curEnt.desc"
            placeholder="请输入实体描述"
            :validate="{required: true}"
            :maxlength="50"
            :showWordLimit="true"
          ></ht-input>
        </ht-form-item>
        <ht-form-item label="新实体名称">
          <ht-input
            v-model="curEnt.name"
            placeholder="请输入实体名称"
            v-pinyin="curEnt.desc"
            :validate="{
              required: true,
              regex: {
                exp: '^[a-zA-Z][a-zA-Z0-9_]{0,28}$',
                message:
                  '只能输入字母、数字、下划线，且以字母开头,长度不能超过28'
              }
            }"
            :maxlength="28"
            :showWordLimit="true"
          />
        </ht-form-item>
        <ht-form-item label="类型">
          <ht-select
            v-model="copyType"
            validate="required"
            :options="[
              {key: 1, value: '子实体'},
              {key: 2, value: '孙实体'}
            ]"
          />
        </ht-form-item>
        <ht-form-item label="所属子实体" v-if="copyType === 2">
          <ht-select
            v-model="subIndex"
            :options="formData.ents"
            validate="required"
          >
            <template slot-scope="{options}">
              <el-option
                v-for="(item, index) in options"
                :key="index"
                :label="item.desc || item.comment"
                :value="index"
                :disabled="item.relation === 'main'"
              >
              </el-option>
            </template>
          </ht-select>
        </ht-form-item>
      </form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => (copyDialogVisible = false)">{{
          $t('eip.common.cancel')
        }}</el-button>
        <el-button type="primary" @click="confirmCopy()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import req from '@/request.js'
export default {
  name: 'BusinessObjEnts',
  props: ['formData'],
  data() {
    return {
      relationData: [
        {key: 'onetoone', value: '一对一'},
        {key: 'onetomany', value: '一对多'}
      ],
      activeNames: ['-1'],
      currentEntType: null, //当前编辑的实体类型：main,sub,sun
      currentSunIndex: -1, //当前编辑的孙实体索引
      copyDialogVisible: false,
      copyType: 1,
      subIndex: null,
      curEnt: {},
      currentActiveKey: '',
      popoverVisible: false
    }
  },
  created() {
    this.$validator = this.$root.$validator
  },
  computed: {
    // 业务对象是否已经发布
    deployed: function() {
      return this.formData && this.formData.deployed == 1
    }
  },
  methods: {
    handleDelSun() {
      this.popoverVisible = !this.popoverVisible
    },
    copyEnt(ent) {
      this.curEnt = JSON.parse(JSON.stringify(ent))
      this.curEnt.desc = this.curEnt.desc || this.curEnt.comment
      this.copyType = 1
      this.subIndex = null
      this.copyDialogVisible = true
    },
    confirmCopy() {
      this.$validator.validateAll('copyForm').then(result => {
        if (result) {
          //外部表
          if (this.curEnt.isExternal == '1') {
            this.emitExtCopy()
          } else {
            this.emitCopy()
          }
          this.copyDialogVisible = false
        }
      })
    },
    emitCopy() {
      let obj = {
        desc: this.curEnt.desc,
        comment: this.curEnt.desc,
        name: this.curEnt.name,
        packageId: '',
        show: this.copyType === 1 ? '子实体' : '孙实体',
        children: [],
        relation:
          this.curEnt.relation === 'main' ? 'onetomany' : this.curEnt.relation,
        attributeList: this.curEnt.attributeList || [],
        status: '',
        isCheck: true
      }
      if (obj.attributeList) {
        obj.attributeList.forEach(e => {
          e.id = null
          e.entId = null
        })
      }
      //复制为子实体
      if (this.copyType === 1) {
        this.$emit('addEntRows', obj)
      } else {
        //复制为孙实体
        this.$emit('addGrandSonEnt', this.subIndex, obj)
      }
    },
    emitExtCopy() {
      let obj = this.curEnt
      delete obj.id
      delete obj.pkVal
      obj.show = this.copyType === 1 ? '子实体-外' : '孙实体-外'
      obj.relation =
        this.curEnt.relation === 'main' ? 'onetomany' : this.curEnt.relation
      if (obj.attributeList) {
        obj.attributeList.forEach(e => {
          e.id = null
          e.entId = null
        })
      }
      //复制为子实体
      if (this.copyType === 1) {
        this.$emit('addEntRows', obj)
      } else {
        //复制为孙实体
        this.$emit('addGrandSonEnt', this.subIndex, obj)
      }
    },
    deleteEnt(index) {
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteEntRows(index)
      })
    },
    addEntRows() {
      this.$emit('addEntRows')
    },
    addEntExts(index, i) {
      this.$emit('addEntExts', index, i)
    },
    getEntsByIndex(index) {
      this.currentActiveKey = ''
      this.$emit('getEntsByIndex', index)
      setTimeout(() => {
        this.$forceUpdate()
      }, 50)
      this.currentEntType = index > 0 ? 'sub' : 'main'
    },
    addGrandSonEnt(index) {
      this.$emit('addGrandSonEnt', index)
    },
    deleteEntRows(index) {
      if (index - 1 >= 0) {
        //删除实体之后自动选择上一个实体
        this.$emit('getEntsByIndex', index - 1, 'delete')
      }
      this.$emit('deleteEntRows', index)
    },
    entBlur(index) {
      this.$emit('entBlur', index)
    },
    chineseFormat(id, list, param, index, v, name) {
      if (v) {
        var vChange = v.split('').filter(item => {
          return item && item.trim()
        }).join('')

        list[index][name] = vChange
      }
      this.$emit('chineseFormat', id, list, param, index, vChange)
    },
    getGrandSonEntsByIndex(i, index, clickItem) {
      this.currentActiveKey = `${index}_${i}`
      this.currentSunIndex = i
      this.$emit('getGrandSonEntsByIndex', i, index)
      this.currentEntType = 'sun'
    },
    deleteGrandSonEntRows(i, index) {
      this.$emit('deleteGrandSonEntRows', i, index)
      this.popoverVisible = false
    }
  },
  watch: {
    currentEntType: function(newVal) {
      // 不再编辑孙实体时重置 索引为-1
      if (newVal != 'sun') {
        this.currentSunIndex = -1
        this.activeNames = [-1]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.card {
  height: 100%;
  color: $--color-text-primary;
  /deep/ .el-form-item__label {
    font-size: 12px;
  }
  /deep/ .el-radio-horizontal {
    margin-right: 15px;
    padding-top: 10px;
  }
  .card__header {
    justify-content: space-around;
  }
  .card__button {
    margin: 16px;
  }
  .card__body {
    height: 100%;
  }
  .height-32 {
    height: 32px;
  }
  .float-l {
    float: left;
  }
  .scrollbar-fullheight {
    height: 100%;
  }
  .inputs {
    width: 100% !important;
  }
  .card__ent {
    width: 281px;
    border-radius: 2px;
    background: $--color-white;
    border: 2px solid #dcdee0;
    margin-bottom: 15px;
    margin-left: 15px;
  }
  .card__ent.active {
    border-color: #409eff;
    .card__ent--header {
      margin: 0;
      .card__ent--title,
      .card__ent--btngroup span {
        color: #409eff;
        visibility: visible;
      }
      .card__ent--title {
        flex: 1;
      }
      .card__ent--btngroup {
        width: 62px;
        justify-content: flex-end;
      }
    }
  }
  .card__ent--header {
    height: 30px;
    margin: 0px;
    background: #f6f6f6;
    border-bottom: 1px solid #dcdee0;
    border-top-left-radius: 2px;
    border-top-right-radius: 2px;
    justify-content: space-between;
  }
  .card__ent--title {
    cursor: default;
    line-height: 30px;
    font-weight: 700;
    margin-left: 10px;
    flex: 1;
  }
  .card__ent--btngroup {
    margin-right: 10px;
    width: 62px;
    justify-content: flex-end;
  }
  .card__ent--btngroup span {
    visibility: hidden;
    cursor: pointer;
    font-size: 14px;
    font-weight: 700;
  }
  .card__ent--btngroup span + span {
    margin-left: 10px;
  }

  /** 孙实体 begin **/
  .sun_ent {
    .active {
      border: 2px solid #409eff;
    }
    .el-collapse-item /deep/ .el-collapse-item__header.is-active {
      border-bottom: 1px solid $--border-color-base;
      margin-left: 0px;
      font-size: 13px;
    }
    .el-collapse-item /deep/ .el-collapse-item__content {
      padding: 0px;
    }
    .el-collapse-item /deep/ .el-collapse-item__wrap {
      border-bottom-left-radius: 5px;
      border-bottom-right-radius: 5px;
      border-bottom: 1px solid #ebeef5;
    }
    >>> .el-collapse-item__header {
      border: 1px solid #ebeef5;
      font-size: 13px;
      font-weight: 600;
      margin-left: 0px;
    }
    >>> .el-collapse-item__arrow {
      display: block !important;
    }
    >>> .el-collapse {
      border: 1px solid #ebeef5;
    }
    .card__acd--header {
      width: calc(100% - 30px);
      height: 100%;
      justify-content: space-between;
    }
    .card__acd--title {
      cursor: default;
      line-height: 30px;
      font-weight: 700;
      margin-left: 10px;
    }
    .card__acd--btngroup span {
      font-size: 14px;
      font-weight: 700;
    }
    .card__acd--btngroup span + span {
      margin-left: 10px;
    }
    .el-collapse-item.active /deep/ .el-collapse-item__header {
      background: #f6f6f6;
      border: 1px solid #dcdee0;
      margin-left: 0px;
      font-size: 13px;
    }
  }
  /** 孙实体 end **/
}
/deep/.el-textarea /deep/.el-input__count {
  height: 29px;
  bottom: 1px;
}
.card__ent--body,
.card__acd--body {
  padding: 12px !important;
  /deep/ .el-form-item__label {
    text-align: left;
    float: none;
    word-break: break-word;
  }
  /deep/.el-form-item__content {
    margin-left: 0 !important;
    .ent-desc-textarea{
      .el-textarea__inner{
        min-height: 32px !important;
      }
    }
  }
}
.warn-icon-wrap {
  i {
    color: rgb(255, 153, 0);
    margin-right: 6px;
  }
}
</style>
