<template>
  <div>
    <div 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="ccode">
              <el-select v-model="queryParams.ccode" style="width: 200px;">
                  <el-option v-for="n in gongslist" :label="n.cname" :value="n.ccode" @click="getcname(n)" />
              </el-select>
          </el-form-item>

          <el-form-item label="订单号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="车牌号" prop="plateNum">
              <el-input v-model="queryParams.plateNum" placeholder="请输入车牌号" clearable />
          </el-form-item>
          <el-form-item label="订单开始时间" prop="orderTimeBegin">
            <el-date-picker
              v-model="queryParams.orderTimeBegin"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%;" 
              type="datetime"
              placeholder="请选择时间"
            />
          </el-form-item>
          <el-form-item label="订单结束时间" prop="orderTimeEnd">
            <el-date-picker
              v-model="queryParams.orderTimeEnd"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%;" 
              type="datetime"
              placeholder="请选择时间"
            />
          </el-form-item>
          <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 label="交易编码" prop="tradeNo">
              <el-input v-model="queryParams.tradeNo" placeholder="请输入交易编码" clearable />
          </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="Wallet" 
        @click="payment(1)">支付</el-button>
      <el-table 
        style="width:100%;margin-top: 10px;"
        :data="yysList"
        border
        stripe
        max-height="600px"
        @selection-change="selChange"
      >
          <el-table-column type="selection" width="55" />
          <el-table-column label="订单号" min-width="320" align="center" prop="orderNo" :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="120" align="center" prop="plateNum" :show-overflow-tooltip="true" />
          <el-table-column label="订单时间" min-width="200" align="center" prop="orderTime" :show-overflow-tooltip="true" />
          <el-table-column label="金额账号" min-width="120" align="center" prop="accountCode" :show-overflow-tooltip="true" />
          <el-table-column label="订单金额" min-width="120" align="center" prop="amount" :show-overflow-tooltip="true">
            <template #default="scope">
                <div>{{scope.row.amount/100}}</div>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" min-width="120" 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>
              <div v-else-if="scope.row.status == 6" style="color: #ff6000;">待结算</div>
              <div v-else-if="scope.row.status == 7">已完成</div>
              <div v-else-if="scope.row.status == 7">已取消</div>
            </template>
          </el-table-column>
          <el-table-column label="计费方式" min-width="120" align="center" prop="feeType" :show-overflow-tooltip="true">
            <template #default="scope">
              <div v-if="scope.row.feeType == 1">ODO</div>
              <div v-else-if="scope.row.feeType == 2">SOC</div>
              <div v-else-if="scope.row.feeType == 3">换电量</div>
            </template>
          </el-table-column>
          <el-table-column label="基础费用" min-width="120" align="center" prop="basicFee" :show-overflow-tooltip="true" />
          <el-table-column label="服务开始时间" min-width="120" align="center" prop="serviceTimeBegin" :show-overflow-tooltip="true" />
          <el-table-column label="服务结束时间" min-width="120" align="center" prop="serviceTimeEnd" :show-overflow-tooltip="true" />
          
          <el-table-column label="服务费" min-width="120" align="center" prop="serviceFee" :show-overflow-tooltip="true" />
          <el-table-column label="上次租赁电池时车辆里程" min-width="180" align="center" prop="lastRentBatCarOdo" :show-overflow-tooltip="true" />
          <el-table-column label="归还电池时车辆里程" min-width="150" align="center" prop="nowReturnBatCarOdo" :show-overflow-tooltip="true" />
          
          <el-table-column label="按ODO换电费" min-width="120" align="center" prop="odoAmount" :show-overflow-tooltip="true" />
          <el-table-column label="总充电量" min-width="120" align="center" prop="electAmount" :show-overflow-tooltip="true" />
          <el-table-column label="租借电池包仓位" min-width="120" align="center" prop="rentBatNo" :show-overflow-tooltip="true" />

          <el-table-column label="租用电池包编码" min-width="120" align="center" prop="rentBatCode" :show-overflow-tooltip="true" />
          <el-table-column label="租用电池包SOC" min-width="120" align="center" prop="rentBatSoc" :show-overflow-tooltip="true" />
          <el-table-column label="归还电池包编码" min-width="120" align="center" prop="returnBatCode" :show-overflow-tooltip="true" />
          
          <el-table-column label="归还电池包仓位" min-width="120" align="center" prop="returnBatNo" :show-overflow-tooltip="true" />
          <el-table-column label="归还电池包SOC" min-width="120" align="center" prop="returnBatSoc" :show-overflow-tooltip="true" />
          <el-table-column label="归还电池租出时soc" min-width="150" align="center" prop="returnBatRentSoc" :show-overflow-tooltip="true" />

          <el-table-column label="归还电池租出的换电站" min-width="160" align="center" prop="returnBatRentStationName" :show-overflow-tooltip="true" />
          <el-table-column label="换电模式" min-width="120" align="center" prop="changeMode" :show-overflow-tooltip="true">
            <template #default="scope">
              <div v-if="scope.row.changeMode == 1">全自动</div>
              <div v-else-if="scope.row.changeMode == 2">半自动</div>
              <div v-else-if="scope.row.changeMode == 3">人工干预</div>
            </template>
          </el-table-column>
          <el-table-column label="换电车道" min-width="120" align="center" prop="changeLane" :show-overflow-tooltip="true">
            <template #default="scope">
              <div v-if="scope.row.changeMode == 1">A车道</div>
              <div v-else-if="scope.row.changeMode == 2">B车道</div>
              <div v-else-if="scope.row.changeMode == 3">人工干预</div>
            </template>
          </el-table-column>
          <el-table-column label="交易编码" min-width="120" align="center" prop="tradeNo" :show-overflow-tooltip="true" />
        </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" 
      width="500" 
      :align-center="true"
      :close-on-click-modal="false"
      @close="zfclose"
    >
    <div style="width: 100%;padding: 25px;text-align: center;">
      <div style="padding-bottom: 15px;font-size: 22px;">请打开微信扫一扫完成支付</div>
      <div v-if="qscode" style="display: flex;padding-bottom: 15px;align-items: center;justify-content: center;">
        <div style="padding-right: 10px;">剩余支付时间</div>

        <div style="padding-right: 6px;color: #ff6000;"><span style="font-size: 22px;">{{tmminute}} </span>分</div>
        <div style="color: #ff6000;"><span style="font-size: 22px;">{{tmsecond}} </span>秒</div>
      </div>
      <div v-if="qscode" style="position: relative;width: 200px;height: 200px;margin: 0 auto;">
        <div v-if="issx" @click="payment()" style="position: absolute;top: 0;left: 0;width: 200px;height: 200px;line-height: 200px;font-size: 20px;color: #fff;background:rgba(0, 0, 0, 0.7);cursor: pointer;">点击重新获取</div>
        <img :src="qscode" width="200" height="200" />
      </div>
      
      <div v-else style="width:200px;height:200px;margin: 0 auto;line-height: 200px;text-align: center;">正在生成二维码...</div>
    </div>
    </el-dialog>    
  </div>
