<template>
    <div>
      <div v-if="zjtype == 1" 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;">
        <el-button 
          type="primary" 
          plain 
          icon="Plus" 
          @click="showpop(1)">新增</el-button>
        <el-table 
          style="width:100%;margin-top: 10px;"
          :data="yysList"
          border
          stripe
          :max-height="zjtype == 1?'600px':'400px'"
        >

            <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="stationName" :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="160" fixed="right">
              <template #default="scope">
                <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 :span="24">
                <el-form-item label="初始来源" prop="sourceFrom">
                  <el-radio-group v-model="addata.sourceFrom">
                    <el-radio value="1">站</el-radio>
                    <el-radio value="2">车</el-radio>
                  </el-radio-group>
                </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" 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 v-if="zjtype == 1" :span="24">
                <el-form-item label="换电站" prop="stationCode">
                    <el-select v-model="addata.stationCode" 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">
                <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>
    </div>
  </template>
  <script setup lang="ts" name="UserPage">
        import { 
            gethdzlist
        } from '@/api/swapstation/hdz'

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

        import { 
          getdicttype
        } from '@/api/systemSet/modelno'
      //  import { 
      //   getdict
      //  } from '@/api/systemSet/dict'
      import { ref,reactive} from 'vue'
      import { ElMessage, ElMessageBox } from 'element-plus'
      
      const props = withDefaults(defineProps<{
        zjtype?:string|number
        stationCode?:string
        list:any[]
      }>(), {
        zjtype:1,
        stationCode:'',
        list:() => []
      })

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

      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>([])
      if(props.zjtype == 1){
        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()
            }
        })
        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)
        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-站，2-车
        status:'',	                //状态：1-出租中，2-充电中，3-充电完毕，4-故障，5-其它
        pkId:'',
        productionDate:'',	        //生产日期
        registrationDate:'',	      //注册时间
        sourceCode:'',	            //站码或车牌照
        stationCode:'',	            //换电站编码
        stationName:'',             //换电站名称
        soc:''	                    //当前电量
      })

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

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

      const rules = ref({
        typeCode:[
            { required: true, message: "请输入电池型号编码", trigger: "blur" }
        ],
        batCode:[
          { required: true, message: "请输入电池编码", trigger: "blur" }
        ],
        sourceFrom:[
          { 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	        
          addata.registrationDate = row.registrationDate	      
          addata.sourceCode = row.sourceCode	            
          addata.stationCode = row.stationCode	            
          addata.soc = row.soc	                             
           
        }else{
          addata.typeCode = ''	              
          addata.batCode = ''	                
          addata.sourceFrom = ''	            
          addata.status = ''	                
          addata.pkId = ''
          addata.productionDate = ''	        
          addata.registrationDate = ''	      
          addata.sourceCode = ''	            
          addata.stationCode = props.zjtype == 1?'':props.stationCode	            
          addata.soc = ''	                       
        }
      }
      function savehand() {
        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[]>([])
    function zhuixpop(code:string) {
      dccode.value = code
      getzhuis(dccode.value).then(rps => {
        gjlist.value = rps.data as any
      })
      zspop.value = true
    }

    //添加追溯
    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)
    })

    const zsrules = ref({
      batCode:[
        { required: true, message: "请输入电池编码", trigger: "blur" }
      ],
      pointType:[
          { required: true, message: "请选择类型", trigger: "blur" }
      ],
     
      pointCode:[
        { required: true, message: "请选择轨迹点", trigger: "blur" }
      ],
      beginTime:[
        { required: true, message: "请选择开始时间", trigger: "blur" }
      ]
    })

    let dczsRef = ref()

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

    function getgjdname(name:string) {
      addzsdata.pointName = name
    }
  </script>
  <style scoped>
  .el-divider--horizontal{
    border-color:#5b98cd;
  }
  </style>