<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div class="app-container">
    <el-card class="box-carde">
      <div slot="header" class="clearfix">
        <span>测风塔信息</span>
        <el-button style="float: right;padding:3px 10px 3px 3px;" type="text" :loading="btnLonding"
                   @click="exportDataEvent">导出数据
        </el-button>
      </div>
      <el-button type="primary" size="small" @click="insertEvent" style="round-clip: 10px"
                 :loading="btnLonding">新增</el-button>
      <div style="padding-top: 10px">
        <vxe-table
          :keep-source="true"
          align="center"
          :loading="loading"
          highlight-current-row
          ref="xTable"
          auto-resize
          border
          resizable
          show-overflow
          :edit-rules="rules"
          :data="tableData"
          v-show="showTable"
          :edit-config="{trigger: 'manual', mode: 'row',autoClear: false,icon:'none'}"
        >
          <vxe-table-column title="测风塔信息">
            <vxe-table-column field="name" title="名称"  width="13%"
                              :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
            <vxe-table-column field="manufacturer" title="生产商"  width="13%"
                              :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
            <vxe-table-column field="modelNumber" title="型号"  width="10%"
                              :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
            <vxe-table-column min-width="50px"  width="14%" field="installationTime" title="安装时间"
                              :edit-render="{props: {type: 'default'}}">
              <template v-slot:edit="{ row }">
                <el-date-picker
                  size="mini"
                  v-model="row.installationTime"
                  style="width: 100%"
                  type="date"
                  placeholder="选择日期："
                />
              </template>
              <template v-slot="{ row }">{{ timestampToTime(row.installationTime) }}</template>
            </vxe-table-column>
            <vxe-table-column field="sample" title="是否样板机"  width="7%"
                              :edit-render="{name: '$select', options: options}"></vxe-table-column>
            <vxe-table-column field="report" title="是否上报"  width="7%"
                              :edit-render="{name: '$select', options: options}"></vxe-table-column>
            <vxe-table-column field="bindTunnel" title="绑定通道" width="13%"
                              :edit-render="{name: '$select', options: bindTunnels}">
              <template v-slot:header>
                <el-tooltip content="当设备绑定通道时，对应通道断开后，根据预测测风生成设备实时数据" placement="top">
                  <span>绑定通道<i class="el-icon-question"></i></span>
                </el-tooltip>
              </template>
            </vxe-table-column>
            <vxe-table-column field="interval" title="入库间隔（单位s）" width="8%" align="center"
                              :edit-render="{name: '$select', options: intervals}"></vxe-table-column>
            <vxe-table-column field="backupA" title="经度"  width="7%"
                              :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
            <vxe-table-column field="backupB" title="纬度"  width="7%"
                              :edit-render="{name: '$input', attrs: {type: 'text'}}"></vxe-table-column>
            <vxe-table-column width="15%" align="center" title="操作">
              <template v-slot="{ row }">
                <template v-if="$refs.xTable.isActiveByRow(row)">
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    @click="saveRowEvent(row)"
                    :loading="saveLoding">保存
                  </el-button>
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    @click="cancelRowEvent(row)">取消
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-edit"
                    @click="editRowEvent(row)"
                    :loading="btnLonding">编辑
                  </el-button>
                  <el-button
                    type="danger"
                    style="padding: 3px 4px 3px 4px;margin: 2px"
                    size="mini"
                    icon="el-icon-delete"
                    @click="removeEvent(row)"
                    :loading=btnLonding>删除
                  </el-button>
                </template>
              </template>
            </vxe-table-column>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          perfect
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="total"
          :page-sizes=[10,50,100]
          :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
          @page-change="handlePageChange"
          v-show="!btnLonding&&showTable"
        >
        </vxe-pager>
      </div>

    </el-card>
  </div>
