<template>
  <div class="app-container">
    <div>
      <el-card>
        <div slot="header" class="clearfix">
          <b><span>AGC_AVC信息</span></b>
          <el-button
            :loading="loadButton"
            style="float: right;padding:3px 10px 3px 3px;"
            type="text"
            @click="exportDataEvent"
          >导出数据
          </el-button>
        </div>
        <el-button type="primary" size="small" style="round-clip: 10px" :loading="loadButton" @click="insertEvent">添加</el-button>
        <div style="padding-top: 10px">
          <vxe-table
            v-show="showTable"
            ref="xTable"
            export-config
            :keep-source="true"
            align="center"
            :loading="loading"
            highlight-current-row
            auto-resize
            border
            resizable
            max-height="600px"
            :edit-rules="rules"
            :data="tableData"
            :edit-config="{trigger: 'manual', mode: 'row',autoClear: false,icon:'none'}"
          >
            <vxe-table-column title="AGC_AVC信息" align="center">
              <vxe-table-column
                field="name"
                title="名称"
                width="8%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="modelNumber"
                title="型号"
                width="8%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                field="manufacturer"
                title="生产商"
                width="8%"
                align="center"
                :edit-render="{name: '$input', attrs: {type: 'text'}}"
              />
              <vxe-table-column
                width="150px"
                field="installationTime"
                title="安装时间"
                align="center"
                :edit-render="{props: {type: 'default'}}"
              >
                <template v-slot:edit="{ row }">
                  <el-date-picker
                    v-model="row.installationTime"
                    size="mini"
                    style="width: 100%"
                    type="date"
                    placeholder="选择日期："
                  />
                </template>
                <template v-slot="{ row }">{{ timestampToTime(row.installationTime) }}</template>
              </vxe-table-column>
              <vxe-table-column
                field="report"
                title="是否上报"
                width="8%"
                align="center"
                :edit-render="{name: '$select', options: trueOrFalse}"
              />
              <vxe-table-column
                field="interval"
                title="入库间隔（单位s）"
                width="8%"
                align="center"
                :edit-render="{name: '$select', options: intervals}"
              />
              <vxe-table-column title="操作" fixed="right" width="10%" align="center">
                <template v-slot="{ row }">
                  <template v-if="$refs.xTable.isActiveByRow(row)">
                    <el-button
                      type="success"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium"
                      icon="el-icon-edit"
                      @click="editSave(row)"
                    >保存
                    </el-button>
                    <el-button
                      class="cancel-btn"
                      icon="el-icon-refresh"
                      type="warning"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium"
                      @click="cancelRowEvent(row)"
                    >取消
                    </el-button>
                  </template>
                  <template v-else>
                    <el-button
                      :loading="loadButton"
                      type="primary"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium "
                      icon="el-icon-edit"
                      @click="editRowEvent(row)"
                    >编辑
                    </el-button>
                    <el-button
                      :loading="loadButton"
                      type="danger"
                      style="padding: 3px 4px 3px 4px;margin: 2px;"
                      size="medium "
                      icon="el-icon-delete"
                      @click="deleteRowEvent(row)"
                    >删除
                    </el-button>
                  </template>
                </template>
              </vxe-table-column>

            </vxe-table-column>
          </vxe-table>
          <vxe-pager
            v-show="!loadButton&&showTable"
            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']"
          />
        </div>
      </el-card>
    </div>
    <!-- 删除提示框 -->
    <el-dialog :visible.sync="delVisible" title="提示" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteCancel()">取 消</el-button>
        <el-button type="primary" @click="deleteInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Index',
  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.mid == '' || this.mid == undefined) {
          // 新增
          if ((value == s6[i].name)) {
            callback(new Error('名称不能重复'))
          }
        } else {
          // 修改
          if (this.mid != s6[i].id) {
            if ((value == s6[i].name)) {
              callback(new Error('名称不能重复'))
            }
          }
        }
      }
      callback()
    }
    return {
      mid: '',
      rowId: '',
      loadButton: false,
      loading: false,
      showTable: true,
      delVisible: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      trueOrFalse: [{ label: '是', value: true }, { label: '否', value: false }],
      intervals: [{ key: 0, value: 0, label: '不入库' },{ key: 60, value: 60, label: '一分钟' }, { key: 900, value: 900, label: '十五分钟' }],
      // 是否为编辑
      isEdit: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, validator: checkName }
        ],
        modelNumber: [
          { required: true, message: 'AGC_AVC型号不能为空', trigger: 'blur' }
        ],
        manufacturer: [
          { required: true, message: '制造商名称不能为空' }
        ],
        installationTime: [
          { required: true, message: '请选择日期' }
        ],
        report: [
          { required: true, message: '是否上报不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    getInfo() {
      this.$axios.get('/agcAvcInfo').then(res => {
        console.log(res.data)
        this.tableData = res.data
        this.total = res.data.length
        this.loading = false
      }).catch((error) => {
        this.$message.error('获取AGC_AVC信息出错' + error)
      })
    },
    editSave(row) {
      this.$refs.xTable.validate(this.$refs.xTable.getCurrentRecord(),valid => {
        if (valid) {
          this.$refs.xTable.clearActived().then(() => {
            if (this.isEdit) {
              console.log(row)
              row.equipmentType = row.equipmentType.code
              // 编辑保存
              this.$axios.put('/agcAvcInfo/', row).then(res => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.loadButton = false
                this.getInfo()
              }).catch((error) => {
                this.$refs.xTable.setActiveRow(row)
                this.$message.error('修改AGC_AVC出错' + error)
              })
            } else {
              // 新增保存
              this.$axios.post('/agcAvcInfo/', row).then(res => {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.loadButton = false
                this.getInfo()
              }).catch((error) => {
                this.$refs.xTable.setActiveRow(row)
                this.$message.error('保存AGC_AVC出错' + error)
              })
            }
          })
        } else {
          this.$XModal.message({status: 'error', message: '校验不通过！'})
        }
      })
    },
    editRowEvent(row) {
      this.mid = row.id
      this.isEdit = true
      this.loadButton = true
      this.$refs.xTable.setActiveRow(row)
    },
    insertEvent(row) {
      this.mid = ''
      this.showTable = true
      this.piadd = false
      this.isEdit = false
      this.loadButton = true
      this.$refs.xTable.insert({ interval: 60 }).then(({ row }) => this.$refs.xTable.setActiveRow(row))
    },
    exportDataEvent() {
      this.$axios.get('/agcAvcInfo/').then(res => {
        const data = res.data
        this.$refs.xTable.exportData({
          filename: 'AGC_AVC信息',
          type: 'csv',
          isHeader: true,
          isFooter: true,
          data
        })
      })
    },
    cancelRowEvent(row) {
      const xTable = this.$refs.xTable
      xTable.clearActived().then(() => {
        // 还原行数据
        if (this.isEdit) {
          //编辑
          xTable.revertData(row)
        } else {
          //新增
          xTable.remove(row)
        }
        this.loadButton = false;
      })
    },
    // 删除场站信息
    deleteRowEvent(row) {
      this.rowId = row.id
      this.delVisible = true
    },
    deleteCancel() {
      this.delVisible = false
    },
    deleteInfo() {
      this.$axios.delete('/agcAvcInfo/' + this.rowId).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.delVisible = false
        this.getInfo()
      }).catch((error) => {
        this.$message.error('删除AGC_AVC信息出错' + error)
      })
    },
    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
    }
  }
}
</script>

<style scoped>

</style>
