<template>
    <div>
      <div v-if="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="status">
              <el-select v-model="queryParams.status" style="width: 180px" placeholder="请选择状态">
                  <el-option label="预约成功" value="1" />
                  <el-option label="已使用" value="2" />
                  <el-option label="已取消" value="3" />
                  <el-option label="已过期" value="4" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="预约车主" prop="userId">
                <el-input v-model="queryParams.userId" placeholder="请输入车主" clearable />
            </el-form-item> -->
             
            <el-form-item label="预约人" prop="ucode">
                  <el-autocomplete
                    style="width: 100%"
                    v-model="qswxuser"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入手机号查询"
                    clearable
                    @blur="qsautoblur"
                    @select="qshandleSelect"
                    @clear="qsautoclear"
                  />
            </el-form-item>

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

            <el-form-item v-if="yunList.length > 0" label="换电站" prop="stationCode">
                <el-select style="width: 200px;" v-model="queryParams.stationCode" placeholder="请选择换电站">
                    <el-option 
                      v-for="n in yunList" 
                      :label="n.name" 
                      :value="n.code"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="开始日期" prop="swapDayBegin">
                <el-date-picker
                  v-model="queryParams.swapDayBegin"
                  value-format="YYYYMMDD"
                  style="width: 150px;" 
                  type="date"
                  placeholder="开始日期"
                />
            </el-form-item>
            <el-form-item label="结束日期" prop="swapDayEnd">
                <el-date-picker
                  v-model="queryParams.swapDayEnd"
                  value-format="YYYYMMDD"
                  style="width: 150px;" 
                  type="date"
                  placeholder="结束日期"
                />
            </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;">
          <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>
        <el-table 
          style="width:100%;margin-top: 10px;"
          :data="yysList"
          border
          stripe
          :max-height="search?'550px':'680px'"
        >
            <el-table-column label="预约人姓名" min-width="120" align="center" prop="uname" :show-overflow-tooltip="true" />
      
            <el-table-column label="手机号码" min-width="120" align="center" prop="phone" :show-overflow-tooltip="true" />
            <el-table-column label="车牌号" min-width="120" align="center" prop="plateNum" :show-overflow-tooltip="true" />
            <el-table-column label="换电站名称" min-width="120" align="center" prop="stationName" :show-overflow-tooltip="true" />
            <el-table-column label="预约换电日期" min-width="120" align="center" prop="swapDay" :show-overflow-tooltip="true">
              <template #default="scope">
                    <div>{{formatDa(scope.row.swapDay)}}</div>   
              </template>
            </el-table-column>
            <el-table-column label="换电时间段" min-width="120" align="center" prop="swapDuration" :show-overflow-tooltip="true" />
            <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" style="color: #59c325;">预约成功</div>
                <div v-else-if="scope.row.status == 2" style="color: #b88230;">已使用</div>
                <div v-else-if="scope.row.status == 3">已取消</div>
                <div v-else-if="scope.row.status == 4">已过期</div>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" min-width="120" align="center" prop="ctime" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" width="100" fixed="right">
              <template #default="scope">
                <!-- <el-button link type="primary" icon="Edit" @click="showpop(2,scope.row)">修改</el-button> -->
                <el-button v-if="scope.row.status == 1" 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="550px" 
          append-to-body
          :close-on-click-modal="false"
        >
        
        <el-form ref="yysRef" :model="addata" :rules="rules" label-width="100px">
          <el-row>
            <!-- <el-col :span="12">
                <el-form-item label="订单类型" prop="orderType">
                    <el-select v-model="addata.orderType" placeholder="请选择类型">
                        <el-option label="换电" value="1" />
                        <el-option label="充电" value="2" />
                    </el-select>
                </el-form-item>
            </el-col> -->
            <el-col :span="24">
                <el-form-item label="预约人" prop="userId">
                  <el-autocomplete
                    style="width: 100%"
                    v-model="wxuser"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入手机号查询"
                    clearable
                    @blur="autoblur"
                    @select="handleSelect"
                    @clear="autoclear"
                  />
                    <!-- <el-input v-model="addata.uname" placeholder="请输入姓名" clearable /> -->
                </el-form-item>

                
            </el-col>
            <el-col :span="24">
                <el-form-item label="车牌号" prop="plateNum">
                    <el-select v-model="addata.plateNum" placeholder="请选择车牌号">
                        <el-option 
                          v-for="n in carlist" 
                          :label="n.plateNum" 
                          :value="n.plateNum"
                          
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            
            <!-- <el-col :span="24">
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="addata.phone" placeholder="请输入手机号码" clearable />
                </el-form-item>
            </el-col> -->
            <el-col :span="24">
                <el-form-item label="换电站" prop="stationCode">
                    <el-select v-model="addata.stationCode" placeholder="请选择换电站">
                        <el-option 
                          v-for="n in yunList" 
                          :label="n.name" 
                          :value="n.code"
                          @click="getlabel(n.name)" 
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="预约日期" prop="swapDay">
                    <el-date-picker
                    v-model="addata.swapDay"
                    value-format="YYYYMMDD"
                    style="width: 100%;" 
                    type="date"
                    placeholder="换电日期"
                />
                </el-form-item>
            </el-col>  
            <el-col :span="24">
              <el-form-item label="时间段" prop="swapDuration">
                <!-- <el-time-select
                  v-model="addata.swapDuration"
                  style="width: 100%"
                  start="08:30"
                  step="00:15"
                  end="18:30"
                  placeholder="请选择时间段"
                /> -->

                <el-select v-model="addata.swapDuration" placeholder="请选择时间段">
                  
                  <el-option label="0:00 - 1:00" value="0:00 - 1:00" />
                    <el-option label="1:00 - 2:00" value="1:00 - 2:00" />
                    <el-option label="2:00 - 3:00" value="2:00 - 3:00" />
                    <el-option label="3:00 - 4:00" value="3:00 - 4:00" />
                    <el-option label="4:00 - 5:00" value="4:00 - 5:00" />
                    <el-option label="5:00 - 6:00" value="5:00 - 6:00" />
                    <el-option label="6:00 - 7:00" value="6:00 - 7:00" />
                    <el-option label="7:00 - 8:00" value="7:00 - 8:00" />
                    <el-option label="8:00 - 9:00" value="8:00 - 9:00" />
                    <el-option label="9:00 - 10:00" value="9:00 - 10:00" />
                    <el-option label="10:00 - 11:00" value="10:00 - 11:00" />
                    <el-option label="11:00 - 12:00" value="11:00 - 12:00" />
                    <el-option label="12:00 - 13:00" value="12:00 - 13:00" />
                    <el-option label="13:00 - 14:00" value="13:00 - 14:00" />
                    <el-option label="14:00 - 15:00" value="14:00 - 15:00" />
                    <el-option label="15:00 - 16:00" value="15:00 - 16:00" />
                    <el-option label="16:00 - 17:00" value="16:00 - 17:00" />
                    <el-option label="17:00 - 18:00" value="17:00 - 18:00" />
                    <el-option label="18:00 - 19:00" value="18:00 - 19:00" />
                    <el-option label="19:00 - 20:00" value="19:00 - 20:00" />
                    <el-option label="20:00 - 21:00" value="20:00 - 21:00" />
                    <el-option label="21:00 - 22:00" value="21:00 - 22:00" />
                    <el-option label="22:00 - 23:00" value="22:00 - 23:00" />
                    <el-option label="23:00 - 24:00" value="23:00 - 24:00" />
                </el-select>
                </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>
    </div>
  </template>
  <script setup lang="ts" name="UserPage">
        import { 
            gethdzlist
        } from '@/api/swapstation/hdz'

        import { 
          getjqrlist, 
        } from '@/api/swapstation/vehicle'

        import { 
            getyylist, 
            addhdz, 
            delhdz
        } from '@/api/order/reservation'
        import { carNum,getDateDaysAgo } from '@/utils/validate'

        import { 
          getwxlist
        } from '@/api/operation/wxuser'
        
        import { formatDate } from '@/utils/ruoyi'
      //  import { 
      //   getdict
      //  } from '@/api/systemSet/dict'
      //import { jsonp } from 'vue-jsonp'
      import { ref,reactive} from 'vue'
      import { ElMessage, ElMessageBox } from 'element-plus'
      

      function formatDa(s:any) {
        return formatDate(s)
      }


      let search = ref(true)

      let queryParams = reactive({
        pageSize:20,	          //每页条数
        pageNo:1,	              //页数
        ucode:'',	              //换电车主ID
        status:'',
        plateNum:'',	                                        //车牌号
        swapDayBegin:getDateDaysAgo(30).replace(/-/g,''),	    //预约换电日期开始,示例值(yyyyMMdd)
        swapDayEnd:getDateDaysAgo().replace(/-/g,''),	        //预约换电日期结束
        stationCode:''	                                      //换电站编码
     })
      
      //查询
      let total = ref(0)
      let yysList = ref<any>([])
      function handBtnqu(){
        queryParams.pageNo = 1
        getyys()
      }
      
      //初始查询换电站
      let yunList = ref<any>([])
        gethdzlist({
          pageSize:100,	      //每页条数
          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 qswxuser = ref('')


      
      //初始查询字典类型
      // let yxtype = ref<any>([])
      // getdict({
      //   typeCode:'robotyxms'
      // }).then(rps => {
      //   yxtype.value = rps.data
      // })  

      function getyys() {
        yysList.value.splice(0)
        getyylist(queryParams).then(rps => {
            if(rps.data){
              //yysList.value = 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()

        queryParams.swapDayBegin = ''
        queryParams.swapDayEnd = ''	 

        wxuser.value = ''
      }

      
      //新增、修改
      let type = ref(1)
      let openpop = ref(false)
      let ystit = ref('添加预约')
      let yysRef = ref()
      let slecas = ref('')
      let wxuser = ref('')
      let addata = reactive({
        source:'2',				      //来源：1-小程序，2-云端，3-站端
        userId:'',	                  //预约人ID
        ucode:'',                    //预约人编码
        uname:'',	                    //预约人姓名
        phone:'',	                    //手机号码
        plateNum:'',	                //车牌号
        stationCode:'',	              //换电站编码
        stationName:'',	              //换电站名称
        swapDay:'',	                  //预约换电日期,示例值(yyyyMMdd)
        swapDuration:'',	            //预约换电时间段,示例值(8:00-10:00)
        //status:'1'	                   //状态：1-预约成功，2-到店使用，3-取消，4-过期

        // source:'2',				      //来源：1-小程序，2-云端，3-站端
        // ucode:'',				        //预约人编码
        // uname:'',				        //预约人姓名
        // phone:'',				        //手机号码	
        // plateNum:'',			      //车牌号
        // stationCode:'',		      //换电站编码
        // stationName:'',		      //换电站名称
        // swapDay:'',				      //预约换电日期,示例值(yyyyMMdd)
        // //reservationTime:''		//预约时间	
        // swapDuration:''		//预约换电时间段,示例值(8:00-10:00)
      })
      const rules = ref({
        userId:[
          { required: true, message: "请选择预约人", trigger: "blur" }
        ],
        swapDay:[
          { required: true, message: "请选择换电日期", trigger: "blur" }
        ],
        stationCode:[
          { required: true, message: "请选择换电站", trigger: "blur" }
        ],
        // swapDuration:[
        //   { required: true, message: "请选择换电时间段", trigger: "blur" }
        // ],
        plateNum:[
          { required: true, message: "请输入车牌号", trigger: "blur" },
          { validator:carNum, trigger: "blur"}
        ]
      })

      //获取微信用户
      async function querySearchAsync (queryString: string, cb:any) {
        getwxlist({
          pageSize:100,	               //每页条数
          pageNo:1,	                     //页数
          phoneNumber:queryString,       //手机号
          // nickName:queryString,          //昵称
          // name:queryString               //名称
        }).then((res) => {
            if (res.data && (res.data as any).records.length > 0) {
                // mapList.value = res.data;
                let listss = (res.data as any).records.map((n:any) => {
                    return {
                        value: `${n.name?n.name:'暂未设置姓名'}—${n.phoneNumber?n.phoneNumber:'暂未绑定手机号'}`,
                        name: n.name,
                        phoneNumber:n.phoneNumber,
                        id:n.wuid //??
                    }
                })
                cb(listss)
                //return listss
                // callback(mapList.value);
            }else{
                cb([])
            }
            }).catch(() => {
                cb([])
            })
        }
   

        function autoblur() {
          if(addata.userId === ''){
            wxuser.value = ''
            addata.plateNum = ''
            carlist.value.splice(0)
          }
        }

        function autoclear() {
          addata.userId = ''
          addata.plateNum = ''
          carlist.value.splice(0)
        }

        function handleSelect(v: any) {
          addata.userId = v.id
          addata.ucode = v.id
          addata.uname = v.name	                        //预约用户名称
          addata.phone = v.phoneNumber                  //预约用户手机
          getcar(v.id)
        }
      

        function qsautoblur() {
          if(queryParams.ucode === ''){
            qswxuser.value = ''
          }
        }

        function qsautoclear() {
          queryParams.ucode = ''
        }

        function qshandleSelect(v: any) {
          queryParams.ucode = v.id
        }
      //获取换电站名称
      function getlabel(n:string){
        addata.stationName = n
      }

      function showpop(num:any){
        type.value = num
        openpop.value = true
        ystit.value = '添加预约'
        yysRef.value?.resetFields()
        wxuser.value = ''
      }

      //保存
      function handleAdd() {
        
        yysRef.value?.validate((valid:Boolean) => {
            if (valid) {
              addhdz(addata).then(() => {
                ElMessage({
                    type: 'success',
                    message: '预约成功'
                })
                setTimeout(()=> {
                    openpop.value = false
                    getyys()
                },600)
            })
            }
        })
      }

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

      //删除
    function handleDelete(row:any) {
      ElMessageBox.confirm(
        `确定取消预约`,
        '温馨提示',
        {
            // confirmButtonText: '',
            // cancelButtonText: 'Cancel',
            type: 'warning',
        }
      ).then(() => {
        delhdz(row.pkId).then(() => {
            ElMessage({
                type: 'success',
                message: '取消成功'
            })
            getyys()
          })
      })
    }

    //根据用户id查询车辆
    let carlist = ref<any>([])
    function getcar(ownerId:string) {
      carlist.value.splice(0)
        getjqrlist({
          pageSize:100,	      //每页条数
          pageNo:1,	          //页数
          ownerId	            //车主ID
        }).then(rps => {
            if(rps.data){
              carlist.value = (rps.data as any).records
            }
        })
      }

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