<template>
    <div>
      <div v-if="zjtype == 1 && search" class="app-container" style="margin-bottom: 12px;padding-bottom: 5px;border-radius: 10px;">
        <el-form
          ref="querform" 
          :model="queryParams" 
          :inline="true" 
        >
            <el-form-item label="换电站" prop="stationCode">
                <el-select v-model="queryParams.stationCode" placeholder="请选择换电站" style="width: 200px;">
                    <el-option v-for="n in yunList" :label="n.name" :value="n.code" />
                </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handBtnqu">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
      </div>
      <div class="app-container" style="margin-bottom: 12px;border-radius: 10px;">

          <template v-if="zjtype == 1">
            <div style="display: flex;justify-content: space-between;">
            <el-button 
            type="primary" 
            plain 
            icon="Plus" 
            @click="showpop(1)">新增</el-button>
            <el-tooltip class="item" effect="dark" :content="search? '隐藏搜索' : '显示搜索'" placement="top">
              <el-button size="mini" circle icon="Search" @click="search = !search" />
            </el-tooltip>
          </div>
        </template>
        <template v-else>
          <el-button 
            type="primary" 
            plain 
            icon="Plus" 
            @click="showpop(1)">新增</el-button>
        </template>
        <el-table 
          style="width:100%;margin-top: 10px;"
          :data="yysList"
          border
          stripe
          :max-height="theight"
        >

            <el-table-column label="电池编码" min-width="150" align="center" prop="batCode" :show-overflow-tooltip="true">
              <template #default="scope">
                <div @click="showpop(2,scope.row)" style="display: inline-block;color:#16599d;border-bottom: 1px solid #417ebb;cursor:pointer">{{scope.row.batCode}}</div>
              </template>
            </el-table-column>
            
            <el-table-column label="电池型号" min-width="150" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <!-- <el-table-column label="电池型号编码" min-width="150" align="center" prop="typeCode" :show-overflow-tooltip="true" /> -->
            <!-- <el-table-column label="初始来源" min-width="80" align="center" prop="sourceFrom" :show-overflow-tooltip="true">
                <template #default="scope">
                    <div v-if="scope.row.status == 1">站</div>
                    <div v-else-if="scope.row.status == 2">车</div>
                </template>
            </el-table-column> -->
            <el-table-column label="状态" min-width="80" align="center" prop="status" :show-overflow-tooltip="true">
                <template #default="scope">
                    <div v-if="scope.row.status == 1">出租中</div>
                    <div v-else-if="scope.row.status == 2">充电中</div>
                    <div v-else-if="scope.row.status == 3">充电完毕</div>
                    <div v-else-if="scope.row.status == 4">故障</div>
                    <div v-else-if="scope.row.status == 5">其他</div>
                </template>
            </el-table-column>

            <el-table-column label="生产日期" min-width="110" align="center" prop="productionDate" :show-overflow-tooltip="true" />
            <el-table-column label="注册时间" min-width="110" align="center" prop="registrationDate" :show-overflow-tooltip="true" />

            <!-- <el-table-column label="站码或车牌照" min-width="110" align="center" prop="sourceCode" :show-overflow-tooltip="true" /> -->
            
            <el-table-column v-if="zjtype == 1" label="当前位置" min-width="130" align="center" prop="pointName" :show-overflow-tooltip="true" />
            <!-- <el-table-column v-if="zjtype == 1" label="换电站编码" min-width="130" align="center" prop="stationCode" :show-overflow-tooltip="true" /> -->
            <el-table-column label="当前电量" min-width="80" align="center" prop="soc" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" width="240" fixed="right">
              <template #default="scope">
                <el-button link type="primary" icon="SetUp" @click="dcsjhand(scope.row.batCode)">实时数据</el-button>
                <el-button link type="primary" icon="Tickets" @click="zhuixpop(scope.row.batCode)">追溯</el-button>
                <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="total > 10" style="display: flex;justify-content: right;padding-top:20px;">
            <el-pagination
              v-model:current-page="queryParams.pageNo"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[10, 20, 30, 40]"
              background
              size="small"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="getyys"
            />
          </div>
          
      </div>
  
    
      <!-- 添加或修改配置对话框 -->
        <el-dialog 
          v-model="openpop" 
          :title="ystit" 
          width="600px" 
          append-to-body
          :close-on-click-modal="false"
        >

        <el-form ref="yysRef" :model="addata" :rules="rules" label-width="130px">
          <el-row>
            <el-col :span="24">
                <el-form-item label="电池型号" prop="typeCode">
                    <el-select v-model="addata.typeCode" @change="dchand" placeholder="请选择电池型号">
                        <el-option @click.native="getdcname(n.typeName)" v-for="n in dctypelist" :label="n.typeName" :value="n.typeCode" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="电池编码" prop="batCode">
                    <el-input v-model="addata.batCode" placeholder="请输入电池编码" clearable />
                </el-form-item>
            </el-col>
            <el-col v-if="zjtype == 1" :span="24">
                <el-form-item label="初始来源" prop="sourceFrom">
                  <el-radio-group v-model="addata.sourceFrom" @input="sourcechang">
                    <el-radio value="1">站</el-radio>
                    <el-radio value="2">车</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-col>
            <el-col v-if="zjtype == 1 && addata.sourceFrom == '1'" :span="24">
                <el-form-item label="换电站" prop="sourceCode">
                    <el-select v-model="addata.sourceCode" placeholder="请选择换电站">
                        <el-option @click.native="gethdzname(n.name)" v-for="n in yunList" :label="n.name" :value="n.code" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24" v-if="addata.sourceFrom == '2'">
                <el-form-item label="车牌号" prop="sourceCode">
                    <el-input v-model="addata.sourceCode" placeholder="请输入车牌号" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="状态" prop="status">
                    <el-select v-model="addata.status" placeholder="请选择状态">
                        <el-option label="出租中" value="1" />
                        <el-option label="充电中" value="2" />
                        <el-option label="充电完毕" value="3" />
                        <el-option label="故障" value="4" />
                        <el-option label="其它" value="5" />
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="生产日期" prop="productionDate">
                <el-date-picker
                    v-model="addata.productionDate"
                    value-format="YYYYMMDD"
                    style="width: 100%;" 
                    type="date"
                    placeholder="请选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="注册日期" prop="registrationDate">
                <el-date-picker
                    v-model="addata.registrationDate"
                    value-format="YYYYMMDD"
                    style="width: 100%;" 
                    type="date"
                    placeholder="请选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="电池仓序号" prop="dccNo">
                    <el-input v-model="addata.dccNo" placeholder="请输入电池仓序号" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="当前电量" prop="soc">
                    <el-input v-model="addata.soc" placeholder="请输入当前电量" clearable />
                </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleAdd">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!--电池追溯-->
      <el-drawer 
        v-model="zspop" 
        :with-header="false"
        size="600"
      >
      <div>电池轨迹</div>
      <div style="height: 500px;padding: 20px;overflow-y:auto;">
        <el-steps direction="vertical" :active="gjlist.length">
          <el-step v-for="n in gjlist" :title="`${n.pointName}----${n.beginTime}`" />
        </el-steps>
      </div>
      <div style="text-align: center;">
        <el-button type="primary" @click="zhuishand">添加追溯</el-button>
        <el-button @click="zspop = false">关闭</el-button>
      </div>
      </el-drawer>

      <!-- 添加电池追溯 -->
      <el-dialog 
          v-model="dczspop" 
          title="添加电池追溯" 
          width="600px" 
          append-to-body
          :close-on-click-modal="false"
        >

        <el-form ref="dczsRef" :model="addzsdata" :rules="zsrules" label-width="130px">
          <el-row>
            <!-- <el-col :span="24">
                <el-form-item label="电池编码" prop="batCode">
                    <el-input v-model="addzsdata.batCode" placeholder="请输入电池编码" clearable />
                </el-form-item>
            </el-col> -->
            <el-col :span="24">
                <el-form-item label="轨迹点类型" prop="pointType">
                  <el-radio-group v-model="addzsdata.pointType">
                    <el-radio value="1">站</el-radio>
                    <el-radio value="2">车</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-col>  
            <el-col v-if="addzsdata.pointType == '1'" :span="24">
                <el-form-item label="换电站" prop="pointCode">
                    <el-select v-model="addzsdata.pointCode" placeholder="请选择换电站">
                        <el-option @click.native="getgjdname(n.name)" v-for="n in yunList" :label="n.name" :value="n.code" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col v-else :span="24">
                <el-form-item label="车牌照" prop="pointCode">
                    <el-input v-model="addzsdata.pointCode" placeholder="请输入车牌照" clearable />
                </el-form-item>
            </el-col>
            
            <el-col :span="24">
              <el-form-item label="开始时间" prop="beginTime">
                <el-date-picker
                    v-model="addzsdata.beginTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%;" 
                    type="datetime"
                    placeholder="请选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                    v-model="addzsdata.endTime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%;" 
                    type="datetime"
                    placeholder="请选择日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="adddczs">确 定</el-button>
            <el-button @click="dczspop = false">关 闭</el-button>
          </div>
        </template>
      </el-dialog>

    <!--实时数据-->
    <el-dialog 
        v-model="realdatapop" 
        title=""
        width="850px"
        fullscreen 
        append-to-body
        :close-on-click-modal="false"
    >
      <template #header>
        <div  style="font-size: 20px;">
          电池编码：{{diancode}}
        </div>
      </template>
      
      <el-date-picker
        v-model="times"
        type="daterange"
        value-format="YYYY-MM-DD"
         @calendar-change="handleCalendarChange"
        :disabled-date="disabledDate"
        unlink-panels
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @clear="cleardate"
        
      />

      <!--:shortcuts="shortcuts"-->

      <el-button type="primary" @click="getdcdata" style="margin-left: 30px;">查询</el-button>

      <el-row :gutter="30">
        <el-col :span="24">
            <div ref="refChart" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart1" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart2" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart3" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart4" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart5" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart6" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
         <el-col :span="24">
            <div ref="refChart7" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart8" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart9" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart10" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart11" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart12" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <!-- <el-col :span="24">
            <div ref="refChart13" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart14" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col>
        <el-col :span="24">
            <div ref="refChart15" class="chart-cont2" style="height: 400px;margin-top: 20px;padding:10px;border-radius: 10px;box-shadow: 0 0 20px -5px rgba(84, 151, 232, 0.5);background: #fff;"></div>
        </el-col> -->
      </el-row>
    </el-dialog>
    </div>
  </template>
  <script setup lang="ts" name="UserPage">
        import { 
            gethdzlist
        } from '@/api/swapstation/hdz'

        import { 
            getjqrlist, 
            addhdz, 
            update,
            delhdz,
            getzhuis,
            addzhuis,
            getdcsj
        } from '@/api/swapstation/battery'

        import { 
          getdicttype
        } from '@/api/systemSet/modelno'
      //  import { 
      //   getdict
      //  } from '@/api/systemSet/dict'
      import { ref,reactive,computed,watch} from 'vue'
      import { ElMessage, ElMessageBox } from 'element-plus'

      import * as echarts from 'echarts'
      
      const props = withDefaults(defineProps<{
        zjtype?:string|number
        stationCode?:string
        stationName?:string
        list:any[]
      }>(), {
        zjtype:1,
        stationCode:'',
        stationName:'',
        list:() => []
      })

      const emit = defineEmits<{
        update: []
      }>()

      let firstSelectedDate = ref<any>('')
      const handleCalendarChange = (val:any) => {
        firstSelectedDate.value = val[0]
      }
      const disabledDate = (time:any) => {
        if (!firstSelectedDate.value) return false
        
        // 示例：限制选择范围为选中日期的前后7天
        const startTime = firstSelectedDate.value.getTime() - 7 * 24 * 3600 * 1000
        const endTime = firstSelectedDate.value.getTime() + 7 * 24 * 3600 * 1000
        
        return time.getTime() < startTime || time.getTime() > endTime
      }


      const cleardate = () => {
        firstSelectedDate.value = ''
      }


      let search = ref(true)
      let theight = computed(() => {
        if(props.zjtype == 1 && !search.value){
          //?'600px':'400px'
          return '680px'
        }
        if(props.zjtype == 1){
          return '600px'
        }
        return '400px'
      }) 
      

      let queryParams = reactive({
        pageSize:20,	      //每页条数
        pageNo:1,	          //页数
        stationCode:props.zjtype == 1?'':props.stationCode       //换电站编码  ??
      })
      
      //查询
      let total = ref(0)
      let yysList = ref<any>([])
      function handBtnqu(){
        queryParams.pageNo = 1
        getyys()
      }
      
      

      //初始查询电池型号
      let dctypelist = ref<any[]>([])
      getdicttype({
        pageSize:50,	        //每页条数
        pageNo:1
      }).then(rps => {
        dctypelist.value = (rps.data as any).records
      })

      function dchand(v:any) {
        console.log(v)
      }

      //初始查询换电站
      let yunList = ref<any>([])
      gethdzlist({
          pageSize:20,	      //每页条数
          pageNo:1,	          //页数
          proxyId:'',	          //归属运营商ID
          name:'',	          //站点名称
          code:'',	          //站点编码
          status:'',	          //状态：1-正常营业，2-正常停运，3-故障停运，4-指令停运，9-其它
          type:'',	          //站点类型ID
        }).then(rps => {
            if(rps.data){
                let list = (rps.data as any).records
                yunList.value = list?list:[]
                //queryParams.stationCode = list[0].code
                //getyys()
            }
        })
      if(props.zjtype == 1){
        
        getyys()
      }else{
        if(props.list.length > 0){
          yysList.value = props.list
        }
      }
      
      //初始查询字典类型
      // let yxtype = ref<any>([])
      // getdict({
      //   typeCode:'robotyxms'
      // }).then(rps => {
      //   yxtype.value = rps.data
      // })  

      function getyys() {
        yysList.value.splice(0)
        total.value = 0
        getjqrlist(queryParams).then(rps => {
            if(rps.data){
              yysList.value = (rps.data as any).records
              total.value = (rps.data as any).total
            }
        })
      }

      function handleSizeChange(val:number) {
        queryParams.pageSize = val
        getyys()
      }
      
      //重置
      let querform = ref()
      function resetQuery() {
        querform.value?.resetFields()
      }

      
      //新增、修改
      let type = ref(1)
      let openpop = ref(false)
      let ystit = ref('添加电池')
      let yysRef = ref()
      let slecas = ref('')
      let addata = reactive({
        typeCode:'',	                                  //电池型号编码
        typeName:'',                                    //电池型号名称
        batCode:'',	                                    //电池编码
        sourceFrom:'1',	                                //初始来源：1-站，2-车
        sourceCode:'',	                                //站码或车牌照
        status:'',	                                    //状态：1-出租中，2-充电中，3-充电完毕，4-故障，5-其它
        pkId:'',
        productionDate:'',	                            //生产日期
        registrationDate:'',	                          //注册时间
        
        //stationCode:'',	                                //换电站编码
        //stationName:'',                                 //换电站名称
        soc:'',	                                        //当前电量
        dccNo:'',                                       //电池仓序号    
        pointType:'',                                   //轨迹点类型 1-站，2-车
        pointCode:'',	                                  //轨迹点编码
        pointName:''	                                  //轨迹点名称
      })

      // watch(() => addata.sourceFrom,() => {
      //   addata.sourceCode = ''
      // })

      function sourcechang() {
        addata.sourceCode = ''
        console.log(addata.sourceCode,'chang')
      }

      function getdcname(n:string) {
        addata.typeName = n
      }

      function gethdzname(n:string) {
        addata.pointName = n
      }

      const rules = ref({
        typeCode:[
            { required: true, message: "请输入电池型号编码", trigger: "blur" }
        ],
        batCode:[
          { required: true, message: "请输入电池编码", trigger: "blur" }
        ],
        sourceFrom:[
          { required: true, message: "请选择初始来源", trigger: "blur" }
        ],
        sourceCode:[
            { required: true,validator:(rule:any, value:any, callback:any) => {
              if(value.length == ''){
                if (addata.sourceFrom == '1') {
                  return callback(new Error('请选择换电站'))
                }
                return callback(new Error('请输入车牌号'))
              }
              return callback()
            }, trigger: "blur" 
          }
        ],
        // stationCode:[
        //   { required: true, message: "请选择换电站", trigger: "blur" }
        // ],
        status:[
          { required: true, message: "请选择状态", trigger: "blur" }
        ]
      })



      function showpop(num:any,row?:any){
        type.value = num
        openpop.value = true
        ystit.value = num == 1?'添加电池':'修改电池'
        yysRef.value?.resetFields()
        if(row){
          addata.typeCode = row.typeCode	              
          addata.batCode = row.batCode	                
          addata.sourceFrom = row.sourceFrom+''	            
          addata.status = row.status+''	                
          addata.pkId = row.pkId
          addata.productionDate = row.productionDate?row.productionDate:''	        
          addata.registrationDate = row.registrationDate?row.registrationDate:''	      
          
          addata.sourceCode = row.sourceCode?row.sourceCode:''	 

          addata.pointCode = row.sourceCode?row.sourceCode:''	                            
          addata.pointName = row.pointName?row.pointName:''

          // addata.stationCode = row.pointCode?row.pointCode:''	
          // addata.stationName = row.pointName?row.pointName:''            

          addata.soc = row.soc	                             
          addata.dccNo = row.dccNo?row.dccNo:'' 
        }else{
          addata.typeCode = ''	              
          addata.batCode = ''	                
          addata.sourceFrom = '1'	            
          addata.status = ''	                
          addata.pkId = ''
          addata.productionDate = ''	        
          addata.registrationDate = ''	      
          addata.sourceCode = props.zjtype == 1?'':props.stationCode	            
          // addata.stationCode = props.zjtype == 1?'':props.stationCode	    
          // addata.stationName = ''   
          
          addata.pointCode = props.zjtype == 1?'':props.stationCode                          
          addata.pointName = props.zjtype == 1?'':props.stationName                                                          

          addata.soc = ''
          addata.dccNo = ''	                       
        }
      }
      function savehand() {
        addata.pointType = addata.sourceFrom
        addata.pointCode = addata.sourceCode
        if(type.value == 1){
            return addhdz(addata)
        }
        return update(addata)
        
      }
      //保存
      function handleAdd() {
        yysRef.value?.validate((valid:Boolean) => {

            if (valid) {
                // if(addata.sourceFrom == '1'){
                //   addata.sourceCode = addata.stationCode
                // }
                savehand().then(() => {
                ElMessage({
                    type: 'success',
                    message: type.value == 1?'添加成功':'修改成功'
                })
                setTimeout(()=> {
                    openpop.value = false
                    getyys()
                    emit('update')
                },600)
            })
            }
        })
      }

    //取消
    function cancel() {
      openpop.value = false
    }

      //删除
    function handleDelete(row:any) {
      ElMessageBox.confirm(
        `确定删除电池：${row.batCode}`,
        '温馨提示',
        {
            // confirmButtonText: '',
            // cancelButtonText: 'Cancel',
            type: 'warning',
        }
      ).then(() => {
        delhdz(row.pkId).then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功'
            })
            getyys()
            emit('update')
          })
      })
    }

    //追溯
    let zspop = ref(false)
    let dccode = ref('')
    let gjlist = ref<any[]>([])
    
    
    //添加追溯
    let dczspop = ref(false)
    let addzsdata = reactive({
      batCode:'',	             //电池编码
      pointType:'1',	          //轨迹点类型：1-电站，2-车辆
      beginTime:'',	          //开始时间,示例值(yyyy-MM-dd HH:mm:ss)
      pointCode:'',	          //轨迹点编码
      pointName:'',	          //轨迹点名称
      endTime:''	            //结束时间,示例值(yyyy-MM-dd HH:mm:ss)
    })
    
    watch(() => addzsdata.pointType,() => {
      addzsdata.pointCode = ''
    })
    const zsrules = ref({
      batCode:[
        { required: true, message: "请输入电池编码", trigger: "blur" }
      ],
      pointType:[
          { required: true, message: "请选择类型", trigger: "blur" }
      ],
     
      pointCode:[
        { required: true, validator:(rule:any, value:any, callback:any) => {
              if(value.length == ''){
                if (addzsdata.pointType == '1') {
                  return callback(new Error('请选择换电站'))
                }
                return callback(new Error('请输入车牌号'))
              }
              return callback()
            }, trigger: "blur" }
      ],
      beginTime:[
        { required: true, message: "请选择开始时间", trigger: "blur" }
      ]
    })


    function zhuixpop(code:string) {
      addzsdata.batCode = code
      dccode.value = code
      getzhuis(dccode.value).then(rps => {
        gjlist.value = rps.data as any
      })
      zspop.value = true
    }

    let dczsRef = ref()

    function zhuishand() {
      dczsRef.value?.resetFields()
      dczspop.value = true
    }
    
    function adddczs() {
      
      dczsRef.value?.validate((valid:Boolean) => {
        if (valid) {
          if(addzsdata.pointType == '2'){
            addzsdata.pointName = addzsdata.pointCode
          }
          addzhuis(addzsdata).then(() => {
              ElMessage({
                  type: 'success',
                  message: '添加成功'
              })
              dczspop.value = false
              getzhuis(dccode.value).then(rps => {
                gjlist.value = rps.data as any
              })
          })
        }
      })
    }

    function getgjdname(name:string) {
      addzsdata.pointName = name
    }

    
    //实时数据
    let realdatapop = ref(false)
    let diancode = ref('')
    let times = ref<any>([])
    const shortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        },
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          return [start, end]
        },
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        },
      },
    ]


    function dcsjhand(code:any){
      realdatapop.value = true
      firstSelectedDate.value = ''
      times.value = []
      diancode.value = code
      let date = new Date()
      let year = date.getFullYear()
      let month = String(date.getMonth() + 1).padStart(2, '0')
      let day = String(date.getDate()).padStart(2, '0')

      let start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)

      let syear = start.getFullYear()
      let smonth = String(start.getMonth() + 1).padStart(2, '0')
      let sday = String(start.getDate()).padStart(2, '0')


      getrealdata(`${syear}-${smonth}-${sday}`,`${year}-${month}-${day}`)
    }

    function getdcdata() {
      if(times.value){
        getrealdata(times.value[0],times.value[1])
      }
      
    }
    function getrealdata(beginTime:any,endTime:any) {
      getdcsj(diancode.value,`${beginTime} 00:00:00`,`${endTime} 59:59:59`).then((rps:any) => {
        if(rps.data && rps.data.batData.length > 0){
          let xdata = rps.data.batData.map((n:any) => {
            let time = new Date(n.id*1)
            
            let year = time.getFullYear()
            let month = String(time.getMonth() + 1).padStart(2, '0')
            let day = String(time.getDate()).padStart(2, '0')
            let h = String(time.getHours()).padStart(2, '0')
            let m = String(time.getMinutes()).padStart(2, '0')
            let s = String(time.getSeconds()).padStart(2, '0')

            return `${year}-${month}-${day} ${h}:${m}:${s}`
          })
          
          //电池包SOH
          let sohdata = rps.data.batData.map((n:any) => {
            return n.soh
          })

          //电池包总电流
          let batTotalcurr = rps.data.batData.map((n:any) => {
            return n.batTotalCurr
          })

          //单体电压总个数
          let batCellVoltCnt = rps.data.batData.map((n:any) => {
            return n.batCellVoltCnt
          })

          //探针温度总个数
          let probeTempCnt = rps.data.batData.map((n:any) => {
            return n.probeTempCnt
          })

          //电池包正极绝缘值
          let batPosiInsu = rps.data.batData.map((n:any) => {
            return n.batPosiinsu
          })
          //电池包负级绝缘值
          let batNegaInsu = rps.data.batData.map((n:any) => {
            return n.batNegainsu
          })

          setdcwdchart(refChart.value,xdata,sohdata,'电池包SOH','#2363a5','%')
          setdcwdchart(refChart1.value,xdata,batTotalcurr,'电池包总电流','#2363a5','A')
          setdcwdchart(refChart2.value,xdata,batCellVoltCnt,'单体电压总个数','#2363a5','')

          setdcwdchart(refChart3.value,xdata,probeTempCnt,'探针温度总个数','#2363a5','')
          setdcwdchart(refChart4.value,xdata,batPosiInsu,'电池包正极绝缘值','#2363a5','Kohm')
          
          setdcwdchart(refChart5.value,xdata,batNegaInsu,'电池包负极绝缘值','#2363a5','Kohm')
          
          // setdcwdchart(refChart4.value,xdata,testdata,'出水温度','#2363a5','℃')
          // setdcwdchart(refChart5.value,xdata,testdata,'回水温度','#2363a5','℃')
          // setdcwdchart(refChart6.value,xdata,testdata,'最低单体电压组','#2363a5','')

          // setdcwdchart(refChart7.value,xdata,testdata,'最高单体温度','#2363a5','℃')
          // setdcwdchart(refChart8.value,xdata,testdata,'最高单体温度组','#2363a5','')
          // setdcwdchart(refChart9.value,xdata,testdata,'最低单体温度','#2363a5','℃')

          // setdcwdchart(refChart10.value,xdata,testdata,'最高单体温度','#2363a5','℃')
          // setdcwdchart(refChart11.value,xdata,testdata,'最高单体温度组','#2363a5','')
          // setdcwdchart(refChart12.value,xdata,testdata,'最低单体温度','#2363a5','℃')

          // setdcwdchart(refChart13.value,xdata,testdata,'最低单体温度组','#2363a5','')
          // setdcwdchart(refChart14.value,xdata,testdata,'电池电压需求','#2363a5','V')
          // setdcwdchart(refChart15.value,xdata,testdata,'电池电流需求','#2363a5','A')
        }
        if(rps.data && rps.data.chargingData.length > 0){
          let x2data = rps.data.chargingData.map((n:any) => {
              let time = new Date(n.id*1)
              
              let year = time.getFullYear()
              let month = String(time.getMonth() + 1).padStart(2, '0')
              let day = String(time.getDate()).padStart(2, '0')
              let h = String(time.getHours()).padStart(2, '0')
              let m = String(time.getMinutes()).padStart(2, '0')
              let s = String(time.getSeconds()).padStart(2, '0')

              return `${year}-${month}-${day} ${h}:${m}:${s}`
              
            })
            let cddl = rps.data.chargingData.map((n:any) => {
              return n.chgQty 
            })

            let batMaxVolt = rps.data.chargingData.map((n:any) => {
              return n.batMaxVolt 
            })
            
            let batMinvolt = rps.data.chargingData.map((n:any) => {
              return n.batMinvolt 
            })

            let batMaxTemp = rps.data.chargingData.map((n:any) => {
              return n.batMaxTemp 
            })
            
            let batMinTemp = rps.data.chargingData.map((n:any) => {
              return n.batMinTemp 
            })

            let voltDemand = rps.data.chargingData.map((n:any) => {
              return n.voltDemand 
            })
            
            let currDemand = rps.data.chargingData.map((n:any) => {
              return n.currDemand 
            })
            
            
            setdcwdchart(refChart6.value,x2data,cddl,'充电电量','#2363a5','kWh')
            setdcwdchart(refChart7.value,x2data,batMaxVolt,'最高单体电压','#2363a5','V')
            setdcwdchart(refChart8.value,x2data,batMinvolt,'最低单体电压','#2363a5','V')
            setdcwdchart(refChart9.value,x2data,batMaxTemp,'最高单体温度','#2363a5','℃')
            setdcwdchart(refChart10.value,x2data,batMinTemp,'最低单体温度','#2363a5','℃')
            setdcwdchart(refChart11.value,x2data,voltDemand,'电池电压需求','#2363a5','V')
            setdcwdchart(refChart12.value,x2data,currDemand,'电池电流需求','#2363a5','A')
            
            
        }
        
      })
      // setTimeout(() => {
      //   let testdata = [
      //     [20,65,80,60,90,100,45,20,65,80,60,90,100,45],
      //     [30,75,50,60,80,100,45,30,75,50,60,80,100,45],
      //     [80,75,100,50,20,60,35,80,75,100,50,20,60,35],
      //     [20,65,80,60,90,100,45,20,65,80,60,90,100,45],
      //     [30,75,50,60,80,100,45,30,75,50,60,80,100,45],
      //     [80,75,100,50,20,60,35,80,75,100,50,20,60,35],
      //     [10,65,90,40,10,70,55,90,85,76,60,30,40,65]
      //   ]
      //   setdcwdchart(refChart.value,testdata,'电池包SOH','#2363a5','%')
      //   setdcwdchart(refChart1.value,[[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35],[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35]],'单体电压','#2363a5','V')
      //   setdcwdchart(refChart2.value,[[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35],[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35]],'探针温度','#2363a5','℃')
      //   setdcwdchart(refChart3.value,[[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35],[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35]],'电池包SOH','#2363a5','%')
      //   setdcwdchart(refChart4.value,[[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35],[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35]],'单体电压','#2363a5','V')
      //   setdcwdchart(refChart5.value,[[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35],[20,65,80,60,90,100,45],[30,75,50,60,80,100,45],[80,75,100,50,20,60,35]],'探针温度','#2363a5','℃')
      // },1000)
    }

