<!-- 实体类-基础属性 -->
<template>
  <div class="flex-col">
    <a-spin :spinning="spinning">
      <div>
        <a-button
          v-if="type === 'CIDX' || ENTCLS_ELEM_NEW_BTN"
          class="openAddRelationSty"
          @click="openModel()"
        >新增属性类</a-button>
        <a-button
          v-if="
            (type === 'ELEM' && ENTCLS_ELEM_ADD_BTN) ||
              (type === 'MIME' && ENTCLS_MIME_ADD_BTN)
          "
          class="openAddRelationSty"
          style="margin-left:10px;"
          @click="checkAttrClass()"
        >添加属性
        </a-button>
        <a-button
          v-if="type === 'NONE'"
          class="openAddRelationSty"
          style="margin-left:10px;"
          @click="handleMerage"
        >合并</a-button>
      </div>
      <div ref="tableWrapper" class="flex1 flex-col">
        <a-table
          :pagination="false"
          class="flex1"
          row-key="attrClsID"
          :columns="columns"
          :data-source="data"
          :row-selection="rowSelection"
          size="small"
          bordered
        >
          <!--可编辑（'attrClsName','attrUnit'）-->
          <template
            v-for="col in ['attrClsName', 'attrUnit', 'attrClsMemo']"
            :slot="col"
            slot-scope="text, record"
          >
            <div :key="col">
              <a-input
                v-if="record.editable"
                style="margin: -5px 0"
                :value="text"
                @change="
                  (e) => handleChange(e.target.value, record.attrClsID, col)
                "
              />
              <template v-else>
                <div :title="text">{{ text | ellipsis(10) }}</div>
              </template>
            </div>
          </template>
          <template slot="attrValueType" slot-scope="text">
            <!--<a-select v-if="record.editable" style="width:100%"-->
            <!--v-model="text"-->
            <!--@change="e => handleChange(text, record.attrClsID, 'attrValueType')">-->
            <!--<a-select-option :value="key" v-for="(value,key) in attrClsType" :key="key">{{value}}-->
            <!--</a-select-option>-->
            <!--</a-select>-->
            <template>
              {{ attrClsType[text] }}
            </template>
          </template>
          <template slot="noneOperation" slot-scope="text, record">
            <a-popconfirm
              title="删除待审属性？"
              ok-text="Yes"
              cancel-text="No"
              @confirm="deleteAttr(record.attrClsID)"
              @cancel="deleteCancel"
            >
              <a-button size="small" class="cancel-sty"><a>删除</a></a-button>
            </a-popconfirm>
            <a-button
              size="small"
              class="cancel-sty"
              @click="transferMerage(record.attrClsID)"
            ><a>迁移</a>
            </a-button>
            <a-button
              size="small"
              class="cancel-sty"
              @click="adjustAttrModal(record)"
            ><a>调整</a></a-button>
          </template>
          <!--备注-->
          <template slot="attrClsBz" slot-scope="text">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ text }}</span>
              </template>
              {{ text | ellipsis(5) }}
            </a-tooltip>
          </template>
          <!--设置必填-->
          <template slot="isBT" slot-scope="text, record">
            <a-checkbox disabled :checked="record.notNull" />
          </template>
          <template slot="domain" slot-scope="text, record">
            <!--{{text}}-->
            <!--{{record}}-->
            <div v-if="record.attrValueType === 'TEXT'">
              {{ text | filterTest }}
            </div>
            <div
              v-if="
                record.attrValueType === 'LONG' ||
                  record.attrValueType === 'DOUBLE'
              "
            >
              <span>{{ text | filterMinValue }}</span>
              <span>{{ text | filterMaxValue }}</span>
            </div>
          </template>

          <!--操作按钮-->
          <template slot="operation" slot-scope="text, record">
            <div v-if="record.isEdit === 'T'" class="editable-row-operations">
              <span>
                <a-button
                  v-if="type === 'ELEM'"
                  size="small"
                  @click="updates(record)"
                ><a>批量更新</a></a-button>
                <a-button v-if="isShowTag" size="small"><a>运行</a></a-button>
                <a-button
                  v-if="isShowTag"
                  class="cancel-sty"
                  size="small"
                  @click="openCheckTargetModal(record.attrClsID)"
                ><a>选择指标</a></a-button>
                <a-button
                  v-if="ENTCLS_ELEM_EDIT_BTN || ENTCLS_MIME_EDIT_BTN"
                  class="cancel-sty"
                  size="small"
                ><a @click="editAttrClass(record)">编辑</a></a-button>
                <a-popconfirm
                  title="删除基本属性？"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="deleteAttr(record.attrClsID)"
                  @cancel="deleteCancel"
                >
                  <a-button size="small" class="cancel-sty"><a>删除</a></a-button>
                </a-popconfirm>
              </span>
            </div>
          </template>
        </a-table>
      </div>
    </a-spin>
  </div>
  <!--</a-col>-->
  <!--</a-row>-->
