<template>
  <div class="charge-box">
    <div class="charge-tools">
      <el-form :inline="true" :model="queryParams">

        <el-form-item label="换电编号:">
          <el-input v-model="queryParams.swapId" placeholder="请输入换电编号" clearable />
        </el-form-item>

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

        <el-form-item label="换电日期:">
          <el-date-picker
            v-model="dateArr.swapDate"
            class="times"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="换电结果:">
          <el-select v-model="queryParams.swapState" clearable placeholder="全部">
            <el-option label="全部" value=""></el-option>
            <el-option label="成功" value="1"></el-option>
            <el-option label="失败" value="2"></el-option>
            <el-option label="不完整" value="0"></el-option>
            <el-option label="换电错误" value="3"></el-option>
          </el-select>
        </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-top">
        <el-button type="primary" class="daochu" @click="swapExport">导出结果</el-button>
      </div>
      <div class="charge-table-bottom">
        <el-table
          :data="datalist"
          :header-cell-style="{
            background: '#1d283e',
            borderColor: '#2f3c86',
            height: '36px',
            lineHeight: '36px',
            color:'white',
            fontSize: '16px',
          }"
          fit
          :height="tableheight"
          style="width: 100%"
        >
          <el-table-column
            prop="swapId"
            label="换电编号"
            fixed
            width="180"
          />
          <el-table-column
            prop="vehiclePlate"
            label="车牌号"
            width="100"
          />
          <el-table-column
            prop="vehicleVin"
            label="车辆识别码"
            width="200"
          />
          <el-table-column
            prop="swapBeginTime"
            label="换电开始时间"
            width="180"
          />
          <el-table-column
            prop="fullDuration"
            label="安装满电时长"
            width="120"
          />
          <el-table-column
            prop="swapDuration"
            label="换电时长"
            sortable
            width="110"
          />
          <el-table-column
            prop="vehicleSn"
            label="亏电电池SN"
            width="200"
          />
          <el-table-column
            label="亏电电池SOC"
            width="120"
          >
          <template slot-scope="scope">
              {{ scope.row.vehicleSoc | PercentFilter}}
          </template>
          </el-table-column>
          <el-table-column
            label="亏电电池SOH"
            width="120"
          >
          <template slot-scope="scope">
              {{ scope.row.vehicleSoh | PercentFilter}}
          </template>
          </el-table-column>
          <el-table-column
            prop="swapSn"
            label="满电电池SN"
            width="228"
          />
          <el-table-column
            label="满电电池SOC"
            width="120"
          >
            <template slot-scope="scope">
              {{ scope.row.swapSoc | PercentFilter}}
            </template>
          </el-table-column>
          <el-table-column
            label="满电电池SOH"
            width="150"
          >
            <template slot-scope="scope">
              {{ scope.row.swapSoh | PercentFilter}}
            </template>
          </el-table-column>
          <el-table-column
            prop="swapState"
            label="换电结果"
            width="90"
          >
            <template slot-scope="scope">
              {{ scope.row.swapState===1?'换电成功': scope.row.swapState===2?'换电失败':scope.row.swapState===3?'换电错误':'不完整'}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="230" align="center" fixed="right">
            
            <template slot-scope="scope">
              <el-button type="primary" class="handle" @click="RecordDetail(scope.row.id)" size="small">详情</el-button>
              <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="onlineManage">
      <el-dialog title="换电详情" :visible.sync="dialogRecordDetailVisible" width="1600px">
        <div class="charge-RecordDetail" :style="{'height':tableheight+'px'}">
            <el-tabs v-model="activeName" @tab-click="handleDialogTab">
              <el-tab-pane label="基本信息" name="first">
                <div class="RecordBottom">
                  <div class="DetailDefault">
                    <div class="DetailList">
                        <span>换电编号：</span>
                        <el-tooltip :content="Detail.swapId" placement="top" effect="light">
                          <div class="frame">{{ Detail.swapId  || '—'}}</div>
                        </el-tooltip>
                    </div>
                    <DetailList label="换电开始时间" :value="Detail.swapBeginTime"/>
                    <DetailList label="满电电池SN" :value="Detail.swapSn"/>
                    <DetailList label="亏电电池SN" :value="Detail.vehicleSn"/>
                    <DetailList label="是否暂停" :value="Detail.everPause?'发生':'没有'"/>
                  </div>
                  <div class="DetailDefault">
                    <DetailList label="换电模式" :value="Detail.startMode?'小程序发起':'站控发起'"/>
                    <DetailList label="换电结束时间" :value="Detail.swapEndTime"/>
                    <DetailList label="满电电池SOC" :value="Detail.swapSoc | PercentFilter"/>
                    <DetailList label="亏电电池SOC" :value="Detail.vehicleSoc | PercentFilter"/>
                    <DetailList label="是否中止" :value="Detail.everStop?'发生':'没有'"/>
                  </div>
                  <div class="DetailMin">
                    <DetailList label="选电模式" :value="Detail.chooseMode?'手动':'自动'"/>
                    <DetailList label="安装满电时长" :value="Detail.fullDuration "/>
                    <DetailList label="满电电池SOH" :value="Detail.swapSoh | PercentFilter"/>
                    <DetailList label="亏电电池SOH" :value="Detail.vehicleSoh | PercentFilter"/>
                    
                  </div>
                  <div class="DetailMin" style="width: 248px;">
                    <DetailList label="换电结果" :value="swapResult"/>
                    <DetailList label="换电时长" :value="Detail.swapDuration"/>
                    <DetailList label="满电电池仓位" :value="Detail.swapCode"/>
                    <DetailList label="是否急停" :value="Detail.everEmergency?'发生':'没有'"/>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="车辆信息" name="second">
                <div class="RecordBottom">
                    <div class="DetailDefault">
                      <DetailList label="车牌号" :value="Detail.vehiclePlate"/>
                      <!-- <DetailList label="车辆电池SN" :value="Detail.vehicleSn"/> -->
                    </div>
                    <div class="DetailDefault">
                      <DetailList label="车辆识别码" :value="Detail.vehicleVin"/>
                      <!-- <DetailList label="车辆电池SOC" :value="Detail.vehicleSoc | PercentFilter"/> -->
                    </div>
                    <div class="DetailDefault">
                      <!-- <DetailList label="车辆里程(km)" :value="Detail.vehicleOdo"/> -->
                      <!-- <DetailList label="车辆电池SOH" :value="Detail.vehicleSoh | PercentFilter"/> -->
                    </div>
                    <div class="DetailMin"></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="预选电池" name="third">
                <div class="RecordBottom" style="margin: 0;">
                  <div class="DetailDefault"><DetailList label="预选电池仓位" :value="Detail.preselectionCode"/></div>
                  <div class="DetailDefault" style="width:365px;"><DetailList label="预选满电电池SN" :value="Detail.preselectionSn"/></div>
                  <div class="DetailMin" style="width:268px;"><DetailList label="预选满电电池SOC" :value="Detail.preselectionSoc | PercentFilter"/></div>
                  <div class="DetailMin" style="width:268px;"><DetailList label="预选满电电池SOH" :value="Detail.preselectionSoh | PercentFilter"/></div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="更换快照" name="fourth">
                <div class="DetailStoreList">
                    <div class="DetailStore" v-for="(item,index) in Detail.beginBatSnapshot" :key="item.code">
                        <div class="StoreHead">{{item.code}}号仓</div>
                        <div class="StoreFoot">
                            <div class="battery-begin">
                                <span>电池编号:</span>
                                <div class="frame-text">{{ item.sn || '-' }}</div>
                                <div class="downInfo">
                                  <span>落座信号:</span><div class="frame-text">{{ item.inPlace?'已落座':'未落座' }}</div>
                                </div>
                            </div>
                            <div class="Store-direction"><img src="@/assets/record.png"></div>
                            <div class="battery-begin" v-if="item.code===Detail.endBatSnapshot[index].code">
                                <span>电池编号:</span>
                                <div class="frame-text">{{Detail.endBatSnapshot[index].sn || '-'}}</div>
                                <div class="downInfo">
                                  <span>落座信号:</span><div class="frame-text">{{Detail.endBatSnapshot[index].inPlace?'已落座':'未落座'}}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="同步信息" name="sixth">
                <div class="RecordBottom">
                  <div class="DetailDefault" style="width:310px;"><DetailList label="同步状态" :value="cloudTimeState"/></div>
                  <div class="DetailDefault" style="width:310px;"><DetailList label="同步时间" :value="Detail.uploadTime"/></div>
                  <div class="DetailDefault"></div><div class="DetailDefault"></div>
                </div>
              </el-tab-pane>
            </el-tabs>
            <div class="DetailClose">
                <div class="close" @click="dialogRecordDetailVisible=false">关闭</div>
            </div>
        </div>
        <div slot="footer" class="dialog-footer"></div>
      </el-dialog>
    </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.logCode" :label="item.logName"
                    :value="item.logCode" />
                </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 './permission.scss'
import { swapList, swapExport,RecordFile,swapRecordDetail} from '@/api/records'
import { logModel,exportFile } from "@/api/log";
import DetailList from './DetailList'
export default {
  name: 'DirectivePermission',
  components: {DetailList},
  data() {
    return {
      activeName:'first',
      ExhangeNo:'',
      // 查询时间数组
      dateArr: {
        swapDate: []
      },
      // 数据列表
      datalist: [],
      // 查询参数
      queryParams: {
        page: 1, // 当前页
        pageSize: 10, // 每页条数
        vehiclePlate: undefined, // 车牌号
        swapId: undefined, // 换电编号
        swapBeginTime: undefined,
        swapEndTime: undefined,
        orderByField: undefined, // 排序字段
        orderByWays: 'desc',// 排序方式
        swapState:undefined
      },
      total: 0, // 总条数，
      tableheight: 0,// 表格高度设置
      dialogRecordDetailVisible:false,//详情弹窗状态
      Detail:{},
      //日志查询参数
      serchParams:{
        exchangeNo:undefined,//换电编号
        startTime:undefined,//开始时间
        endTime:undefined,//结束时间
        signals:[],//日志范围
      },
      ruleForm:{
        exportName:undefined,
      },
      rules:{
        exportName: [
            { required: true, message: '请输入任务名称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ],
      },
      dialogexportVisible: false, // 弹窗显示
      logOptions: [],
      logheader: [],
      robotValue: "",
      loading: false,
      dialogType: "find", // 按钮类型(find、export)
    }
  },
  computed:{
    swapResult(){
      switch(this.Detail.swapState){
        case 0:
          return '不完整';
        case 1:
          return '换电成功';
        case 2:
          return '换电失败';
        case 3:
          return '换电错误'
      }
    },
    cloudTimeState(){
      switch(this.Detail.state){
        case 0:
          return '待上传'
        case 1:
          return '上传成功'
        case 2:
          return '上传失败'
      }
    }
  },
  mounted() {
    this.swapList()
    this.onLoadHeight()//设置初始视窗高度
    this.changeWindow()//设置窗口变化高度
    this.getLogModel()
  },
  methods: {
    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 = [];
      }
    },
    //获取日志数据字典
    getLogModel() {
      logModel().then((res) => {
        this.logOptions = res.data;
        this.logheader = res.data;
      });
    },
    //日志查询
    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;
          }
        });
      }
    },
    // 清空表单数据
    dialogClose() { },
    // 弹窗Tab切换
    handleDialogTab(tab, event) {},
    // 换电记录列表，
    swapList() {
      const params = this.queryParams     
      swapList(params).then(res => {
        this.datalist = res.data.records
        this.total = res.data.total
      })
    },
    /** 分页下一页 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.swapList()
    },
    /** 分页选择页数 */
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.swapList()
    },
    // 搜索
    handleQuery() {     
      if (this.dateArr.swapDate!==null && this.dateArr.swapDate.length !== 0) {
        this.queryParams.swapBeginTime = this.dateArr.swapDate[0]+' '+'00:00:00'
        this.queryParams.swapEndTime = this.dateArr.swapDate[1]+' '+'23:59:59'
      }else{
        this.queryParams.swapBeginTime=undefined
        this.queryParams.swapEndTime=undefined
      }
      this.swapList()
    },
    // 搜索重置
    resetForm() {
      this.queryParams.swapBeginTime = undefined
      this.queryParams.swapEndTime = undefined
      this.queryParams.swapId = undefined
      this.queryParams.vehiclePlate = undefined
      this.queryParams.swapState=undefined
      this.dateArr.swapDate=[]
      this.swapList()
    },
    // 导出结果
    swapExport() {
      this.$confirm('确认导出结果？', '导出结果', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async() => {
          const res = await swapExport(this.queryParams)
          //const execlUrl=serverUrl.devServer.proxy['/api'].target+'/excel/'+res.data
          const execlUrl=process.env.VUE_APP_BASE_API+'/excel/'+res.data
          const resUrl=await RecordFile(execlUrl, res.data)
        })
      .catch(err => { console.error(err) })
    },
    //换电记录详情
    RecordDetail(id){
      this.dialogRecordDetailVisible=true     
      if(id){
        swapRecordDetail(id).then(res=>{          
          if(res.code ===0){
            this.Detail=res.data
          }else{
            this.$message.error(res.msg)
          }
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-form{
    .is-required{
        display: flex;
        align-items: center;
        justify-content: center;
        padding-right: 25px;
      }
  }
</style>