const refChart = ref()
const refChart1 = ref()
const refChart2 = ref()
const refChart3 = ref()
const refChart4 = ref()
const refChart5 = ref()
const refChart6 = ref()
const refChart7 = ref()
const refChart8 = ref()
const refChart9 = ref()
const refChart10 = ref()
const refChart11 = ref()
const refChart12 = ref()
const refChart13 = ref()
const refChart14 = ref()
const refChart15 = ref()
    
let myChart: echarts.EChartsType

function setdcwdchart(e:any,xdata:any,ydata:any,tit:any,tcol:any,dw:string) {
  if (e) {
        myChart = echarts.init(e)
        let option

        option = {
            title: {
                text: tit,
                left: 'center',
                textStyle: {
                    color: tcol,//'#2363a5',
                    fontSize: 18
                }
            },
            
             grid: {
                left: '3%',
                top:'15%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                axisPointer: {
                  type: "shadow",
                },
                data:xdata
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: `{value} ${dw}`,
                }
            },
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "cross",
                crossStyle: {
                  color: "#999",
                },
              },
            },
            series: [
                {
                  
                  data: ydata,
                  symbol: 'none',
                  type: 'line',
                  //smooth: true,
                  seriesLayoutBy: 'row',
                  emphasis: { focus: 'series' },
                  endLabel: {
                    show: true,
                    formatter: '{a}',
                    distance: 2000
                  }
                }
            ]
        };

        option && myChart.setOption(option);
    }
}


  </script>
  <style scoped>
  .el-divider--horizontal{
    border-color:#5b98cd;
  }
  </style>