<template>
  <div class="app-container">
    <el-form ref="queryForm" size="small" :inline="true">
      <el-form-item label="场站名称">
        <el-select v-model="stationCode" placeholder="请选择" @change="stationChange">
          <el-option
              v-for="item in stationList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search" @click="dataQuery">查询
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="exportTemplateEvent"
        >逆变器模板下载
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          :auto-upload="true"
          ref="uploadNbqTemplate"
          action="/inverterinfo/uploadNbqTemplate"
          :http-request="dataUpload"
          :on-change="beforeUpload"
          :on-error="onError"
          :file-list="fileList"
          :show-file-list="false"
        >
          <el-button type="info" plain size="mini" :loading="loading">逆变器模板导入</el-button>
        </el-upload>
      </el-col>
    </el-row>

    <div style="padding-top: 10px">
      <vxe-table
          ref="xTable"
          align="center"
          class="mytable-style"
          auto-resize
          border
          resizable
          export-config
          highlight-current-row
          show-overflow
          max-height="700"
          :data="tableData"
          :radio-config="{trigger: 'row'}">
        <vxe-column type="radio" width="60"/>
        <vxe-table-column field="stationCode" title="所属场站" :formatter="stationCodeFormat"></vxe-table-column>
        <vxe-table-column field="name" title="设备名称"></vxe-table-column>
        <vxe-table-column field="manufacturer" title="制造商"></vxe-table-column>
        <vxe-table-column field="modelNumber" title="型号"></vxe-table-column>
        <vxe-table-column field="sample" title="是否样板机" :formatter="yesNoFormat"></vxe-table-column>
      </vxe-table>
      <vxe-pager
          background
          :loading="loading"
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :total="total"
          @page-change="handlePageChange"
          :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
      </vxe-pager>
    </div>

    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="750px" height="600px">
      <el-form ref="form" :model="form" :rules="rules" width="730px" label-width="130px">
        <el-row class="mb4">
          <el-col :span="12">
            <el-form-item label="所属场站" prop="stationCode">
              <el-select
                  v-model="form.stationCode"
                  placeholder="请选择"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in this.stationList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="name">
              <el-input style="width: 100%" v-model="form.name" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mb4">
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input  style="width: 100%" v-model="form.manufacturer" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="modelNumber">
              <el-input style="width: 100%" v-model="form.modelNumber" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="mb4">
          <el-col :span="12">
            <el-form-item label="是否样板机" prop="sample">
              <el-select
                  v-model="form.sample"
                  placeholder="请选择"
                  style="width: 100%"
              >
                <el-option
                    v-for="item in this.yesNoOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="commitChannel">确 定</el-button>
        <el-button @click="cancelChannel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  name: 'inverterinfo',
  data() {
    return {
      form: {
        stationCode: undefined,
        name: undefined,
        manufacturer: undefined,
        modelNumber: undefined,
        sample: undefined,
      },
      title: "",
      // 是否显示弹出层
      open: false,
      edit: false,
      total: 0,
      sortOrder: 'asc',
      pageSize: 10,
      currentPage: 1,
      stationList: [],
      stationCode: [],
      searchForm: {},
      tableData: [],
      loading: false,
      modId: '',//备用id
      yesNoOptions: [
        {value: '0', label: '不是'},
        {value: '1', label: '是'}
      ],
      // 表单校验
      rules: {
        stationCode: [
          {required: true, message: "所属场站不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "设备名称不能为空", trigger: "blur"}
        ],
        manufacturer: [
          {required: true, message: "制造商不能为空", trigger: "blur"}
        ],
        modelNumber: [
          {required: true, message: "型号不能为空", trigger: "blur"}
        ],
        sample: [
          {required: true, message: "是否样板不能为空", trigger: "blur"}
        ],
      },

      fileList: [],
    }
  },
  mounted() {
    this.getStationCode()
  },
  computed: {},
  methods: {
    dataUpload(item) {
      const formData = new FormData()
      formData.append('file', item.file)

      this.$axios({
        url: '/inverterinfo/uploadNbqTemplate',
        method: 'post',
        //删除默认的Content-Type
        transformRequest: [(data, headers) => {
          delete headers.post['Content-Type']
          return data
        }],
        data: formData
      }).then((response) => {
        this.stationChange()
        this.dataQuery()
        this.$message.success("导入成功")
      }).catch((error) => {
        this.$message.error("导入失败" + error)
      })
    },
    onError(err, file, fileList){
      console.log(JSON.parse(err.message).msg)
      alert('失败')
    },
    beforeUpload(file, fileList){
      if (fileList.length > 1) {
        // 移除旧文件
        this.fileList = [file];
      } else {
        this.fileList = fileList;
      }
      let index = file.name.lastIndexOf(".");
      let suffixName = file.name.substr(index+1);
      if (suffixName=='xls' || suffixName=='xlsx'){
        return true
      }
      else{
        this.$message({
          type: 'warning',
          message: '请导入excel模板文件!'
        })
        this.fileList=[]
        return false
      }
    },
    exportTemplateEvent() {
      this.$axios.get("/inverterinfo/exportTemplateEvent/", {
        responseType: 'blob'// 用于解决中文乱码
      }).then((response) => {
        this.loading = false
      }).catch((error) => {
        this.loading = false
        this.$message.error('下载模板失败' + error)
      })
    },
    // 表单重置
    reset() {
      this.edit = false;
      this.form = {
        stationCode: undefined,
        name: undefined,
        manufacturer: undefined,
        modelNumber: undefined,
        sample: undefined,
      },
      this.resetForm("form");
    },
    // 取消按钮
    cancelChannel() {
      this.open = false;
      this.reset();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增逆变器信息";
      this.edit = false;
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.title = "修改逆变器信息";
      this.reset();
      const _selectData = this.$refs.xTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      this.open = true;
      this.edit = true;
      this.form = JSON.parse(JSON.stringify(_selectData))
    },
    // 提交按钮
    commitChannel() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.form.id != undefined) {
            // 更新操作
            this.$axios.post('/inverterinfo/updateById', this.form).then((res) => {
              this.$message.success('修改成功')
              this.open = false;
              this.stationChange()
              this.dataQuery()
            }).catch((error) => {
            })
          } else {
            // 新增操作
            this.$axios.post('/inverterinfo/save', this.form).then((res) => {
              if (res == undefined) {
                this.$message.success('新增失败')
              } else {
                this.$message.success('新增成功')
                this.stationChange()
                this.dataQuery()
                this.open = false;
              }
            }).catch((error) => {
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      const _selectData = this.$refs.xTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }

      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete(_selectData)
      }).catch(() => {
      });
    },
    /**
     * 删除提交
     */
    doDelete(row) {
      this.$axios.post('/inverterinfo/remove', row).then((res) => {
        this.$message.success('删除成功！')
        this.stationChange()
        this.dataQuery()
      }).catch((error) => {
      })
      this.loading = false
    },
    stationChange() {
      this.currentPage = 1
      this.pageSize = 10
    },
    stationCodeFormat({cellValue, row, column}) {
      const item = this.stationList.find(item => item.value === cellValue)
      return item ? item.label : ''
    },
    yesNoFormat({cellValue, row, column}) {
      if (cellValue == 0) {
        return '不是'
      } else {
        return '是'
      }
    },
    handlePageChange({currentPage, pageSize}) {
      this.currentPage = currentPage
      this.pageSize = pageSize
      this.dataQuery();
    },
    dataQuery() {
      this.loading = true
      const param = {
        "currentPage": this.currentPage,
        "pageSize": this.pageSize,
        "stationCode": this.stationCode
      }

      this.$axios.get('/inverterinfo/getByStationCode', {params: param}).then(response => {
        this.tableData = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getStationCode() {
      this.$axios({url: '/electricfield/all', method: 'get'}).then(response => {
        this.stationList = response.data
        if (this.stationList.length > 0) {
          this.stationCode = this.stationList[0].value
          this.dataQuery()
        }
      })
    },
  }
}
</script>
