<template>
  <div class="chain-management-page">
    <Card>
      <div class="search-con">
        <Input
          placeholder="请输入名称关键字或者通证标识"
          class="search-input"
          v-model="searchContent.keyword"
          style="width: 200px;margin-right:10px"
          clearable
        />
        <ButtonGroup class="search-btngroup">
          <Button type="primary" @click="handleSearch">查找</Button>
          <Button type="primary" @click="handleRefresh">
            <Icon type="md-refresh" />
          </Button>
        </ButtonGroup>
        <Button type="info" @click="handleAdd" style="margin-left: 20px"
          >+ 添加</Button
        >
      </div>
      <tables
        ref="tables"
        editable
        pagable
        v-model="tableData"
        :columns="columns"
        :currentPage="searchContent.pageNum"
        :pageSize="searchContent.pageSize"
        :totalSize="totalSize"
        :loading="loading"
        @on-change="handleCurrentChange"
      />
        <Modal
        :title="modalTitle"
        v-model="modalStatus"
        @on-cancel="handleCancel"
      >
        <div class="model-item">
          <label class="label">名称：</label>
          <Input
          placeholder="请输入区块链名称，20字以内"
          :maxlength="20"
          v-model="chainObj.blockChainName"
          :disabled="this.chainObj.blockChainId != ''"
          />
        </div>
        <div class="model-item">
          <label class="label">IP：</label>
          <Input
          placeholder="请输入区块链RPC请求IP"
            v-model="chainObj.ip"
          />
        </div>
        <div class="model-item">
          <label class="label">端口：</label>
          <Input
          placeholder="请输入区块链RPC请求端口"
            v-model="chainObj.port"
          />
        </div>
        <div class="model-item">
          <label class="label">标题(title)：</label>
          <Input
          placeholder="请输入平行链的Title，主链无需填写"
            v-model="chainObj.title"
          />
        </div>
        <div class="model-item">
          <label class="label">初始高度：</label>
          <Input
          placeholder="请输入初始区块高度，平行链始终为0"
            v-model="chainObj.startHeight"
          />
        </div>
        <div class="model-item">
          <label class="label">备注：</label>
          <Input
          placeholder="请输入备注，200字以内"
          type="textarea"
            v-model="chainObj.remark"
          />
        </div>
        <div slot="footer">
          <Button
            type="primary"
            @click="handleSubmitAdd"
          >
            确定
          </Button>
        </div>
      </Modal>
    </Card>
  </div>
