<template>
  <div class="dashboard-container">
    <div class="search-content">
      <!-- <el-input v-model="queryParams.vehicleName" placeholder="请输入机车名称" style="width: 220px;" clearable /> -->
      <el-input v-model="queryParams.vehicleCode" placeholder="请输入机车号" style="width: 220px;" clearable />
      <div class="search-btn">
        <div class="search" @click="handleQuery">查询</div>
        <div class="reset" @click="reset">重置</div>
      </div>
    </div>

    <div class="table-content">
      <div style="width: 100%;height: 30px;">
        <div class="btn" @click="addVehicle">
          <span class="icon font_family">&#xe604;</span>
          新增
        </div>
        <div class="btn" @click="batchDelVehicle">
          <span class="icon font_family">&#xe607;</span>
          批量删除
        </div>
        <div class="btn" @click="importLoadIn">
          <span class="icon font_family">&#xe606;</span>
          导入
        </div>
        <div class="btn" @click="exportBaseVehicle">
          <span class="icon font_family">&#xe605;</span>
          导出
        </div>
        <div class="btn" @click="downloaExcel">
          <span class="icon font_family">&#xe603;</span>
          下载模板
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="vehicleCode" label="机车号" align="center" /> -->

        <el-table-column prop="vehicleType" label="车型" align="center" />
        <el-table-column prop="vehicleCode" label="机车号" align="center" />
        <el-table-column prop="ends" label="AB端" align="center" />

        <el-table-column prop="terminalName" label="车载终端" align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" width="170px;" />
        <el-table-column prop="updateTime" label="更新时间" align="center" width="170px;" />
        <el-table-column label="操作" align="center" width="250px;">
          <template slot-scope="scope">
            <div class="operateBtn">
              <div type="text" @click="openList(scope.row)">车载终端挂载</div>
              <div type="text" @click="updateVehicle(scope.row)">修改</div>
              <div type="text" @click="delVehicle(scope.row)"><span>删除</span></div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination :page-sizes="[10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <addVehicleDialog v-if="addVehicleData.dialogVisible" :addVehicleData="addVehicleData" @addVehicleBtn="addVehicleBtn">
    </addVehicleDialog>
    <updateVehicleDialog v-if="updateVehicleData.dialogVisible" :updateVehicleData="updateVehicleData"
      @updateVehicleBtn="updateVehicleBtn">
    </updateVehicleDialog>
    <mountVehicleList @mountSave="mountSaveBtn" :mountListData="mountListData" v-if="mountListData.dialogVisible">
    </mountVehicleList>
    <el-dialog center :visible.sync="uploadDialog" title="机车信息导入" width="620px">
      <el-upload style="text-align: center" ref="uploadFile" class="upload-demo" drag action="#"
        :http-request="uploadHttpRequest" :auto-upload="false" :file-list="fileList" :on-change="uploadFileList">
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <!-- <div class="el-upload__tip">只能上传xls/xlsx文件,且不超过500kb</div> -->
      </el-upload>
      <div class="hxj">支持扩展名：.xlsx</div>
      <div class="hxj">请先下载模板，根据模板内容填写，再上传文件 <span class="xzmba" @click="downloaExcel">下载模板</span> </div>
      <div slot="footer" class="dialog-footer">
        <div class="search" @click="httpRequest">保 存</div>
        <div class="reset" @click="uploadDialog = false">取 消</div>
      </div>

    </el-dialog>
  </div>
</template>
  
