<template>
  <el-dialog
    width="65%"
    title="建模复制"
    :visible="dialogVisible"
    :before-close="handleClose"
    :destroy-on-close="true"
    append-to-body
    :close-on-click-modal="false"
  >
    <form v-form data-vv-scope="saveCopyForm">
      <table class="form-table" cellspacing="0" cellpadding="0" border="0">
        <tbody>
          <tr>
            <th width="140px" class="text-center">模型描述</th>
            <th width="140px" class="text-center">模型别名</th>
            <th width="140px" class="text-center">所属分类</th>
            <th width="140px" class="is-required text-center">新模型描述</th>
            <th width="140px" class="is-required text-center">新模型别名</th>
            <th width="140px" class="is-required text-center">新所属分类</th>
          </tr>
          <tr>
            <th width="140px" class="text-center">{{ boDef.description }}</th>
            <th width="140px" class="text-center">{{ boDef.alias }}</th>
            <th width="140px" class="text-center">{{ boDef.categoryName }}</th>
            <th width="140px" class="text-center">
              <ht-input
                v-model="boDef.newDescription"
                placeholder="请输入新模型描述"
                :validate="{required: true}"
                :maxlength="50"
                :showWordLimit="true"
              ></ht-input>
            </th>
            <th width="140px" class="text-center">
              <ht-input
                v-model="boDef.newAlias"
                placeholder="请输入新模型别名"
                autocomplete="off"
                v-pinyin="boDef.newDescription"
                validate="required: true|regex:^[a-zA-Z][a-zA-Z0-9_]*$,只能输入字母、数字、下划线，且以字母开头"
                :maxlength="50"
                :showWordLimit="true"
              ></ht-input>
            </th>
            <th width="140px" class="text-center">
              <EipSysTypeSelector
                placeholder="请选择分类"
                cat-id="9"
                v-model="boDef.newCategoryName"
                :sys-type-id.sync="boDef.newCategoryId"
                :validate="{required: true}"
              />
            </th>
          </tr>
        </tbody>
      </table>
      <el-table
        :data="boEnts"
        style="margin-top: 20px;"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'childEnts'}"
      >
        <el-table-column prop="desc" label="实体描述"> </el-table-column>
        <el-table-column prop="name" label="实体名称"> </el-table-column>
        <el-table-column prop="newDesc" label="新实体描述">
          <template slot-scope="{row}">
            <ht-input
              v-model="row.newDesc"
              placeholder="请输入新实体描述"
              :validate="{required: true}"
              @input="chineseFormat(row.newDesc, row)"
              :maxlength="50"
              :showWordLimit="true"
            ></ht-input>
          </template>
        </el-table-column>
        <el-table-column prop="newName" label="新实体名称"
          ><template slot-scope="{row}">
            <ht-input
              v-model="row.newName"
              placeholder="请输入新实体名称"
              :validate="{
                required: true,
                regex: {
                  exp: '^[a-zA-Z][a-zA-Z0-9_]{0,28}$',
                  message:
                    '只能输入字母、数字、下划线，且以字母开头,长度不能超过28'
                }
              }"
              :maxlength="28"
              :showWordLimit="true"
            ></ht-input>
          </template>
        </el-table-column>
      </el-table>
    </form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{ $t('eip.common.cancel') }}</el-button>
      <el-button type="primary" @click="saveCopy">{{
        $t('eip.common.save')
      }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import EipSysTypeSelector from '@/components/selector/EipSysTypeSelector.vue'
import form from '@/api/form.js'
import req from '@/request.js'
export default {
  components: {EipSysTypeSelector},
  data() {
    return {
      defId: '',
      boDef: {
        alias: '',
        description: '',
        categoryName: '',
        newAlias: '',
        newDescription: '',
        newCategoryId: '',
        newCategoryName: ''
      },
      boEnts: [],
      dialogVisible: false
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  },
  methods: {
    chineseFormat(desc, row) {
      setTimeout(function() {
        req
          .request({
            url: `${window.context.uc}/base/tools/v1/getPinyin`,
            method: 'GET',
            params: {chinese: desc, type: 0}
          })
          .then(res => {
            if (res.data.state) {
              row.newName = res.data.value
            }
          })
      }, 500)
    },
    showDialog(defId) {
      this.defId = defId
      form.getEntData(defId, resp => {
        this.boDef = {
          alias: resp.data.alias,
          description: resp.data.description,
          categoryName: resp.data.categoryName,
          newAlias: '',
          newDescription: '',
          newCategoryId: '',
          newCategoryName: ''
        }
        this.boEnts = []
        if (resp.data && resp.data.boEnt) {
          this.handleEnt([resp.data.boEnt])
        }
        this.dialogVisible = true
      })
    },
    handleEnt(boEnt) {
      boEnt.forEach(e => {
        let newE = {
          id: e.id,
          name: e.name,
          desc: e.desc,
          newName: '',
          newDesc: ''
        }
        if (e.childEnts) {
          newE.childEnts = []
          e.childEnts.forEach(sub => {
            let newSub = {
              id: sub.id,
              name: sub.name,
              desc: sub.desc,
              newName: '',
              newDesc: ''
            }
            if (sub.childEnts) {
              newSub.childEnts = []
              sub.childEnts.forEach(sun => {
                let newSun = {
                  id: sun.id,
                  name: sun.name,
                  desc: sun.desc,
                  newName: '',
                  newDesc: ''
                }
                newSub.childEnts.push(newSun)
              })
            }
            newE.childEnts.push(newSub)
          })
        }
        this.boEnts.push(newE)
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    saveCopy() {
      let param = JSON.parse(JSON.stringify(this.boDef))
      let entsMap = this.nest2tile(this.boEnts)
      if (!entsMap) {
        return
      }
      param.entsMap = entsMap

      let dataList = _.cloneDeep(param)
      delete dataList.description
      delete dataList.categoryName
      for (let item in dataList.entsMap) {
        
        if (dataList.entsMap[item].id) {
          delete dataList.entsMap[item].id
        }
        if (dataList.entsMap[item].name) {
          delete dataList.entsMap[item].name
        }
        if (dataList.entsMap[item].desc) {
          delete dataList.entsMap[item].desc
        }
        if (dataList.entsMap[item].childEnts) {
          delete dataList.entsMap[item].childEnts
        }
      }
      this.$validator.validateAll('saveCopyForm').then(result => {
        if (result) {
          form.saveBoCopy(dataList).then(resp => {
            if (resp.data && resp.data.state) {
              this.$message.success(resp.data.message || '操作成功')
              this.handleClose()
              this.$emit('onConfirm', null)
            }
          })
        } else {
          let arr = this.$validator.errors.items.filter(
            item => item.scope == 'saveCopyForm'
          )
          this.$message({
            showClose: true,
            message: `有${arr.length}个字段未通过校验，请正确填写表单内容。`,
            type: 'warning'
          })
        }
      })
    },
    nest2tile(ents) {
      let result = {},
        newNameSet = new Set()
      for (let i = 0; i < ents.length; i++) {
        const e = ents[i]
        if (newNameSet.has(e.newName)) {
          this.$message.warning(`存在重名的实体名称：${e.newName}`)
          return null
        }
        result[e.name] = e
        newNameSet.add(e.newName)
        //子表
        if (e.childEnts) {
          for (let j = 0; j < e.childEnts.length; j++) {
            const sub = e.childEnts[j]
            if (newNameSet.has(sub.newName)) {
              this.$message.warning(`存在重名的实体名称：${sub.newName}`)
              return null
            }
            result[sub.name] = sub
            newNameSet.add(sub.newName)
            //孙表
            if (sub.childEnts) {
              for (let g = 0; g < sub.childEnts.length; g++) {
                const sun = sub.childEnts[g]
                if (newNameSet.has(sun.newName)) {
                  this.$message.warning(`存在重名的实体名称：${sun.newName}`)
                  return null
                }
                result[sun.name] = sun
                newNameSet.add(sun.newName)
              }
            }
          }
        }
      }
      return result
    }
  }
}
</script>
<style scoped>
.text-center {
  text-align: center;
}
</style>
