<!-- 实体-新增实体 -->
<template>
  <a-modal
    :title="headTitle"
    :visible="show"
    :mask-closable="false"
    @ok="handleOk"
    @cancel="handleClose"
  >
    <div style="display: flex">
      <div style="width:130px;">
        <div style="width:100px;height:100px;overflow:hidden;border:1px solid #ddd">
          <img v-if="headImg" style="width:100px;height:100px;" :src="headImg" alt="头像">
        </div>
        <label
          class="btn btn-orange"
          for="uploads"
          style="display:inline-block;width: 100px;padding: 0;text-align: center;line-height: 28px;border:1px solid #ccc;margin-top: 20px;"
        >选择图片</label>
        <input
          id="uploads"
          type="file"
          :value="imgFile"
          style="position:absolute; clip:rect(0 0 0 0);display: none"
          accept="image/png, image/jpeg, image/gif, image/jpg"
          @change="uploadImg($event, 1)"
        >
      </div>
      <a-form :form="form" style="flex: 1">
        <a-form-item :label="TEXT.ENT + '名称:'">
          <a-input v-decorator="formRules.name" />
        </a-form-item>
        <a-form-item :label="TEXT.ENT + '描述:'">
          <a-input v-decorator="formRules.memo" type="textarea" />
        </a-form-item>
      </a-form>
    </div>
    <div v-if="!entityId">
      <a-table
        :columns="columns"
        :data-source="resultList"
        :pagination="false"
        size="small"
        row-key="attrClsID"
        bordered
      >
        <template slot="attrValueType" slot-scope="text">
          {{ attrClsType[text] }}
        </template>
        <template slot="attrValue" slot-scope="text,record">
          <!--{{record}}-->
          <editable-cell
            :record="record"
            :text="text"
            :editable="record.edit"
            @change="onCellChange(record,'attrValue', $event)"
            @close="closeCell(record)"
          />
          <!--<a-input placeholder="请输入属性值" v-model="record.attrValue" style="width: 120px;"/>-->
        </template>
      </a-table>
    </div>
  </a-modal>
</template>

<script>
import EditableCell from '../../views/common/editableCell'

const api = require('@/api')
const TEXT = window.USER_ROLE_LANGUAGE[window.USER_ROLE]
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
}
const columns = [
  {
    rowClassName: 'name',
    title: '名称',
    dataIndex: 'attrClsName',
    align: 'center'
  },
  {
    title: '数据类型',
    dataIndex: 'attrValueType',
    align: 'center',
    scopedSlots: { customRender: 'attrValueType' }
  },
  {
    title: '单位',
    dataIndex: 'attrUnit',
    align: 'center'
  },
  {
    title: '属性值',
    dataIndex: 'attrValue',
    width: '30%',
    scopedSlots: { customRender: 'attrValue' }
  }
]
export default {
  name: 'AddEntityModal',
  components: {
    EditableCell
  },
  // paramsId 实体类id  title：标题   entityName: 实体名字  entityId:实体id isLink:改变路由 entClsIcon: 实体图标
  props: ['paramsId', 'title', 'entityName', 'entityId', 'entityMemo', 'isLink', 'entClsIcon', 'isModel'],
  data() {
    return {
      TEXT,
      columns,
      attrClsType: this.$const.attrClsType,
      resultList: [], // 必填列表
      fileName: '', // 本机文件地址
      headImg: '',
      imgFile: '',
      formItemLayout,
      headTitle: '',
      form: this.$form.createForm(this),
      show: true,
      formRules: { // 所有验证规则
        name: [ // 用作标识，我们统一写成和表单提交字段一样
          'name', // 表单提交的字段
          {
            rules: [{ required: true, message: '此选项必填', whitespace: true }],
            initialValue: this.entityName
          }
        ],
        memo: [ // 用作标识，我们统一写成和表单提交字段一样
          'memo', // 表单提交的字段
          {
            rules: [{ required: false, message: '可以选择填' }],
            initialValue: this.entityMemo
          }
        ]
      }
    }
  },
  created() {
    const vm = this
    this.headTitle = this.title
    if (this.paramsId) { // 新增
      api.attrClass.getAttrClassById2(this.paramsId, 'ELEM').then(function(data) {
        const resultList = []
        data.forEach(v => {
          if (v.notNull) {
            v.edit = {
              abled: false
            }
            v.attrValue = ''
            resultList.push(v)
          }
        })
        vm.resultList = resultList
      })
    }
  },
  mounted() {
    //  判断是新增还是添加
    if (this.entityName) {
      this.headImg = this.entClsIcon
    }
  },
  methods: {
    // 选择本地图片
    uploadImg(e, num) {
      var max_size = 80// 20k
      var _this = this
      // 上传图片
      var file = e.target.files[0]
      _this.fileName = file.name
      var size = file.size
      if (size > max_size * 1024) {
        this.$message.warning('建议上传图标不要超过80KB')
      }
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG|JPEG|BMP)$/.test(e.target.value)) {
        alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
        return false
      }
      var reader = new FileReader()
      reader.onload = (e) => {
        let data
        data = e.target.result
        this.$open('cropperImgModal', {
          paramImgUrl: data
        }, function(data) {
          this.headImg = data.data
        })
      }
      // 转化为base64
      reader.readAsDataURL(file)
      // 转化为blob
      // reader.readAsArrayBuffer(file)
    },
    async getFormData() {
      var result = await this.$formValidateFields('form') // form的字符串
      // 在这里对form返回数据进行处理
      return result
    },
    async handleOk(e) {
      var result = await this.getFormData() // this是当前组件的this,  'form'此表单的名称，一定要是字符串
      const entClsID = this.paramsId // 实体类id
      const entId = this.entityId // 实体id
      const entName = result.name.trim() // 实体名字
      const uniqueMatchList = this.$checkSpecialChar(entName)
      if (uniqueMatchList.length > 0) {
        this.$message.error(`${this.isModel ? '模板' : '实体'}名称不能包含特殊字符【${uniqueMatchList.join('、')}】！`)
        return false
      }
      if (!result.memo) result.memo = ''
      const entMemo = result.memo.trim()
      const entIcon = (this.headImg && this.headImg != 'null') ? encodeURIComponent(this.headImg) : ''
      const notNullAttrVOList = []
      this.resultList.forEach(v => {
        notNullAttrVOList.push({ attrClsID: v.attrClsID, attrValue: v.attrValue })
      })
      if (entClsID) {
        // 新增实体
        if (notNullAttrVOList.some(v => { return !v.attrValue })) {
          this.$message.error('属性值必填')
          return false
        } else {
          api.entity.addEntity(entClsID, entName, entMemo, entIcon, notNullAttrVOList, this.isModel).then((data) => {
            if (data !== false) {
              if (this.isLink) {
                this.$trigger('entity:nodeCreated', data)
              }
              this.$close(data)
            }
          })
        }
      }
      if (entId) {
        // 修改实体
        api.entity.updateEntityName(entId, entName, entMemo, entIcon, this.isModel).then((data) => {
          if (data !== false) {
            if (this.isLink) {
              this.$trigger('entity:nodeUpdated', data)
            }
            this.$close(data)
          }
        })
      }
    },
    // 关闭模态窗
    handleClose(e) {
      this.$close(false)
    },
    closeCell(record) {
      record.edit.abled = false
    },
    onCellChange(target, data, value) {
      target.attrValue = value.toString()
      target.edit.abled = false
    }
  }
}
</script>

<style scoped>

</style>