<script>
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import {
  getLocomotiveList,
  exportBaseVehicle,
  downloaExcel,
  vehicleDelete,
  importVehicle,
  addVehicle,
  vehicleUpdate,
  vehicleTerminalAdd,
  vehicleTerminalUnmount
} from '@/api/account/locomotiveMsg'
import addVehicleDialog from './components/addVehicleDialog.vue'
import updateVehicleDialog from './components/updateVehicleDialog.vue'
import mountVehicleList from './components/mountVehicleList.vue'
export default {
  name: 'Cart',
  computed: {
    ...mapGetters(['name'])
  },
  components: {
    addVehicleDialog,
    updateVehicleDialog,
    mountVehicleList
  },
  data() {
    return {
      uploadDialog: false,
      fileList: [],
      getEnds:'',
      addVehicleData: {
        dialogVisible: false
      },
      updateVehicleData: {
        dialogVisible: false,
        data: {}
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vehicleName: '',
        vehicleCode: ''
      },
      tableData: [],
      total: 0,
      action: '#',
      delVehicleList: '',
      mountListData: {
        dialogVisible: false,
        vehicleCode: ''
      },
      exportData: {
        ids: []
      }
    }
  },
  created() {
    this.getLocomotiveList(this.queryParams)
  },
  methods: {
    mountSaveBtn(payload) {
      let params = {
        ends:this.getEnds,
        vehicleCode: payload.vehicleCode,
        terminalCode: payload.terminalCode
      }
      if (!payload.isMount) {
        vehicleTerminalAdd(params).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '挂载成功!'
            });
            this.getLocomotiveList(this.queryParams)
            this.mountListData.dialogVisible = false
          }
        })
      } else {
        if (params.terminalCode == '') {
          this.$confirm('确定要解绑吗?', '信息提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            vehicleTerminalUnmount({
              vehicleCode: payload.vehicleCode
            }).then(res => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '解绑成功!'
                });
                this.getLocomotiveList(this.queryParams)
                this.mountListData.dialogVisible = false
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        } else {
          this.$confirm(`确定要将终端更改为${params.terminalCode}吗？`, '信息提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            vehicleTerminalAdd(params).then(res => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: '更换成功!'
                });
                this.getLocomotiveList(this.queryParams)
                this.mountListData.dialogVisible = false
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }

      }
    },
    getLocomotiveList(params) {
      getLocomotiveList(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getLocomotiveList(this.queryParams)
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getLocomotiveList(this.queryParams)
    },
    handleQuery() {
      this.getLocomotiveList(this.queryParams)
    },
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        vehicleName: '',
        vehicleCode: ''
      }
      this.getLocomotiveList(this.queryParams)
    },
    //导出信息
    exportBaseVehicle() {
      if (this.exportData.ids.length == 0) {
        return this.$message({
          type: 'error',
          message: '请选择要导出的机车信息!'
        });
      } else {
        exportBaseVehicle(this.exportData).then(res => {
          // const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
          // const url = window.URL.createObjectURL(blob);
          // const a = document.createElement('a');
          // a.href = url;
          // a.download = '机车信息管理.xls';
          // a.click();
          // window.URL.revokeObjectURL(url);


          if (res.type == "application/json") {
            const reader = new FileReader();
            reader.readAsText(res, 'utf-8');
            reader.onload = function () {
              const msg = JSON.parse(reader.result);
              if (msg.code == 200) {
                const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = '机车信息管理.xls';
                a.click();
                window.URL.revokeObjectURL(url);
              } else {
                Message({
                  type: 'error',
                  message: msg.msg
                });
              }
            }
          } else {
            const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '机车信息管理.xls';
            a.click();
            window.URL.revokeObjectURL(url);
          }



        })
      }
    },
    downloaExcel() {
      downloaExcel('/baseVehicle/downloaExcel').then(res => {
        const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '机车信息模板.xls';
        a.click();
        window.URL.revokeObjectURL(url);
      })
    },
    delVehicle(scope) {
      this.$confirm('确定要删除吗?', '信息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vehicleDelete(scope.id).then(res => {
          if (res.code == 200) {
            this.getLocomotiveList(this.queryParams)
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSelectionChange(v) {
      this.exportData.ids = []
      let delVehicleList = ''
      v.forEach(element => {
        delVehicleList += element.id + ','
        this.exportData.ids.push(element.id)
      });
      delVehicleList = delVehicleList.slice(0, delVehicleList.length - 1)
      this.delVehicleList = delVehicleList
    },
    batchDelVehicle() {
      if (this.delVehicleList.length == 0) {
        return this.$message({
          type: 'error',
          message: '请选择要删除的机车信息!'
        });
      }
      this.$confirm('确定要删除吗?', '信息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vehicleDelete(this.delVehicleList).then(res => {
          if (res.code == 200) {
            this.getLocomotiveList(this.queryParams)
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    importLoadIn: function () {
      this.uploadDialog = true
    },
    uploadFileList(file) {
      if (file.status === 'ready') {
        this.fileList.push(file)
        if (this.fileList.length > 1) {
          this.fileList.splice(0, 1)
        }
      }
    },
    // 导入
    httpRequest(param) {
      let formData = new FormData();
      // formData.append('file', this.dataForm.file.raw);
      formData.append('file', this.fileList[0].raw)
      let configHeaders = {
        headers: { "Content-Type": "multipart/form-data" }
      };
      importVehicle(formData).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '导入成功!'
          });
          let uid = this.fileList[0].raw.uid
          let idx = this.$refs.uploadFile.uploadFiles.findIndex(item => item.uid === uid)
          this.$refs.uploadFile.uploadFiles.splice(idx, 1)
          this.getLocomotiveList(this.queryParams)
          this.uploadDialog = false
        } else {
          let uid = this.fileList[0].raw.uid
          let idx = this.$refs.uploadFile.uploadFiles.findIndex(item => item.uid === uid)
          this.$refs.uploadFile.uploadFiles.splice(idx, 1)
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    addVehicle() {
      this.addVehicleData.dialogVisible = true
    },
    updateVehicle(row) {
      let newRow = { ...row }
      this.updateVehicleData.data = newRow
      this.updateVehicleData.dialogVisible = true
    },
    addVehicleBtn(payload) {
      addVehicle(payload).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '新增成功!'
          });
          this.getLocomotiveList(this.queryParams)
          this.addVehicleData.dialogVisible = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    updateVehicleBtn(payload) {
      let params = {
        id: payload.data.id,
        vehicleCode: payload.data.vehicleCode,
        vehicleType: payload.data.vehicleType,
        ends: payload.data.ends,
        remark: payload.data.remark
      }
      vehicleUpdate(params).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.getLocomotiveList(this.queryParams)
          this.updateVehicleData.dialogVisible = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    openList(row) {
      this.getEnds=row.ends
      this.mountListData.dialogVisible = true,
        this.mountListData.vehicleCode = row.vehicleCode
    }
  }
}
</script>
  
<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.dashboard-container {
  .search-content {
    width: 100%;
    height: 74px;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding-left: 10px;

    .el-input {
      margin: 0 10px;
    }

    .el-select {
      margin: 0 10px;
    }

    .search-btn {
      display: flex;
      align-items: center;
      height: 100%;
      margin-left: 10px;

      div {
        // margin: 0 6px;
        display: inline-block;
        width: 80px;
        height: 40px;
        border-radius: 2px;
        font-size: 14px;
        line-height: 40px;
        text-align: center;
      }

      div:hover {
        cursor: pointer;
      }

      .search {
        margin-right: 10px;
        background-color: #2766DD;
        color: #F7F8FB;
      }

      .search:hover {
        background-color: #4D85F4;
      }

      .reset {
        color: #333334;
        border: 1px solid #D7D7D7;
      }

      .reset:hover {
        color: #1F9FFF;
        border: 1px solid #1F9FFF;
      }
    }
  }

  .table-content {
    margin-top: 15px;
    width: 100%;
    background-color: #fff;
    padding: 0 20px 20px;

    .btn {
      margin: 15px 20px 15px 0;
      cursor: pointer;
      float: left;
      text-align: center;
      width: 98px;
      height: 34px;
      border-radius: 2px;
      border: 1px solid #ABC7FD;
      line-height: 34px;
      font-weight: 400;
      font-size: 14px;
      color: #2250C8;
      background-color: #E7EEFF;
    }

    .btn:hover {
      color: #FFFFFF;
      background-color: #2250C8;
      border: 1px solid #2250C8;
    }

    .btn:active {
      color: #FFFFFF;
      background-color: #194DA4;
      border: 1px solid #194DA4;
    }

    .startUsing {
      width: 60px;
      height: 25px;
      margin: 14.5px auto 0;
      line-height: 25px;
      text-align: center;
      font-size: 12px;
      color: #fff;
      border-radius: 5px;
      background-color: #00974B;
    }

    .Deactivate {
      width: 60px;
      height: 25px;
      margin: 14.5px auto 0;
      line-height: 25px;
      text-align: center;
      font-size: 12px;
      color: #fff;
      border-radius: 5px;
      background-color: #FF9933;
    }

    .operateBtn {
      display: flex;
      justify-content: center;
      color: #2866DD;

      div {
        font-size: 14px;
        margin: 0 5px;
        cursor: pointer;
      }
    }

    .pagination {
      margin: 10px 0;
      width: 100%;
      height: 20px;

      .el-pagination {
        float: right;
        margin: 10px 0;
      }
    }
  }
}

.hxj {
  height: 46px;
  line-height: 46px;
  text-align: center;
}

.xzmba {
  color: #2766dd;
  text-decoration: underline;
  cursor: pointer;
}

.operateBtn {
  display: flex;
  justify-content: center;
  color: #2866DD;

  div {
    font-size: 16px;
    margin: 0 5px;
    cursor: pointer;
  }
}
</style>
  