<template>
  <div class="charge-box">
    <div class="charge-tools">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="换电编号:" style="margin-left: 35px">
          <el-input v-model.trim="queryParams.swapId" placeholder="请输入换电编号" clearable />
        </el-form-item>

        <el-form-item label="车牌号:" style="margin-left: 50px">
          <el-input v-model.trim="queryParams.vehiclePlate" placeholder="请输入车牌号" clearable />
        </el-form-item>

        <el-form-item label="车辆识别码:" style="margin-left: 50px">
          <el-input v-model.trim="queryParams.PlateCode" placeholder="请输入车牌号" clearable />
        </el-form-item>

        <el-form-item label="时间范围:" style="margin-left: 50px">
          <el-date-picker v-model="dateTime" class="times" type="datetimerange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="serch actve" @click="handleQuery">查询</el-button>
          <el-button type="primary" class="serch" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="charge-table">
      <div class="charge-table-bottom">
        <el-table :data="datalist" :header-cell-style="{
          background: '#1d283e',
          borderColor: '#2f3c86',
          height: '36px',
          lineHeight: '36px',
          color: 'white',
          fontSize: '15px',
        }" stripe fit :height="tableheight" style="width: 100%">
          <el-table-column type="index" label="序号" width="55" />
          <el-table-column prop="swapId" width="400" label="换电编号" />
          <el-table-column prop="vehiclePlate" label="车牌号" />
          <el-table-column prop="vehicleVin" label="车辆识别码" />
          <el-table-column prop="swapBeginTime" label="换电开始时间" />
          <el-table-column prop="swapEndTime" label="换电结束时间" />
          <el-table-column prop="swapDuration" label="换电时长" />
          <el-table-column label="操作" align="center" width="200">
            <template v-if="scope.row.userAccount !== 'admin'" slot-scope="scope">
              <el-button type="primary" class="handle" size="small" @click="handleSerch(scope.row)">日志查询</el-button>
              <el-button type="primary" class="handle" size="small"
                @click="handleExport(scope.row)">导出日志</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pageblock">
        <el-pagination :current-page="queryParams.page" :page-sizes="[10, 20, 30, 40]" :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!--导出弹窗-->
    <div class="rolemanage">
      <el-dialog :title="dialogType === 'find' ? '查看日志' : '导出日志'" :visible.sync="dialogexportVisible"
        :destroy-on-close="true" @close="dialogClose">
        <el-form :model="ruleForm" :rules="rules" ref="ExportForm" v-loading="loading">
          <el-form-item label="任务名称:" prop="exportName" v-if="dialogType==='export'">
            <el-input v-model="ruleForm.exportName" placeholder="请输入任务名称"></el-input>
          </el-form-item>
          <div class="checkFirst">
            <div>日志范围：</div>
            <template>
              <el-form-item style="margin-left:8px; margin-top: 20px">
                <el-select multiple v-model="robotValue" filterable clearable placeholder="全部" @change="changeSelect"
                  collapse-tags @remove-tag="removeTag">
                  <el-option label="全部" value="全部" @click.native="selectAll"></el-option>
                  <el-option v-for="item in logOptions" :key="item.alarmCode" :label="item.alarmName"
                    :value="item.alarmCode" />
                </el-select>
              </el-form-item>
            </template>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" class="save" @click="handleExportLog">{{ dialogType==='find' ? '查看': '生成' }}</el-button>
          <el-button class="exit" @click="dialogexportVisible = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
    <!--导出弹窗结束-->
  </div>
</template>

