<!--
 * @Author: wlo_o
 * @Date: 2022-02-16 14:19:46
 * @LastEditors: Jone
 * @LastEditTime: 2022-07-04 11:06:21
 * @FilePath: /frontend/lib/components/MdElementValueList.vue
 * @Description: 元素值列表（值域）
 *
 * Copyright (c) 2022 by 青岛百洋智能科技股份有限公司, All Rights Reserved.
-->
<template>
  <div>
    <el-row
      type="flex"
      class="mb5"
    >
      <el-col :span="12">
        <template v-if="!!$slots['title']">
          <slot name="title"></slot>
        </template>
        <div v-else-if="!!title">{{title}}</div>
        <div v-else>&nbsp;</div>
      </el-col>
    </el-row>
    <el-row
      v-show="editable"
      type="flex"
      justify="end"
      style="padding-bottom: 10px"
    >
      <el-button
        :disabled="!id||editRowIndex!=-1"
        @click="handleRowAddClick"
        size="small"
        class="addBtn"
        type="primary"
      >添加</el-button>
    </el-row>
    <el-row>
      <el-table
        :header-cell-style="{background:'#F2F7FF',color:'#323232',height:'46px'}"
        v-loading="loading"
        :data="tableData"
        stripe
      >
        <el-table-column
          type="index"
          width="50"
        >
          <div slot="header">序号</div>
          <template slot-scope="scope">{{(pagination.page-1)*pagination.pageSize+scope.$index+1}}</template>
        </el-table-column>
        <el-table-column
          prop="value"
          label="值"
        >
          <template slot-scope="scope">
            <template v-if="editRowIndex==scope.$index">
              <el-input
                v-model="editRowData.value"
                v-loading="rowLoading"
                v-on:keyup.enter.native="inputFocus('label-ref')"
                v-on:keyup.esc.native="handleRowCancelClick(scope)"
                size="medium"
                ref="value-ref"
                placeholder="请输入值"
              />
            </template>
            <template v-else>{{scope.row.value}}</template>
          </template>
        </el-table-column>
        <el-table-column
          prop="label"
          label="值含义"
        >
          <template slot-scope="scope">
            <template v-if="editRowIndex==scope.$index">
              <el-input
                v-model="editRowData.label"
                v-loading="rowLoading"
                v-on:keyup.enter.native="inputFocus('desc-ref')"
                v-on:keyup.esc.native="handleRowCancelClick(scope)"
                size="medium"
                ref="label-ref"
                placeholder="请输入值含义"
              />
            </template>
            <template v-else>{{scope.row.label}}</template>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="说明"
        >
          <template slot-scope="scope">
            <template v-if="editRowIndex==scope.$index">
              <el-input
                v-model="editRowData.description"
                v-loading="rowLoading"
                v-on:keyup.enter.native="handleRowSaveClick(scope)"
                v-on:keyup.esc.native="handleRowCancelClick(scope)"
                size="medium"
                ref="desc-ref"
                placeholder="请输入说明"
              />
            </template>
            <template v-else>{{scope.row.description}}</template>
          </template>
        </el-table-column>
        <el-table-column
          v-if="editable"
          :width="showRowBtnText?200:100"
          label="操作"
        >
          <template slot-scope="scope">
            <div v-show="editRowIndex!=scope.$index">
              <el-button
                :disabled="scope.row.isSys==1||(editRowIndex!=-1&&editRowIndex!=scope.$index)"
                @click="handleRowEditClick(scope)"
                type="text"
                size="medium"
                icon="el-icon-edit"
              >
                <span v-if="showRowBtnText">编辑</span>
              </el-button>
              <el-button
                :disabled="scope.row.isSys==1||(editRowIndex!=-1&&editRowIndex!=scope.$index)"
                @click="handleRowDelClick(scope)"
                type="text"
                size="medium"
              >
                <i
                  :style="(scope.row.isSys==1||(editRowIndex!=-1&&editRowIndex!=scope.$index))?{}:{color:'#F56C6C'}"
                  class="el-icon-close"
                ></i>
                <span v-if="showRowBtnText">删除</span>
              </el-button>
            </div>
            <div v-show="editRowIndex==scope.$index">
              <el-button
                v-show="editRowIndex==scope.$index"
                :disabled="scope.row.isSys==1"
                @click="handleRowSaveClick(scope)"
                type="text"
                size="medium"
                icon="el-icon-check"
                style="color:#67C23A"
              >
                <span v-if="showRowBtnText">保存</span>
              </el-button>
              <el-button
                v-show="editRowIndex==scope.$index"
                :disabled="scope.row.isSys==1"
                @click="handleRowCancelClick(scope)"
                type="text"
                size="medium"
                icon="el-icon-close"
                style="color:#909399"
              >
                <span v-if="showRowBtnText">取消</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row
      v-show="pagination.total"
      type="flex"
      justify="end"
    >
      <el-pagination
        :loading="loading"
        :total="pagination.total"
        :page-sizes="pagination.pageSizes"
        :page-size.sync="pagination.pageSize"
        :current-page.sync="pagination.page"
        layout="prev,pager,next,sizes,jumper"
        ref="pagination"
        background
      />
    </el-row>
  </div>
