<template>
  <div>
    <div class="app-container" style="margin-bottom: 20px;padding-bottom: 8px;border-radius: 10px;">
      <el-form
        ref="querform" 
        :model="queryParams" 
        :inline="true" 
        label-width="68px"
      >
          <el-form-item label="账号" prop="uname">
            <el-input v-model="queryParams.uname" placeholder="请输入账号" clearable style="width: 240px" />
          </el-form-item>
          <!-- <el-form-item label="关联方代码">
            <el-input v-model="queryParams.typeRelateCode" placeholder="请输入关联方代码" clearable style="width: 240px" />
          </el-form-item> -->
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable style="width: 240px" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 240px" />
          </el-form-item>
          <!-- <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable style="width: 240px">
              <el-option :key="1" label="启用" :value="1" />
              <el-option :key="2" label="禁用" :value="2" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </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: 20px;padding-bottom: 8px;border-radius: 10px;">
      <el-button 
        type="primary" 
        plain 
        icon="Plus" 
        @click="showpop(1)">新增</el-button>
      <el-table 
        style="margin-top: 10px;"
        :data="userList"
        border
        stripe
        highlight-current-row
      >
          <el-table-column label="账号" align="center" prop="uname" :show-overflow-tooltip="true">
            <template #default="scope">
                <div v-if="scope.row.readonly != 1" @click="showpop(2,scope.row)" style="display: inline-block;color:#16599d;border-bottom: 1px solid #417ebb;cursor:pointer">{{scope.row.uname}}</div>
                <div v-else>{{scope.row.uname}}</div>
              </template>
          </el-table-column>
          <el-table-column label="账号类型" align="center" prop="type">
            <template #default="scope">
              <div v-if="scope.row.type == 1">开发者</div>
              <div v-else-if="scope.row.type == 2">运营方</div>
              <div v-else="scope.row.type == 3">企业用户</div>
            </template>
          </el-table-column>
          <el-table-column label="所属运营商或企业用户" align="center" width="240" prop="businessName" :show-overflow-tooltip="true" />
          <el-table-column label="关联方代码" align="center" width="140" prop="typeRelateCode" :show-overflow-tooltip="true" />
          <el-table-column label="姓名" align="center" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="手机号" align="center" width="120" prop="phone" :show-overflow-tooltip="true" />
          <el-table-column label="邮箱" align="center" width="200" prop="email" :show-overflow-tooltip="true" />
          
          <!-- <el-table-column label="所属企业用户" align="center" width="200" prop="typeRelateCode" :show-overflow-tooltip="true" /> -->
          <!-- <el-table-column label="性别" align="center" prop="sex">
            <template #default="scope">
              <div v-if="scope.row.sex == 1">男</div>
              <div v-else="scope.row.sex == 2">女</div>
            </template>
          </el-table-column> -->
          
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <div v-if="scope.row.status == 1">启用</div>
              <div v-else style="color: #ccc;">禁用</div>
            </template>
          </el-table-column>
          <!-- <el-table-column v-if="columns[6].visible" label="创建时间" align="center" prop="createTime" width="160">
            <template #default="scope">
              <span>{{ dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" align="left" width="260">
            <template #default="scope">
              <!-- <el-button link v-if="scope.row.readonly != 1" type="primary" icon="Edit" @click="showpop(2,scope.row)">修改</el-button> -->
              <el-button link v-if="scope.row.readonly != 1" type="primary" icon="CircleCheck" @click="handleAuthRole(scope.row)">分配角色</el-button>
              <el-button link v-if="scope.row.readonly != 1 && scope.row.type == 2" type="primary" icon="Monitor" @click="feiphdz(scope.row)">分配站</el-button>
              <el-button link v-if="scope.row.readonly != 1" 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="handleQuery"
        />
      </div>
    </div>

  
    <!-- 添加或修改用户配置对话框 -->
      <el-dialog 
        v-model="openpop" 
        :title="usertit" 
        width="500px" 
        append-to-body
        :close-on-click-modal="false"
      >
      <el-form ref="userRef" :model="userform" :rules="rules" label-width="100px">
        <el-row>
          
          <el-col :span="24">
            <el-form-item v-if="userType == 1" label="账号类型" prop="type">
              <el-radio-group v-model="userform.type">
                <el-radio value="1">开发者</el-radio>
                <el-radio value="2">运营商</el-radio>
                <el-radio value="3">企业用户</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <!-- <el-form-item label="" prop="status">
                <el-select v-model="userform.type" placeholder="请选择运营商" style="width: 160px;">
                    <el-option value="1" label="正常营业" />
                    <el-option value="2" label="正常停运" />
                    <el-option value="3" label="故障停运" />
                    <el-option value="4" label="指令停运" />
                    <el-option value="9" label="其他" />
                </el-select>
            </el-form-item> -->
          </el-col>
          <el-col v-if="userform.type == '2'" :span="24">
            <el-form-item label="运营商" prop="businessCode">

              <el-select v-model="userform.businessCode" placeholder="请选择运营商">
                <el-option v-for="n in yunList" :label="n.label" :value="n.value" />
              </el-select>
                
            </el-form-item>
          </el-col>
          <el-col v-if="userform.type == '3'" :span="24">
            
            <el-form-item  label="企业用户" prop="businessCode1">
              <el-select v-model="userform.businessCode1" placeholder="请选择企业用户">
                <el-option v-for="n in qyuserList" :label="n.cname" :value="n.ccode" />
              </el-select>
                
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="账号" prop="uname">
              <el-input v-model="userform.uname" placeholder="请输入账号" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户密码" prop="password">
              <el-input 
                v-model="userform.password" 
                placeholder="请输入用户密码" 
                type="password" 
                maxlength="20" 
                show-password 
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="userform.status">
                <el-radio value="1">启用</el-radio>
                <el-radio value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="关联方代码" prop="typeRelateCode">
              <el-input v-model="userform.typeRelateCode" placeholder="请输入关联方代码" maxlength="30" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userform.name" placeholder="请输入姓名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userform.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="userform.sex">
                <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="readonly">
              <el-radio-group v-model="userform.readonly">
                <el-radio value="1">是</el-radio>
                <el-radio value="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="userType == 1">
            <el-form-item label="关联微信用户" prop="wxuser">
              <el-autocomplete
                  style="width: 100%"
                  v-model="wxuser"
                  :fetch-suggestions="querySearchAsync"
                  placeholder="请输入手机号查询"
                  clearable
                  @blur="autoblur"
                  @select="handleSelect"
                  @clear="autoclear"
                />
            </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="drawer"
      title="分配角色"
      size="800"  
      :before-close="handleClose"
    >
      <div style="margin-bottom:20px;padding-bottom:15px;border-bottom:1px solid #b8d7f7;color:#409eff;font-size:16px;">基本信息</div>
      <div style="padding-bottom:30px">
        <el-form
        :inline="true" 
        label-width="68px"
      >
          <el-form-item label="账号">
            <el-input v-model="userInfor.uname"  disabled style="width: 240px" />
          </el-form-item>
          <el-form-item label="账号类型">
            <el-input v-model="userInfor.type"  disabled style="width: 240px" />
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-bottom:20px;padding-bottom:15px;border-bottom:1px solid #b8d7f7;color:#409eff;font-size:16px;">角色列表</div>
      <el-button 
        type="primary" 
        icon="Plus" 
        plain
        @click="fenpeirole">分配角色</el-button>
      <el-table
        ref="taskTableRef"
        style="margin-top: 20px;"
        :data="rolelist"
        border
        stripe
        @select="selectClick"
        :header-cell-class-name="cellClass"
      >
      <el-table-column type="selection" width="55" />
        <el-table-column label="角色名称" align="center" prop="name" />
        <el-table-column label="角色编码" align="center" prop="rcode" />
        <el-table-column label="角色类型" align="center" prop="type" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <div v-if="scope.row.status == 1">启用</div>
            <div v-else>禁用</div>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  
    <!--分配换电站-->

    <fphdz 
     v-if="hdzpop" 
     :show="hdzpop"
     :uid="uid" 
     :code="hdzcode"
     @update="handhdx"
     @cancel="hdzpop = false"
    />
  </div>
</template>
<script setup lang="ts">
    import { 
      getuser,
      adduser,
      updateuser,
      deleteuser,
      adduserrole
    } from '@/api/systemSet/user'

    import { getjslist } from '@/api/systemSet/role'
    import { 
        optionyyslist
      } from '@/api/systemSet/operator'
      import { 
        getlist
      } from '@/api/operation/company'

      import Fphdz from './fphdz.vue'

      import { 
        getwxlist
      } from '@/api/operation/wxuser'  

    import { ref,reactive,nextTick } from 'vue'
    import { ElMessage, ElMessageBox } from 'element-plus'

    //用户类型
     let Info:any = localStorage.getItem('Infor')
     let userType = ref<any>('') 
     let roles = ''
     if(Info){
      Info = JSON.parse(Info)
      userType.value = (Info as any).type
      if((Info as any).roles && (Info as any).roles.length > 0){
        roles = (Info as any).roles[0].rcode
      }
      
     }
     
     
     let yunList = ref<any>([])
     let qyuserList = ref<any>([])
     if(userType.value == 1){
          //初始查询运营商
          optionyyslist().then(rps => {
                if(rps.data){
                   // let list = (rps.data as any).records
                    yunList.value = rps.data
                }
          })

          
          //初始获取企业用户
          getlist({
            pageSize:200,
            pageNo:1
          }).then(rps => {
                if(rps.data){
                  let list = (rps.data as any).records
                  qyuserList.value = list?list:[]
                }
            })
     }

   

     

    //查询用户
    let queryParams = reactive({
      uid:'',
      pageSize:20,	      //每页条数
      pageNo:1,	          //页数
      uname:'',	          //账号
      typeRelateCode:'',	//关联方代码
      name:'',            //姓名
      phone:''	          //手机
    })
    let total = ref(0)
    let userList = ref([])
    //查询
    function handBtnqu() {
      queryParams.pageNo = 1
      handleQuery()
    }

    function handleQuery() {
      getuser(queryParams).then(rps => {
        if(rps.data){
          total.value = (rps.data as any).total
          let list = (rps.data as any).records
          userList.value = list?list:[]
        }
      })
    }
    handleQuery()

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

    //重置
    let querform = ref()
    function resetQuery() {
      querform.value?.resetFields()
    }


    
    //新增（修改）用户
    let cztype = ref(1)
    let openpop = ref(false)
    let userRef = ref()
    let usertit = ref('添加用户')
    let userform = reactive<any>({
      pkId:'',
      uname:'',	          //账号
      type:'',	          //账号类型：1-开发者，2-运营方，3-客户
      password:'',	      // 密码
      status:'1',          //状态：1-启用，0-禁用
      uid:'',	            //用户ID（修改时用）
      typeRelateCode:'',	//关联方代码
      name:'',	          //姓名
      email:'',	          //邮箱
      phone:'',	          //手机号码
      //sex:'',	            //性别
      readonly:'2',	        //是否内置账号，内置账号不允许动
      avatar:'',	          //头像
      businessCode:'',      //运营商code  企业用户code
      businessCode1:'',      //运营商code  企业用户code
      wuid:''
    })

    const rules = ref({
        uname: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "账号长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        type:[
          { required: true, message: "请选择账号类型", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        businessCode:[
        { required: true, message: "请选择运营商", trigger: "blur" },
        ],
        businessCode1:[
        { required: true, message: "请选择企业用户", trigger: "blur" },
        ],
        status:[
        { required: true, message: "请选择状态", trigger: "blur" },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          }
        ]
    })

    function showpop(type:number,row?:any) {
      cztype.value = type
      openpop.value = true
      usertit.value = type == 1?'添加用户':'修改用户'
      userRef.value?.resetFields()    
      if(row){
        userform.pkId = row.pkId
        userform.uid = row.uid	
        userform.uname = row.uname	                 
        userform.type = row.type+''	                    
        //userform.password = row.password	      //??      
        userform.status = row.status+''                    
        userform.typeRelateCode = row.typeRelateCode	
        userform.name = row.name	                    
        userform.email = row.email	                  
        userform.phone = row.phone	                  
        //userform.sex = row.sex+''	                      
        userform.readonly = row.readonly?row.readonly+'':'2'	            
        if(userform.type == 1){
          userform.businessCode = ''
        }else if(userform.type == 2){
          userform.businessCode = row.businessCode
        }else if(userform.type == 3){
          userform.businessCode1 = row.businessCode
        }

        //userform.avatar = row.avatar	      
        userform.wuid = row.wuid?row.wuid:''   
        wxuser.value =  row.wuid?row.wuid:''
      }else{
        userform.pkId = ''
        userform.uid = ''
        userform.uname = ''	                 
        userform.type = ''	                    
        userform.password = ''      
        userform.status = '1'                 	                      
        userform.typeRelateCode = ''	
        userform.name = ''	                    
        userform.email = ''	                  
        userform.phone = ''	                  
        //userform.sex = ''	                      
        userform.readonly = '2'	            
        //userform.avatar = ''	    
        userform.businessCode = ''
        userform.businessCode1 = ''

        userform.wuid = ''
        wxuser.value = ''
      }
    }

    function caozuohand() {
      if(userform.type == 3){
        userform.businessCode = userform.businessCode1
      }
      if(cztype.value == 1){
         return adduser(userform)
      }
      return updateuser(userform)
    }

    //新增、修改
    function handleAdd() {
      userRef.value?.validate((valid:Boolean) => {
        if (valid) {
          caozuohand().then(() => {
            ElMessage({
              type: 'success',
              message: cztype.value == 1?'添加成功':'修改成功'
            })
            setTimeout(()=> {
              openpop.value = false
              resetQuery()
              handBtnqu()
            },600)
          })
        }
      })
    }

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

    //删除
     function handleDelete(row:any) {
      ElMessageBox.confirm(
      `确定删除用户：${row.uname}`,
      '温馨提示',
      {
        // confirmButtonText: '',
        // cancelButtonText: 'Cancel',
        type: 'warning',
      }
    ).then(() => {
        deleteuser({uid:row.pkId}).then(rps => {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
          handleQuery()
        })
      })
     }

     //分配角色
    let drawer = ref(false)
    let userInfor = ref({
      uname:'',
      type:'',
      uid:''
    })
    let rolelist = ref<any>([])
    let rolesave = ref<any[]>([])
    //查询
    function handleAuthRole(row:any) {
      drawer.value = true
      userInfor.value.uid = row.uid
      userInfor.value.uname = row.uname

      if(row.type == 1){
        userInfor.value.type = '开发者'
      }else if(row.type == 2){
        userInfor.value.type = '运营方'
      }else{
        userInfor.value.type = '企业用户'
      }
      getjslist('').then(rps => {
        rolelist.value = rps.data
        // 默认选中的ID数组
        nextTick(() => {
          const rows = rolelist.value.find((item:any) => item.rcode == row.rcodes)
          if (rows) {
            taskTableRef.value?.toggleRowSelection(rows, true)
            rolesave.value.push({rcode:row.rcodes})
          }
        })
        

      })
    }
    
    // function handleSelectionChange(val:any) {
    //   rolesave.value = val
    // }

    function handleClose() {
      drawer.value = false
    }

     //保存
    function fenpeirole() {
      //角色是否可多选??
      if(rolesave.value.length > 0){
        adduserrole({
          uid:userInfor.value.uid,            //用户id
          rcode:rolesave.value[0].rcode      //角色编码
          //pkId:rolesave.value[0].pkId         
        }).then(() => {
          ElMessage({
            type: 'success',
            message: '分配成功'
          })
          handleQuery()
        })
      }else{
        ElMessage({
          type: 'warning',
          message: '请选择角色'
        })
      }
    } 

    

    //设置单选
    const taskTableRef = ref()
    const selectClick = (selection: any, row: any) => {
        if(selection.length > 1) {
            let del_row = selection.shift();
            taskTableRef.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）；第二个参数为true时又变成了多选
        }
        rolesave.value = selection

    }

    function cellClass(row: any) {
      // 隐藏多选框一列的表头即全选框
      if (row.columnIndex === 0) {
        return 'disabledCheck'
      }
    }
    

    //分配换电站
    let hdzpop = ref(false)
    let uid = ref('') 
    let hdzcode = ref('')
    function feiphdz(row:any){
      hdzpop.value = true
      uid.value = row.uid
      hdzcode.value = row.stationCodes
    }

    //关联微信用户
    let wxuser = ref('')

    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(userform.userId === ''){
            wxuser.value = ''
          }
        }

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

        function handleSelect(v: any) {
          userform.wuid = v.id
        }

    function handhdx() {
      hdzpop.value = false
      handleQuery()
    }
</script>
<style>
/* 隐藏全选按钮 */
.el-table .disabledCheck .cell .el-checkbox__inner {
    display: none;
  }
  .el-divider--horizontal{
    border-color:#5b98cd;
  }
.el-divider--horizontal{
  border-color:#5b98cd;
}
</style>