<script>
import "./log.scss";
import { swapList } from "@/api/records";
import { logModel,exportFile } from "@/api/log";
export default {
  name: "ChangeRecord",
  components: {},
  data() {
    return {
      // 查询时间数组
      dateTime: "",
      // 充电机ID下拉列表
      chargerArr: null,
      // 数据列表
      datalist: [],
      dialogType: "find", // 按钮类型(find、export)
      // 查询参数
      queryParams: {
        page: 1, // 当前页
        pageSize: 10, // 每页条数
        vehiclePlate: undefined, // 车牌号
        vehicleVin:undefined,//车辆识别码
        swapId: undefined, // 换电编号
        swapBeginTime: undefined,
        swapEndTime: undefined,
        orderByField: undefined, // 排序字段
        orderByWays: 'desc'// 排序方式
      },
      //日志查询参数
      serchParams:{
        exchangeNo:undefined,//换电编号
        startTime:undefined,//开始时间
        endTime:undefined,//结束时间
        signals:[],//日志范围
      },
      total: 0, // 总条数，
      tableheight: 0, // 表格高度设置
      dialogexportVisible: false, // 弹窗显示
      checked: false,
      indeterminate: false,
      robotValue: "",
      logOptions: [],
      logheader: [],
      loading: false,
      heightTimer: false,
      ruleForm:{
        exportName:undefined,
      },
      rules:{
        exportName: [
            { required: true, message: '请输入任务名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
      }
    };
  },
  watch: {
    tableheight(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.heightTimer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenHeight = val;
        this.heightTimer = true;
        setTimeout(function () {
          this.heightTimer = false;
        }, 400);
      }
    },
  },
  mounted() {
    this.onLoadHeight();
    this.changeWindow();
    this.getLogModel();
    this.getswapList();
  },
  methods: {
    /* 设置初始视窗高度*/
    onLoadHeight() {
      this.$nextTick(() => {
        this.tableheight = document.body.clientHeight - 400;
      });
    },
    /* 设置窗口变化高度*/
    changeWindow() {
      window.onresize = () => {
        return (() => {
          this.tableheight = document.body.clientHeight - 400;
        })();
      };
    },
    selectAll() {
      if (this.robotValue.length < this.logOptions.length) {
        this.robotValue = [];
        this.logOptions.map((item) => {
          this.robotValue.push(item.alarmCode);
        });
      } else {
        this.robotValue = [];
      }
    },
    changeSelect(val) {
      if (!val.includes("全部") && val.length === this.logOptions.length) {
        this.robotValue.unshift("全部");
      } else if (val.includes("全部") && val.length - 1 < this.logOptions.length) {
        this.robotValue = this.robotValue.filter((item) => {
          return item !== "全部";
        });
      }
    },
    removeTag(val) {
      if (val === "全部") {
        this.robotValue = [];
      }
    },
    // 清空表单数据
    dialogClose() { },
    //获取换电记录列表
    getswapList() {
      swapList(this.queryParams).then((res) => {
        this.datalist = res.data.records;
        this.total = res.data.total;
      });
    },
    //获取日志数据字典
    getLogModel() {
      logModel().then((res) => {
        this.logOptions = res.data;
        this.logheader = res.data;
      });
    },
    /** 分页下一页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getswapList();
    },
    /** 分页选择页数 */
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getswapList();
    },
    // 搜索
    handleQuery() {
      if (this.dateTime) {
        this.queryParams.swapBeginTime = this.$moment(this.dateTime[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.queryParams.swapEndTime = this.$moment(this.dateTime[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.getswapList();
    },
    // 搜索重置
    resetForm() {
      this.queryParams.swapBeginTime = undefined;
      this.queryParams.swapEndTime = undefined;
      this.getswapList();
    },
    //日志查询
    handleSerch(val){
      this.dialogexportVisible=true
      this.dialogType='find'
      this.serchParams.exchangeNo=val.swapId
      this.serchParams.startTime=val.swapBeginTime
      this.serchParams.endTime=val.swapEndTime
    },
    //导出日志
    handleExport(val){
      this.dialogexportVisible=true
      this.dialogType='export'
      this.serchParams.startTime=val.swapBeginTime
      this.serchParams.endTime=val.swapEndTime
      this.serchParams.exchangeNo=val.swapId
    },
    //查询和生成日志文件
    handleExportLog(){
      if(this.dialogType ==='find'){
        this.serchParams.signals=this.robotValue
        this.$router.push({name:"Robot",params:this.serchParams})
      }else{
        this.$refs.ExportForm.validate((valid) => {
          if (valid) {
            let addParams={
              exportName:this.ruleForm.exportName,
              signals:this.robotValue,
              exchangeNo:this.serchParams.exchangeNo,
              startTime:this.serchParams.startTime,
              endTime:this.serchParams.endTime,
              exportLogType:1
            }
            exportFile(addParams).then( res =>{
              if(res.code === 0){
                this.$router.push({path:"/manage-log/data-export"})
              }else{
                this.$message({
                  message: res.msg,
                  type: "warning",
                  duration: 1000,
                  offset: 20,
                });
              }
            })
          } else {
            return false;
          }
        });
      }
    }
  },
};
</script>
<style lang="scss" scoped>
  .el-form{
    .is-required{
        display: flex;
        align-items: center;
        justify-content: center;
        padding-right: 25px;
      }
  }
</style>