</template>
<script>
  import request from '@/utils/request'

  export default {
    data() {
      const checkName = (rule, value, callback) => {
        var s6 = this.tableData
        if (value == null || value === '') {
          callback(new Error('请填测风塔名称'))
        }
        for (let i = 0; i < s6.length; i++) {
          if (this.id == '' || this.id == undefined) {
            // 新增
            if ((value == s6[i].name)) {
              callback(new Error('名称不能重复'))
            }
          } else {
            // 修改
            if (this.id != s6[i].id) {
              if ((value == s6[i].name)) {
                callback(new Error('名称不能重复'))
              }
            }
          }
        }
        callback()
      }
      const reg = /'^-?((0|1?[0-7]?[0-9]?)(([.][0-9]{1,4})?)|180(([.][0]{1,4})?))$'/
      const reg1 = /^-?((0|[1-8]?[0-9]?)(([.][0-9]{1,4})?)|90(([.][0]{1,4})?))$/
      const checkNum = (rule, value, callback) => {
        if (!value) {
          callback(new Error('不许为空'))
        }
        if (reg.test(value) == false) {
          callback(new Error('请输入正确经度'));
        } else {
          callback()
        }
      }
      const checkNum1 = (rule, value, callback) => {
        if (!value) {
          callback(new Error('不许为空'))
        }
        if (reg1.test(value) == false) {
          callback(new Error('请输入正确纬度'));
        } else {
          callback()
        }
      }
      return {
        bindTunnels:[],
        id:'',
        equipmentTypeList:[],
        loading: false,
        saveLoding: false,
        showTable: true,
        btnLonding: false,
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        intervals:[{ key: 0, value: 0, label: '不入库' },{key:60,value:60,label:'一分钟'},{key:900,value:900,label:'十五分钟'}],
        options: [
          {
            value: true,
            label: "是"
          },
          {
            value: false,
            label: "否"
          }
        ],
        rules: {
          name: [
            {required: true,  validator:checkName},
          ],
          manufacturer: [
            {required: true, message: '制造商名称不能为空'},
          ],
          modelNumber: [
            {required: true, message: '测风塔型号不能为空'},
          ],
          installationTime: [
            {required: true, message: '请选择日期'}
          ],
          report: [
            { required: true, message: '是否上报不能为空', trigger: 'change' }
          ],
          sample: [
            { required: true, message: '是否样板机不能为空', trigger: 'change' }
          ]
        }
      }
    },
    created() {
      this.getAll()
    },
    methods: {
      getAll() {
        this.$axios.get('/TunnelInfo/findbyMaster').then(res => {
          this.bindTunnels = res.data
        })
        this.loading = true
        this.saveLoding = false
        this.$axios.get('/windTowerInfo/' + this.currentPage + '/' + this.pageSize,).then(response => {
          if (response.data.content == "") {
            this.showTable = false

          } else {
            this.showTable = true
          }
          // window.console.log(this.equipmentTypeList)
          this.tableData = response.data.content
          for (let i = 0; i < this.tableData.length; i++) {
            //添加省调枚举标识转换
            for (let j = 0; j < this.equipmentTypeList.length; j++) {
              if (this.tableData[i].equipmentType == this.equipmentTypeList[j]["value"]) {
                this.tableData[i].equipmentType = this.equipmentTypeList[j]["label"]
              }
            }
          }
          this.total = response.data.totalElements
          this.loading = false
          this.btnLonding = false
        })
      },
      editRowEvent(row) {
        this.id = row.id
        this.btnLonding = true
        this.$refs.xTable.setActiveRow(row)
      },
      saveRowEvent(row) {
        this.saveLoding = true
        this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(),valid => {
          if (valid) {
            if (row.id == undefined) {
              this.$axios.post('windTowerInfo/',row).then(response => {
                this.getAll()
                this.btnLonding = false
                this.$XModal.message({status: 'warning', message: response.message})
              })
            } else {
              row.equipmentType = row.equipmentType.code
              this.$axios.put('windTowerInfo/',row).then(response => {
                this.getAll()
                this.$XModal.message({status: 'warning', message: response.message})
                this.saveLoding = false
              })
            }
          } else {
            this.$XModal.message({status: 'error', message: '校验不通过！'})
            this.saveLoding = false
          }

        })

      },
      cancelRowEvent(row) {
        this.saveLoding = false
        this.btnLonding = false
        const xTable = this.$refs.xTable
        if (row.id == undefined) {
          xTable.clearActived().then(() => {
            xTable.remove(row)
          })
        } else {

          xTable.clearActived().then(() => {
            // 还原行数据
            xTable.revertData(row)
          })
        }
      },
      removeEvent(row) {
        this.$XModal.confirm('您确定要删除该数据?').then(type => {
          if (type === 'confirm') {
            this.$axios.delete('windTowerInfo/'+row.id).then(response => {
              this.$XModal.message({status: 'warning', message: response.message})
              this.$refs.xTable.remove(row)
            })
          }
        })
      },
      timestampToTime(time) {
        const date = new Date(time) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
        const Y = date.getFullYear() + '-'
        const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        const D = date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()
        return Y + M + D
      },
      insertEvent() {
        this.id = ''
        this.showTable = true
        this.btnLonding = true
        this.$refs.xTable.insert({interval: 60})
          .then(({row}) => this.$refs.xTable.setActiveRow(row))
      },
      handlePageChange({currentPage, pageSize}) {
        this.currentPage = currentPage
        this.pageSize = pageSize
        this.getAll()
      },
      exportDataEvent() {
        this.loading = true
        this.$axios.get('/windTowerInfo/').then(res => {
          const data = res.data.content
          this.$refs.xTable.exportData({
            filename: '测风塔信息',
            type: 'csv',
            isHeader: true,
            isFooter: true,
            data
          })
          this.loading = false
        }).catch(e => {
          this.loading = false

        })
      },
      importDataEvent() {
        this.$refs.xTable.importData({types: ['csv']})
      }
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    /*left: 0;*/
    /*width: 100%;*/
    /*min-height: 100%;*/
    /*height: auto;*/
    /*background-image: linear-gradient(25deg, #05362d, #145d44, #24875d, #35b477)*/
  }

  .pagination {
    margin: 20px 0;
    text-align: right;
  }
</style>
