<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="ownerType">
                <el-select v-model="queryParams.ownerType" placeholder="请选择类型" style="width: 200px;">
                    <el-option label="个人" value="1" />
                    <el-option label="企业" value="2" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="户主名称" prop="accName">
              <el-input 
                v-model="queryParams.accName" 
                placeholder="请输入户主名称" 
                maxlength="20" 
                clearable
                style="width: 200px;"
              />
            </el-form-item>
            <!-- <el-form-item label="联系电话" prop="phone">
              <el-input 
                v-model="queryParams.phone" 
                placeholder="请输入联系电话" 
                maxlength="50" 
              />
            </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>
              <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?'600px':'700px'"
        >
            <el-table-column label="户主名称" min-width="100" align="center" prop="accName" :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.accName?scope.row.accName:'暂未设置'}}</div>
              </template>
            </el-table-column>
            <el-table-column label="联系电话" min-width="120" align="center" prop="phone" :show-overflow-tooltip="true" />
            <el-table-column label="户主类型" min-width="100" align="center" prop="ownerType" :show-overflow-tooltip="true">
              <template #default="scope">
                <div v-if="scope.row.ownerType == 1">个人</div>
                <div v-else>企业</div>
              </template>
            </el-table-column>
            <el-table-column label="账户编码" min-width="300" align="center" prop="code" :show-overflow-tooltip="true" />
            
            <el-table-column label="引入站点" min-width="220" align="center" prop="stationName" :show-overflow-tooltip="true" />
            <el-table-column label="账户总金额(元)" min-width="120" align="left" prop="totalAmount" :show-overflow-tooltip="true">
              <template #default="scope">
                <div>{{scope.row.totalAmount/100}}</div>
              </template>
            </el-table-column>
            <el-table-column label="充值余额(元)" min-width="120" align="left" prop="rechargeAmount" :show-overflow-tooltip="true">
              <template #default="scope">
                <div>{{scope.row.rechargeAmount/100}}</div>
              </template>
            </el-table-column>
              
            <el-table-column label="赠送金额(元)" min-width="120" align="left" prop="giftAmount" :show-overflow-tooltip="true">
              <template #default="scope">
                <div>{{scope.row.giftAmount/100}}</div>
              </template>
            </el-table-column>

            <el-table-column label="积分金额(元)" min-width="120" align="left" prop="point" :show-overflow-tooltip="true">
              <template #default="scope">
                <div>{{scope.row.point/100}}</div>
              </template>
            </el-table-column>
            <el-table-column label="押金(元)" min-width="80" align="left" prop="deposit" :show-overflow-tooltip="true">
              <template #default="scope">
                <div>{{scope.row.deposit/100}}</div>
              </template>
            </el-table-column>
            <el-table-column label="SN码" min-width="150" align="center" prop="snCode" :show-overflow-tooltip="true" />
            <el-table-column label="租金(元)" min-width="80" align="left" prop="rent" :show-overflow-tooltip="true">
              <template #default="scope">
                <div>{{scope.row.rent/100}}</div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="操作" align="center" width="100" fixed="right">
              <template #default="scope">
                <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="500px" 
          append-to-body
          :close-on-click-modal="false"
        >
        <div style="padding: 20px;">
          <el-form 
            ref="yysRef" 
            :model="addata" 
            :rules="rules" 
            label-width="120px">
              <el-row :gutter="30">
                <el-col :span="24">
                  <el-form-item label="户主类型" prop="ownerType">
                      <el-select 
                        @change="changetype"
                        v-model="addata.ownerType" 
                        placeholder="请选择类型"
                      >
                          <el-option 
                            label="企业" 
                            value="2"
                          />
                          <el-option 
                            label="个人" 
                            value="1"
                          />
                          
                      </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="户主名称" prop="ownerId">
                      <el-autocomplete
                        style="width: 100%"
                        v-model="qswxuser"
                        :fetch-suggestions="querySearchAsync"
                        :placeholder="addata.ownerType == '1'?'请输入手机号查询':'请输入企业名称查询'"
                        clearable
                        @blur="qsautoblur"
                        @select="qshandleSelect"
                        @clear="qsautoclear"
                      />
                  </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="totalAmount">
                    <el-input 
                      v-model="addata.totalAmount" 
                      placeholder="请输入总金额" 
                      maxlength="50" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="充值金额(元)" prop="rechargeAmount">
                    <el-input 
                      v-model="addata.rechargeAmount" 
                      placeholder="请输入充值金额" 
                      maxlength="50" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="赠送金额(元)" prop="giftAmount">
                    <el-input 
                      v-model="addata.giftAmount" 
                      placeholder="请输入赠送金额" 
                      maxlength="50" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="积分余额(元)" prop="point">
                    <el-input 
                      v-model="addata.point" 
                      placeholder="请输入积分余额" 
                      maxlength="50" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="押金(元)" prop="deposit">
                    <el-input 
                      v-model="addata.deposit" 
                      placeholder="请输入押金" 
                      maxlength="50" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="SN码" prop="snCode">
                    <el-input 
                      v-model="addata.snCode" 
                      placeholder="请输入SN码" 
                      maxlength="50" 
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="租金(元)" prop="rent">
                    <el-input 
                      v-model="addata.rent" 
                      placeholder="请输入租金" 
                      maxlength="50" 
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
  
        </div>
        
        <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="drawer" 
        :with-header="false"
        size="70%"
      >
        <tit @close="handleClose" name="账户详情" />
        <el-row :gutter="25">
          <el-col :span="24">
            <div style="padding: 0;border: 2px solid #73b9c9;border-radius: 10px;">
              <div class="mktit jqbg">基本信息</div>
              <el-form 
              ref="yysRef" 
              :model="addata" 
              :rules="rules" 
              label-width="120px">
                
                <el-row :gutter="25" style="padding: 20px;">
                  <el-col :span="12">
                    <el-form-item label="户主类型" prop="ownerType">
                        <el-select 
                          disabled
                          v-model="addata.ownerType" 
                          placeholder="请选择类型"
                        >
                            <el-option 
                              label="个人" 
                              value="1"
                            />
                            <el-option 
                              label="企业" 
                              value="2"
                            />
                        </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="户主名称" prop="accName">
                      <el-input 
                        v-model="addata.accName" 
                        placeholder="请输入户主名称" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <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="12">
                    <el-form-item label="账户总金额(元)" prop="totalAmount">
                      <el-input 
                        disabled
                        v-model="addata.totalAmount" 
                        placeholder="" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="充值金额(元)" prop="rechargeAmount">
                      <el-input
                       disabled 
                        v-model="addata.rechargeAmount" 
                        placeholder="" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="赠送金额(元)" prop="giftAmount">
                      <el-input 
                       disabled
                        v-model="addata.giftAmount" 
                        placeholder="" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="积分余额(元)" prop="point">
                      <el-input 
                        disabled
                        v-model="addata.point" 
                        placeholder="" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="押金(元)" prop="deposit">
                      <el-input 
                        disabled
                        v-model="addata.deposit" 
                        placeholder="" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="SN码" prop="snCode">
                      <el-input 
                        v-model="addata.snCode" 
                        placeholder="请输入SN码" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="租金(元)" prop="rent">
                      <el-input 
                        disabled
                        v-model="addata.rent" 
                        placeholder="" 
                        maxlength="50" 
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" style="text-align: center;">
                      <el-button type="success" @click="handleAdd">保 存</el-button>
                      <el-button @click="resetupdate">重 置</el-button>
                    </el-col>
                </el-row>
              </el-form>
            </div>
            
          </el-col>
          <el-col :span="24" style="padding-top: 20px;">
            <div style="height: 100%;margin-bottom: 20px;border: 1px solid #98c3ef; border-radius: 10px;">
              <div class="mktit">余额明细</div>
              <baldetails 
                v-if="drawer" 
                style="padding: 20px 20px 0;"
                :code='code'
              />
            </div> 
          </el-col>
        </el-row>
      </el-drawer>
      
    </div>
  </template>
  <script setup lang="ts" name="UserPage">
      import { ref,reactive,watch } from 'vue'
      import { ElMessage, ElMessageBox } from 'element-plus'
      import Tit from '@/views/components/detailstit.vue'
      import Baldetails from './baldetails.vue'
      import { 
          gethdzlist
      } from '@/api/swapstation/hdz'

      import { 
        getjqrlist, 
        addhdz, 
        update,
        delhdz
      } from '@/api/order/account'
      
      import { 
        getwxlist
      } from '@/api/operation/wxuser'

      import { 
        getlist
      } from '@/api/operation/company'

      import { setNum } from '@/utils/validate'

      function timestamp() {
        return new Date().getTime()
      }

      let search = ref(true)

      let queryParams = reactive({
        pageSize:20,	            //每页条数
        pageNo:1,	                //页数
        ownerType:'',	            //户主类型：1-个人，2-企业
        ownerId:'',	              //户主ID
        code:'',	                //编码
        stationCode:'',	          //引入站点
        accName:'',                //户主名称
        phone:''                  //联系电话
      })
      
      //查询
      let total = ref(0)
      let yysList = ref<any>([])
      function handBtnqu(){
        queryParams.pageNo = 1
        getyys()
      }
      
      //初始查询换电站
      let yunList = ref<any>([])
      gethdzlist({
        pageSize:200,	      //每页条数
        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
          }
      })

      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 standardId = ref('')
      let bzName = ref('')
      let code = ref('')
      let stationName = ref('')
      let addata = reactive<any>({
        pkId:'',
        ownerType:'2',	          //户主类型：1-个人，2-企业
        ownerId:'',	              //户主ID
        accName:'',               //户主名称
        stationCode:'',	          //引入站点
        stationName:'',           //换电站名称  ??
        totalAmount:'',	          //账户总金额，分：总金额=充值金额+赠送金额
        rechargeAmount:'',	      //充值余额，分
        giftAmount:'',	          //赠送金额，分
        point:'',	                //积分余额
        deposit:'',	              //押金
        snCode:'',	              //SN码
        rent:''	                  //租金
      })

      const rules = ref({
        ownerType:[
            { required: true, message: "请选择户主类型", trigger: "blur" }
        ],
        ownerId:[
        { required: true, message: "请选择户主", trigger: "blur" }
        ]
        // stationCode:[
        //   { required: true, message: "请选择站点", trigger: "blur" }
        // ]
      })

      watch(() => addata.totalAmount,v => {
        addata.totalAmount =  setNum(addata.totalAmount)
      })

      watch(() => addata.rechargeAmount,v => {
        addata.rechargeAmount =  setNum(addata.rechargeAmount)
      })

      watch(() => addata.giftAmount,v => {
        addata.giftAmount =  setNum(addata.giftAmount)
      })

      watch(() => addata.point,v => {
        addata.point =  setNum(addata.point)
      })

      watch(() => addata.deposit,v => {
        addata.deposit =  setNum(addata.deposit)
      })

      watch(() => addata.rent,v => {
        addata.rent =  setNum(addata.rent)
      })

      //获取换电站名称
      function getlabel(n:string){
        addata.stationName = n
      }


      let mxlist = ref<any[]>([])
      function showpop(num:any,row?:any){
        type.value = num
        
        if(type.value == 1){
          openpop.value = true
        }else if(type.value == 2){
          drawer.value = true
        }

        ystit.value = num == 1?'添加账户':'修改账户'
        yysRef.value?.resetFields()
        if(row){
          addata.pkId = row.pkId
          
          addata.ownerType = row.ownerType+''	              
          addata.ownerId = row.ownerId
          addata.accName = row.accName	                
          addata.stationCode = row.stationCode	          
          addata.stationName = row.stationName            
          addata.totalAmount = row.totalAmount?row.totalAmount/100:0	          
          addata.rechargeAmount = row.rechargeAmount?row.rechargeAmount/100:0	    
          addata.giftAmount = row.giftAmount?row.giftAmount/100:0	            
          addata.point = row.point?row.point/100:0	                      
          addata.deposit = row.deposit?row.deposit/100:0	                  
          addata.snCode = row.snCode?row.snCode:''	                    
          addata.rent = row.rent?row.rent/100:0	                        

          standardId.value = row.pkId
          bzName.value = row.name
          stationName.value = row.stationName
          code.value = row.code
          mxlist.value = row.detailList
        }else{
          addata.pkId = ''
          addata.ownerType = '2'
          addata.ownerId = ''
          addata.accName = '' 
          addata.stationCode = ''
          addata.stationName = ''
          addata.totalAmount = ''
          addata.rechargeAmount = ''
          addata.giftAmount = ''
          addata.point = ''
          addata.deposit = ''
          addata.snCode = ''
          addata.rent = ''      
          
          qswxuser.value = ''
        }
      }
      function savehand() {
        let objData = Object.assign({},addata,{
          totalAmount:addata.totalAmount*100,
          rechargeAmount:addata.rechargeAmount*100,
          giftAmount:addata.giftAmount*100
        })
        if(type.value == 1){
            return addhdz(objData)
        }
        return update(objData)
        
      }
      //保存
      function handleAdd() {
        yysRef.value?.validate((valid:Boolean) => {
            if (valid) {

              

                savehand().then(() => {
                ElMessage({
                    type: 'success',
                    message: type.value == 1?'添加成功':'修改成功'
                })
                if(type.value == 2){
                  stationName.value = addata.stationName
                }
                setTimeout(()=> {
                    if(type.value == 1){
                      openpop.value = false
                    }else{
                      drawer.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()
          })
      })
    }

    function handleSizeChange(val:number) {
      queryParams.pageSize = val
      getyys()
    }

    //费用标准明细
    let drawer = ref(false)
    //let standardId = ref('')
    function handleClose() {
      drawer.value = false
    }

    function resetupdate() {
      yysRef.value?.resetFields()
    }
    // function bzmingx(id:string) {
    //   drawer.value = true
    //   standardId.value = id
    // }

    let qswxuser = ref('')
    
    function changetype() {
      qswxuser.value = ''
      addata.ownerId = ''
      addata.accName = ''
    }
    //获取微信用户
    function getuser(v:any) {
      if(addata.ownerType == '1'){
        return getwxlist({
          pageSize:100,	               //每页条数
          pageNo:1,	                     //页数
          phoneNumber:v,                //手机号
          // nickName:queryString,          //昵称
          // name:queryString               //名称
        })
      }
      return getlist({
        pageSize:1000,	      //每页条数
        pageNo:1,	            //页数
        cname:v
      })
    }

    async function querySearchAsync (queryString: string, cb:any) {
      getuser(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) => {
                if(addata.ownerType == '1'){
                  return {
                      value: `${n.name?n.name:'暂未设置姓名'}—${n.phoneNumber?n.phoneNumber:'暂未绑定手机号'}`,
                      name: n.name,
                      phoneNumber:n.phoneNumber,
                      id:n.wuid //??
                  }
                }
                return {
                  value: n.cname,
                  name:n.cname,
                  id: n.ccode
                }
                  
              })
              cb(listss)
              //return listss
              // callback(mapList.value);
          }else{
              cb([])
          }
          }).catch(() => {
              cb([])
          })
      }

    function qsautoblur() {
      if(addata.ownerId === ''){
        qswxuser.value = ''
        addata.accName = ''
      }
    }

    function qsautoclear() {
      addata.ownerId = ''
      addata.accName = ''
    }

    function qshandleSelect(v: any) {
      addata.ownerId = v.id
      addata.accName = v.name
    }

    getyys()
  </script>
  <style scoped>
  .el-divider--horizontal{
    border-color:#5b98cd;
  }
  .mktit{
    width: 100%; 
    height: 40px;
    line-height: 40px;
    border-radius: 10px 10px 0 0;
    font-size: 18px;
    font-weight: bold;
    color: #fff;
    text-align: center;
    background: #98c3ef;
  }
  .jqbg{
    background: #73b9c9;
  }
  </style>