</template>
<script>
import OptionsMixin from '../mixins/OptionsMixin'
import EventMixin from '../mixins/EventMixin'
import { fetchApi } from '../common/apis.js'
import isEmpty from 'lodash/isEmpty'

export default {
  mixins: [OptionsMixin, EventMixin],
  props: {
    title: { type: [String, null], default: '' },
    editable: { type: Boolean, default: true },
    id: { type: [String, null], default: null }, // 元素（值域）主键
  },
  watch: {
    id: {
      handler: function (val) {
        this.getList()
      },
    },
    'pagination.page': function () {
      this.getList()
    },
    'pagination.pageSize': function () {
      this.getList()
    },
  },
  data() {
    return {
      loading: false,
      rowLoading: false,
      tableData: [],
      editRowIndex: -1,
      editRowData: {}, // 编辑时，数据备份
      showRowBtnText: false,
      pagination: {
        total: 0,
        page: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
      },
      editStatus: '',
    }
  },
  methods: {
    inputFocus(elName = 'value-ref') {
      this.$nextTick(() => {
        this.$refs[elName].focus()
      })
    },
    getList() {
      let that = this
      let { page, pageSize } = this.pagination
      this.loading = true
      fetchApi
        .call(this, '/element/values/pageList', { page, pageSize, elementId: this.id })
        .then(res => {
          let { records = [], total = 0 } = res
          that.editRowIndex = -1
          that.pagination = { ...that.pagination, total }
          that.tableData = records
        })
        .finally(() => {
          that.loading = false
        })
    },
    handleRowEditClick(scope, action = 'edit') {
      this.editRowIndex = scope.$index
      this.editRowData = JSON.parse(JSON.stringify(scope.row))
      this.editStatus = action
      this.inputFocus()
    },
    handleRowSaveClick(scope) {
      let that = this
      let { value, label } = this.editRowData
      let err = isEmpty(value) ? '值不能为空' : isEmpty(label) ? '值含义不能为空' : ''
      if (err) return this.$message.error(err)
      let lastEditRowIndex = this.editRowIndex
      this.editRowIndex = -1
      let { id: elementId, editRowData, editStatus } = this
      this.rowLoading = true
      fetchApi
        .call(this, '/element/values/save', { ...editRowData, elementId })
        .then(function (res) {
          that.tableData.splice(lastEditRowIndex, 1, res)
          if (editStatus === 'add') {
            that.handleRowAddClick()
          } else {
            that.getList()
          }
        })
        .finally(() => {
          that.rowLoading = false
        })
    },
    handleRowAddClick() {
      this.tableData.push({})
      this.handleRowEditClick({ $index: this.tableData.length - 1, row: {} }, 'add')
      this.inputFocus()
    },
    handleRowCancelClick(scope) {
      isEmpty(scope.row.id) && this.tableData.splice(scope.$index, 1)
      this.editRowIndex = -1
    },
    handleRowDelClick(scope) {
      let that = this
      this.$confirm('此操作将永久删除该行数据, 是否继续?', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        let { id } = scope.row
        fetchApi.call(that, '/element/values/delete', { id }).then(res => {
          that.$message({ type: 'success', message: '删除成功!' })
          that.getList()
        })
      })
    },
  },
  created() {
    this.id && this.getList()
  },
}
</script>
<style>
.addBtn {
  background: #2468f2;
  border-color: #2468f2;
  padding: 0 20px;
}
.addBtn:hover {
  background: #2469f2d6;
  border-color: #2469f2d6;
}
.el-button--primary.is-disabled,
.el-button--primary.is-disabled:active,
.el-button--primary.is-disabled:focus,
.el-button--primary.is-disabled:hover {
  background: #2469f268 !important;
  border: none;
}
/deep/.el-table th.el-table__cell.is-leaf {
  border-bottom: none !important;
}
/deep/.el-icon-close {
  font-size: 18px;
}
</style>