</template>
<script>
import Tables from '_c/tables'
import { formatTime } from '@/libs/tools'
import { BlockChainState, BlockChainStateObj } from '@/enums'
export default {
  inject: ['reload'],
  components: {
    Tables
  },
  data () {
    return {
      loading: false,
      modalStatus: false,
      modalTitle: '新增区块链',
      chainObj: {
        blockChainId: '',
        blockChainName: '',
        ip: '',
        port: '',
        title: '',
        startHeight: '',
        remark: '',
        updateTime: ''
      },
      searchContent: {
        keyword: '',
        pageNum: 1,
        pageSize: 10
      },
      columns: [
        { title: '编号', key: 'blockChainId', align: 'left', minWidth: 180 },
        { title: '链名称', key: 'blockChainName', align: 'center', minWidth: 100 },
        { title: 'IP', key: 'ip', align: 'center', minWidth: 100 },
        { title: '端口', key: 'port', align: 'center', minWidth: 100 },
        { title: '标题(title)',
          key: 'title',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            let title = params.row.title
            return h('span', title || '--')
          }
        },
        // { title: '链上通证', key: 'passIdList', align: 'center', width: 100 },
        { title: '链上通证',
          key: 'passIdList',
          minWidth: 180,
          align: 'left',
          render: (h, params) => {
            let passIdList = params.row.passIdList
            let btn = []
            passIdList.forEach(item => {
              item.split(',')
              btn.push(h(
                'div', item
              ))
            })
            return h('div', passIdList.length ? [btn] : '--')
          } },
        { title: '备注', key: 'remark', align: 'center', minWidth: 120 },
        { title: '状态',
          key: 'navigationName',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            let obj = BlockChainStateObj[params.row.status]
            return h(
              'Tag',
              {
                props: {
                  color: obj.color
                }
              },
              obj.label
            )
          }
        },
        { title: '入库时间',
          key: 'createTime',
          align: 'center',
          minWidth: 150,
          render: (h, params) => {
            return h('span', formatTime(params.row.createTime))
          }
        },
        { title: '更新时间',
          key: 'updateTime',
          align: 'center',
          minWidth: 150,
          render: (h, params) => {
            return h('span', formatTime(params.row.updateTime))
          }
        },
        { title: '操作',
          key: 'navigationName',
          align: 'center',
          minWidth: 265,
          fixed: 'right',
          render: (h, params) => {
            let validState = params.row.status
            let statusBtn = h(
              'Button',
              {
                props: {
                  type: status == BlockChainState.STOP ? 'primary' : 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleUpdateStatus(params.row)
                },
                style: {
                  marginRight: '5px'
                  // display: status == OffShelfType.GROUNDING ? 'inline-block' : 'none'
                }
              },
              validState == BlockChainState.STOP ? '启 用' : '停 用'
            )
            let editBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleUpdate(params.row)
                },
                style: {
                  marginRight: '5px'
                }
              },
              '编 辑'
            )
            let manageBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleManage(params.row)
                },
                style: {
                  marginRight: '5px'
                }
              },
              '管理通证'
            )
            let delBtn = h(
              'Button',
              {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: this.handleDelete(params.row)
                },
                style: {
                  marginRight: '5px',
                  display: validState == BlockChainState.STOP ? 'inline-block' : 'none'
                }
              },
              '删 除'
            )
            return h('div', [statusBtn, editBtn, manageBtn, delBtn])
          }
        }
      ],
      totalSize: 0,
      tableData: []
    }
  },
  created () {
    this.requestData()
  },
  methods: {
    requestData () {
      this.loading = true
      this.api({
        apiName: 'chainManagementList',
        postdata: this.searchContent,
        success: (res) => {
          this.tableData = res.data.records
          this.totalSize = res.data.total
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    handleSearch () {
      this.searchContent.pageNum = 1
      this.requestData()
    },
    handleRefresh () {
      this.reload()
    },
    handleCurrentChange () {
      this.searchContent.pageNum = pageNum
      this.requestData()
    },
    handleUpdateStatus (row) {
      return () => {
        let updateTime = row.updateTime
        let blockChainId = row.blockChainId
        let validState = row.status == 1 ? 2 : 1
        // if(row.status==1){
        //   validState=2
        // }e
        let title = row.status == BlockChainState.STOP ? '启用' : '停用'
        this.$Modal.confirm({
          title,
          content: `确认要 ${title} 名称为 ${row.blockChainName} 的区块链 ？`,
          onOk: () => {
            this.api({
              apiName: 'chainManagementValid',
              postdata: { blockChainId, updateTime, validState },
              success: () => {
                this.requestData()
                this.$Notice.success({ title: `操作成功！` })
              }
            })
          }
        })
      }
    },
    handleUpdate (row) {
      return () => {
        this.modalStatus = true
        this.modalTitle = '编辑区块链'
        this.chainObj = {
          blockChainName: row.blockChainName,
          blockChainId: row.blockChainId,
          ip: row.ip,
          port: row.port,
          startHeight: row.startHeight,
          title: row.title,
          remark: row.remark,
          updateTime: row.updateTime
        }
      }
    },
    handleDelete (row) {
      return () => {
        this.$Modal.confirm({
          title: '删除',
          content: `您确认要删除名称为${row.blockChainName} 的区块链？`,
          onOk: () => {
            this.api({
              apiName: 'chainManagementDelete',
              postdata: row.blockChainId,
              success: () => {
                this.requestData()
                this.$Notice.success({ title: `操作成功！` })
              }
            })
          }
        })
      }
    },
    handleManage (row) {
      return () => {
        let query = { blockChainId: row.blockChainId }
        this.$router.push({ name: 'management_pass', query })
      }
    },
    handleAdd () {
      this.modalStatus = true
      this.modalTitle = '新增区块链'
    },
    cancel () {
      this.chainObj = {
        blockChainId: '',
        blockChainName: '',
        ip: '',
        port: '',
        startHeight: '',
        title: '',
        remark: '',
        updateTime: ''
      }
    },
    handleCancel () {
      this.modalStatus = false
      this.cancel()
    },
    checkForm () {
      let { blockChainId, blockChainName, ip, port, title, startHeight, remark, updateTime } = this.chainObj
      let errMsg = ''
      let form
      if (blockChainId) {
        form = {
          blockChainId,
          ip,
          port,
          title,
          startHeight,
          remark,
          updateTime
        }
      } else {
        form = {

          blockChainName,
          ip,
          port,
          title,
          startHeight,
          remark

        }
      }

      if (!blockChainName) {
        return { errMsg: '请输入区块链名称！' }
      }
      if (!ip) {
        return { errMsg: '请输入区块链RPC请求IP！' }
      }
      if (!port) {
        return { errMsg: '请输入区块链RPC请求端口！' }
      }
      if (!startHeight && startHeight != 0) {
        return { errMsg: '请输入初始高度！' }
      }
      if (!remark) {
        return { errMsg: '请输入备注！' }
      }
      return { errMsg, form }
    },
    handleSubmitAdd () {
      let { errMsg, form } = this.checkForm()
      if (errMsg) {
        return this.$Notice.warning({ title: errMsg })
      }
      let apiName = this.chainObj.blockChainId ? 'chainManagementUpdate' : 'chainManagementSave'
      this.api({
        apiName,
        postdata: form,
        success: (res) => {
          this.requestData()
        },
        complete: () => {
          this.modalStatus = false
          this.$Notice.success({ title: '操作成功' })
          this.cancel()
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.search-con {
    padding: 10px 0;
}
.model-item {
    display: flex;
    margin-bottom: 10px;
    align-items: center;
    .label {
      display: inline-block;
      width: 100px;
      text-align: right;
    }
  }
</style>