</template>
<script setup lang="ts" name="UserPage">
      import { 
          gethdzlist
      } from '@/api/swapstation/hdz'
      import { 
          getjqrlist, 
          batchpayment,
          getip,
          paystatus
      } from '@/api/order/replabatt'

      import { 
        getlist
      } from '@/api/operation/company'
     //  import { 
    //   getdict
    //  } from '@/api/systemSet/dict'
    // import { jsonp } from 'vue-jsonp'
    import { ref,reactive} from 'vue'
    import { ElMessage, ElMessageBox } from 'element-plus'

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


    let queryParams = reactive({
      pageSize:20,	          //每页条数
      pageNo:1,	              //页数
      orderNo:'',	            //订单编码
      plateNum:'',	          //车牌号
      orderTimeBegin:'',	    //订单时间开始,示例值(yyyy-MM-dd HH:mm:ss)
      orderTimeEnd:'',	      //订单时间结束
      stationCode:'',	        //换电站编码
      stationName:'',	        //换电站名称
      userId:'',	            //换电车主ID
      tradeNo:'',             //交易编码
      status:'6',             //订单状态
      ccode:''                //公司编码
   })
    
    //查询
    let total = ref(0)
    let yysList = ref<any>([])
    function handBtnqu(){
      queryParams.pageNo = 1
      getyys()
    }
    
    let cname = ref('')
    //初始查询公司
    let gongslist = ref<any>([])
    getlist({
      pageSize:1000,	          //每页条数
      pageNo:1	              //页数
    }).then(rps => {
        if(rps.data){
          let list = (rps.data as any).records
          gongslist.value = list?list:[]
          queryParams.ccode = gongslist.value[0].ccode
          cname.value = gongslist.value[0].cname
          getyys()
        }
    })

    function getcname(n:any){
      cname.value = n.cname
    }

    //初始查询换电站
    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()
          }
      })
      
    
    let wxuser = ref('')
   

    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 dzarr = ref<any[]>([])

  //获取ip
  getip().then(rps => {
    payqs.payerClientIp = rps.data
  })

  let openpop = ref(false)

  //总金额
  let totalAmount = ref<any>(0)
  //订单号
  let orderNo = ref('')
  function selChange(v:any) {
    dzarr.value = v
    totalAmount.value = 0
    let odrarr = []
    if(v.length > 0){
      odrarr = v.map((e:any) => {
        e.amount = e.amount*1
        totalAmount.value += e.amount
        return e.orderNo
      })
    }
    orderNo.value = odrarr.join()

  }

  let payqs = reactive<any>({
		//wuid:'',                                    //公司编码, 
    ccode:'',                                   //公司编码
		description:'',											        //订单总描述 公司名称+日期
		total:0,												            //支付金额，单位：分
	  timeExp:'',											            //支付结束时间
		attach:{												            //订单附加信息
			type: 2,											            //"1-充值,2-订单。类型 number"
			orderNo:'', 										          //"订单号",
			trader:'',											          //交易发起人
			tradercode:'',                            //uni.getStorageSync('wxuid')				//交易人编码
      description:''
			//walletCode:''										        //钱包编码
			// ownerId:'', 										        //"户主ID，个人wuid，企业:公司编码",
			// walletCode:'' 									        //"钱包编码"
		},								
		// goodsDetail:[
		// 	{
		// 		merchantGoodsId:'',		                  //商户侧商品编码
		// 		wechatpayGoodsId:'',	                  //微信支付定义的统一商品编号（没有可不传）
		// 		goodsName:'',			                      //商品的实际名称
		// 		quantity:1,				                      //商品数量
		// 		unitPrice:0				                      //商品价格
		// 	}
		// ],
		payerClientIp:'',				                    //用户IP
		//deviceId:'',					                      //用户设备型号
		//stationCode:''
	})
  let timer:any = null

  let qscode = ref('')
  function zfclose() {
    payqs.attach = JSON.parse(payqs.attach)
    clearInterval(timer)  
  }


  //失效倒计时
  let minute = ref<any>(29)
  let second = ref<any>(59)

  let tmminute = ref<any>(29)
  let tmsecond = ref<any>(59)

  let djstimet:any = null
  //是否失效
  let issx = ref(false) 
  function payment(type?:number) {
    if(dzarr.value.length > 0){

      //失效时间
      let sxtime:any = new Date().getTime()
      sxtime = sxtime + 30 * 60 * 1000
      sxtime = new Date(sxtime)
      let sxyear = sxtime.getFullYear()
      let sxmoth = String((sxtime.getMonth() + 1)).padStart(2,'0')
      let sxdate = String(sxtime.getDate()).padStart(2,'0')
      let sxhhour = String(sxtime.getHours()).padStart(2,'0')
      let sxminute = String(sxtime.getMinutes()).padStart(2,'0')
      let sxSeconds = String(sxtime.getSeconds()).padStart(2,'0')
  
      payqs.timeExp = `${sxyear}-${sxmoth}-${sxdate} ${sxhhour}:${sxminute}:${sxSeconds}`

      payqs.ccode = queryParams.ccode
      payqs.total = totalAmount
      payqs.attach.orderNo = orderNo.value

      payqs.attach.tradercode = queryParams.ccode
      let dateTime = new Date()
      let year = dateTime.getFullYear()
      let moth:any = String((dateTime.getMonth() + 1)).padStart(2,'0')
      //let date = String(dateTime.getDate()).padStart(2,'0')

      let ddms = `${cname.value}支付${year}年${moth}月订单`
      payqs.description = ddms
      payqs.attach.description = ddms
      if(type == 1){
        payqs.attach = JSON.stringify(payqs.attach)
      }else{
        issx.value = false
      }
      openpop.value = true
      
      qscode.value = ''
      if(timer){
        clearInterval(timer)  
      }
      

      if(djstimet){
        clearInterval(djstimet)
      }

      batchpayment(payqs).then(rps => {
        qscode.value = (rps.data as any).codeUrl

        djstimet = setInterval(() => {
            second.value--
            tmsecond.value = second.value
            if(second.value == 0 && minute.value == 0) {
              tmminute.value = '00' 
              tmsecond.value = '00'
              issx.value = true
              clearInterval(djstimet)
          }
          if(second.value == 0) {
              second.value = 59

              
              tmsecond.value = 59

              minute.value--
              if(minute.value < 10){
                tmminute.value = '0'+ minute.value
              }else{
                tmminute.value = minute.value
              }
          }
          if(second.value < 10){
            tmsecond.value = '0' + second.value
          }else{
            tmsecond.value =  second.value
          }
  
      }, 1000)

        timer = setInterval(() => {
          paystatus((rps.data as any).OutTradeNo).then(rps => {
            if((rps.data as any).tradeState == 'SUCCESS'){    //'NOTPAY'  订单未支付
              ElMessage({
                type: 'warning',
                message: '支付成功'
              })
              openpop.value = false
              handBtnqu()
            }
            
          })
        },5000)
      })
      // ElMessage({
      //     type: 'success',
      //     message: '支付成功'
      //   })
    }else{
      ElMessage({
        type: 'warning',
        message: '请选择订单'
      })
    }
  }

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