</template>

<script>
const api = require('@/api')
const version = window.global.const.version
const data = []
// 表头定义
const columnDefine = {
  attrClsName: {
    title: '名称',
    dataIndex: 'attrClsName',
    width: '20%',
    align: 'center',
    scopedSlots: { customRender: 'attrClsName' }
  },
  attrUnit: {
    title: '单位',
    dataIndex: 'attrUnit',
    width: '10%',
    align: 'center',
    scopedSlots: { customRender: 'attrUnit' }
  },
  attrValueType: {
    title: '数据类型',
    dataIndex: 'attrValueType',
    width: '10%',
    align: 'center',
    scopedSlots: { customRender: 'attrValueType' }
  },
  domain: {
    title: '值范围',
    dataIndex: 'domain',
    width: '15%',
    align: 'center',
    scopedSlots: { customRender: 'domain' }
  },
  applyNum: {
    title: '使用个数',
    dataIndex: 'entUseCount',
    width: '10%',
    align: 'center',
    scopedSlots: { customRender: 'entUseCount' }
  },
  isBT: {
    title: '是否必填',
    dataIndex: 'isBT',
    width: '8%',
    align: 'center',
    scopedSlots: { customRender: 'isBT' }
  },
  noneOperation: {
    // 待审下的操作
    title: '操作',
    dataIndex: 'operation',
    width: '30%',
    align: 'center',
    scopedSlots: { customRender: 'noneOperation' }
  },
  operation: {
    title: '操作',
    dataIndex: 'operation',
    width: '30%',
    align: 'center',
    scopedSlots: { customRender: 'operation' }
  },
  attrClsMemo: {
    title: '描述',
    dataIndex: 'attrClsMemo',
    width: '10%',
    align: 'center',
    scopedSlots: { customRender: 'attrClsMemo' }
  },
  attrClsBz: {
    title: '描述',
    dataIndex: 'attrClsMemo',
    width: '20%',
    align: 'center',
    scopedSlots: { customRender: 'attrClsBz' }
  }
}
const columnMap = {
  // 基本
  ELEM: [
    columnDefine.attrClsName,
    columnDefine.attrUnit,
    columnDefine.attrValueType,
    columnDefine.domain,
    columnDefine.attrClsMemo,
    columnDefine.isBT,
    columnDefine.operation
  ],
  // 无类型
  NONE: [
    columnDefine.attrClsName,
    columnDefine.attrUnit,
    columnDefine.attrValueType,
    columnDefine.applyNum,
    columnDefine.attrClsBz,
    columnDefine.noneOperation
  ],
  // 能力
  CIDX: [
    columnDefine.attrClsName,
    columnDefine.attrUnit,
    columnDefine.attrValueType,
    columnDefine.domain,
    columnDefine.attrClsMemo,
    columnDefine.isBT,
    columnDefine.operation
  ],
  //  多媒体
  MIME: [
    columnDefine.attrClsName,
    columnDefine.attrUnit,
    columnDefine.domain,
    columnDefine.attrClsMemo,
    columnDefine.isBT,
    columnDefine.operation
  ]
}
export default {
  name: 'AttrEditor',
  filters: {
    filterTest(text) {
      if (!text) {
        return ''
      } else {
        return JSON.parse(text).domainKey
      }
    },
    filterMinValue(text) {
      if (!text) {
        return ''
      } else {
        return JSON.parse(text).minValue
          ? '最小值:' + JSON.parse(text).minValue
          : ''
      }
    },
    filterMaxValue(text) {
      if (!text) {
        return ''
      } else {
        return JSON.parse(text).maxValue
          ? '最大值:' + JSON.parse(text).maxValue
          : ''
      }
    }
  },
  data() {
    this.cacheData = data.map((item) => ({ ...item }))
    return {
      // 权限控制
      ENTCLS_ELEM_ADD_BTN: true,
      ENTCLS_ELEM_EDIT_BTN: true,
      ENTCLS_MIME_ADD_BTN: true,
      ENTCLS_MIME_EDIT_BTN: true,
      ENTCLS_ELEM_NEW_BTN: true,

      attrClsType: this.$const.attrClsType,
      id: null,
      type: '',
      data: [],
      tableHeight: {},
      selectedRows: [], // 选中的待审属性列表
      selectedRowKeys: [],
      spinning: false
    }
  },
  computed: {
    rowSelection() {
      const vm = this
      if (this.type === 'NONE') {
        return {
          onChange: (selectedRowKeys, selectedRows) => {
            vm.selectedRows = selectedRows
            vm.selectedRowKeys = selectedRowKeys
          },
          getCheckboxProps: (record) => ({
            props: {
              disabled: record.name === 'Disabled User', // Column configuration not to be checked
              name: record.name
            }
          })
        }
      } else {
        return null
      }
    },
    columns() {
      return columnMap[this.type]
    },
    isShowTag() {
      return this.type === 'CIDX' && version === 'bf'
    }
  },
  mounted() {
    if (this.$const.authorityControl) {
      this.ENTCLS_ELEM_ADD_BTN = !!this.authMap['ENTCLS_ELEM_ADD_BTN']
      this.ENTCLS_ELEM_EDIT_BTN = !!this.authMap['ENTCLS_ELEM_EDIT_BTN']
      this.ENTCLS_MIME_ADD_BTN = !!this.authMap['ENTCLS_MIME_ADD_BTN']
      this.ENTCLS_MIME_EDIT_BTN = !!this.authMap['ENTCLS_MIME_EDIT_BTN']
      this.ENTCLS_ELEM_NEW_BTN = !!this.authMap['ENTCLS_ELEM_NEW_BTN']
    }

    this.tableHeight = {
      y:
        (this.$refs.tableWrapper ? this.$refs.tableWrapper.offsetHeight : 30) -
        30
    }
    var vm = this
    window.onresize = function() {
      vm.tableHeight = {
        y:
          (vm.$refs.tableWrapper ? vm.$refs.tableWrapper.offsetHeight : 30) -
          30
      }
    }
  },
  destoryed() {
    window.onresize = undefined
  },
  created() {
    // 获取实体类id
    this.id = this.$route.params.classId
    // 获取路由type
    this.type = this.$route.meta.type

    this.getAttrClass()
  },
  methods: {
    // 调整属性
    adjustAttrModal(item) {
      this.$open(
        'adjustAttrModal',
        {
          attrClsID: item.attrClsID
        },
        function() {
          this.getAttrClass()
        }
      )
    },
    // 合并
    handleMerage() {
      if (this.selectedRows.length < 2) {
        this.$message.error('请至少选择俩个待审属性')
      } else {
        this.$open(
          'merageAttrModal',
          {
            selectedRows: this.selectedRows,
            selectedRowKeys: this.selectedRowKeys
          },
          function() {
            this.getAttrClass()
          }
        )
      }
    },
    // 迁移方法
    transferMerage(attrClsID) {
      this.$open(
        'transferAttrModal',
        {
          attrClsID: attrClsID
        },
        function() {
          this.getAttrClass()
        }
      )
    },
    onSelectChange() {},
    // 选择自定义属性类
    checkAttrClass() {
      this.$open(
        'chooseAttrClassModal',
        {
          entClsID: this.id,
          attrType: this.type
        },
        function() {
          this.getAttrClass()
        }
      )
    },
    // 编辑实体类
    editAttrClass(param) {
      this.$open(
        'addAttrClassModal',
        {
          title: '编辑属性类',
          attrClassParam: param
        },
        function() {
          this.getAttrClass()
        }
      )
    },
    /**
     * 操作打开实体类的模态框
     */
    openModel() {
      this.$open(
        'addAttrClassModal',
        {
          title: '新增属性类',
          entClsID: this.id,
          type: this.type
        },
        function() {
          this.getAttrClass()
        }
      )
      // if (this.type === 'ELEM') {
      //   this.$open('addAttrClassModal', {
      //     title: '新增属性类',
      //     entClsID: this.id
      //   }, function () {
      //     this.getAttrClass()
      //   })
      // } else {
      //   this.$open('AddEntityClass', {
      //     //模态框的传参
      //     param: this.id,
      //     type: this.type
      //   }, function (data) {
      //     if (data !== false) {
      //       this.getAttrClass()
      //     }
      //   })
      // }
    },
    /**
     * 操作打开选择指标模态窗
     */
    openCheckTargetModal(attrClsID) {
      // const selectData = []
      // this.data.forEach((v, i) => {
      //   if (v.attrClsID !== attrClsID) {
      //     selectData.push(v)
      //   }
      // })
      this.$open(
        'checkTargetModal',
        {
          // 模态框的传参
          entClsId: this.id, // 实体类id
          attrClsID: attrClsID // 属性类id
          // selectData: selectData
        },
        function(data) {
          if (data !== false) {
          }
        }
      )
    },
    deleteCancel() {
      // const newData = [...this.data]
      // const target = newData.filter(item => key === item.attrClsID)[0]
      // if (target) {
      //   Object.assign(target, this.cacheData.filter(item => key === item.attrClsID)[0])
      //   delete target.editable
      //   this.data = newData
      // }
    },
    // 获取属性类列表通过实体类id
    getAttrClass() {
      // if (this.type === 'ELEM' || this.type === 'NONE' || this.type === 'CIDX') {
      var _vm = this
      _vm.spinning = true
      if (this.type === 'NONE') {
        api.entityClass.getEntClsNoneList(_vm.id).then((result) => {
          _vm.spinning = false
          const { attrClsVOList } = result
          if (attrClsVOList) {
            if (!attrClsVOList.attrUnit) {
              attrClsVOList.attrUnit = ''
            }
            if (!attrClsVOList.attrClsMemo) {
              attrClsVOList.attrClsMemo = ''
            }
            _vm.data = attrClsVOList
          }
        })
      } else {
        api.attrClass.getAttrClassById(_vm.id, this.type).then((result) => {
          _vm.spinning = false
          if (result) {
            if (!result.attrUnit) {
              result.attrUnit = ''
            }
            if (!result.attrClsMemo) {
              result.attrClsMemo = ''
            }
            _vm.data = result
          }
        })
      }
      // }
    },
    /**
     * 表格操作调用
     * @param value 修改后的值
     * @param id 修改row的id
     * @param column 修改内容的对应col
     */
    handleChange(value, id, column) {
      // 获取修改后的整个数组对象
      const newData = [...this.data]
      // 通过返回的id获取修改后的这一列的对象
      var target = newData.filter((item) => id === item.attrClsID)[0]
      // 如果修改成功，更新data的数组对象
      if (target) {
        target[column] = value
        this.data = newData
      }
    },

    // 点击编辑调用编辑函数
    edit(key) {
      const newData = [...this.data]
      this.cacheData = newData.map((item) => ({ ...item }))
      var target = newData.filter((item) => key === item.attrClsID)[0]
      // 表格关闭编辑的显示区
      if (target) {
        target.editable = true
        this.data = newData
      }
    },

    // 调用编辑之后产生的保存响应，处理保存函数
    save(key, id) {
      const newData = [...this.data]
      // 通过type来接受获取的参数
      var data = {
        attrClsID: key.attrClsID,
        attrClsName: key.attrClsName,
        attrUnit: key.attrUnit,
        attrClsMemo: key.attrClsMemo,
        valueType: key.attrValueType,
        notNull: key.notNull
      }
      if (data.attrClsName === '') {
        this.$message.error('名称不能为空，重新修改信息')
      } else {
        data.attrClsName = data.attrClsName ? data.attrClsName.trim() : ''
        data.attrUnit = data.attrUnit ? data.attrUnit.trim() : ''
        data.attrClsMemo = data.attrClsMemo ? data.attrClsMemo.trim() : ''
        if (data.attrClsName == '') {
          this.$message.error('属性名传参失败')
        }

        var target = newData.filter((item) => id === item.attrClsID)[0]
        api.attrClass.updateAttrClass(data).then((result) => {
          if (result !== false) {
            this.getAttrClass()
            if (result && target) {
              delete target.editable
              this.data = newData
              this.cacheData = newData.map((item) => ({ ...item }))
            }
          }
        })
      }
    },
    // 删除选中的属性类
    deleteAttr(id) {
      api.attrClass.delAttrClass(id).then((result) => {
        this.getAttrClass()
      })
    },

    // 调用编辑之后产生的取消响应，处理取消函数
    cancel(key) {
      // 获取修改后的整个数组对象
      const newData = [...this.data]
      // 通过返回的id获取修改后的这一列的对象
      var target = newData.filter((item) => key === item.attrClsID)[0]
      if (target) {
        // 如果有输入框存在修改内容，对修改内容销毁，关闭修改页面
        Object.assign(
          target,
          this.cacheData.filter((item) => key === item.attrClsID)[0]
        )
        delete target.editable
        this.data = newData
      }
    },
    // 批量更新
    updates(record) {
      this.$open('updateAttrClsModal', {
        record: record,
        entClsId: this.id
      })
    }
  }
}
</script>

<style scoped></style>
