/**
 * 模板名称:电商用户管理
 * 作者:zhangyy
 * 时间:2023-10-07
 */

<template>
  <div class="ecommerceList">
    <!-- 按订单号搜索 -->
    <Row :gutter="10">
       <Col span="19">
          <Form :label-width="80" :model="searchFilter">
                <transition name="el-zoom-in-center">
                  <Row>
                    <Col span="6">
                      <FormItem label="用户名">
                        <Input placeholder="请输入用户名" v-model="searchFilter.userName"/>
                      </FormItem>
                    </Col>
                    <!-- 按状态 -->
                    <Col span="5">
                      <FormItem label="昵称">
                        <Input placeholder="请输入昵称" v-model="searchFilter.nickName"/>
                      </FormItem>
                    </Col>
                    <!-- 按成交时间 -->
                    <Col span="12" >
                      <FormItem label="注册时间">
                          <Row>
                              <Col span="11">
                                <DatePicker type="date" placeholder="选择日期"
                                format="yyyy-MM-dd"
                                v-model="searchFilter.startDate"
                                @on-change="changeStartTime"/>
                              </Col>
                              <Col span="2" style="text-align: center">-</Col>
                              <Col span="11">
                                <DatePicker type="date" placeholder="截止日期"
                                format="yyyy-MM-dd"
                                v-model="searchFilter.endDate"
                                @on-change="changeEndTime"
                                />
                              </Col>
                          </Row>
                      </FormItem>
                    </Col>
                  </Row>
                </transition>
              </Form>
       </Col>
        <Col span="2">
         <Button type="primary" icon="ios-search" @click="initData">搜索</Button>
       </Col>
       <Col span="2">
         <Button type="error" @click="frozenUser('MULTI')">冻结所选</Button>
       </Col>
    </Row>
    <br />
    <!-- 数据展示 -->
    <el-table class="el-table" ref="usersListTable" :data="usersList" v-loading="dataLoading">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="头像" width="150">
        <template #default="scope">
          <span class="imgStyle">
            <img v-if="scope.row.headImg" :src="scope.row.headImg" alt="">
            <img v-else src="../../../assets/images/default.png" alt="">
          </span>
        </template>
      </el-table-column>
      
      <el-table-column label="用户名" width="150">
        <template #default="scope">
            {{scope.row.userName || '无'}}
        </template>
      </el-table-column>
      <el-table-column label="昵称" width="150">
        <template #default="scope">
            {{scope.row.nickName || '无'}}
        </template>
      </el-table-column>
      <el-table-column label="组织编号" width="150">
        <template #default="scope">
            {{scope.row.orgId || '无'}}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="150">
        <template #default="scope">
            {{scope.row.contactCell || '无'}}
        </template>
      </el-table-column>
      <el-table-column label="注册时间" width="100">
        <template #default="scope">
          <span>
            {{formatData(scope.row.addTime)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <span>
            <Button type="success" size="small"  @click="checkUsersDetail(scope.row)" style="margin-right: 5px;">详情</Button>
            <Button v-show="scope.row.status==0" type="error" size="small" @click="frozenUser(scope.row.id)" style="margin-right: 5px;">冻结账号</Button>
            <Button v-show="scope.row.status==1" type="warning" size="small" @click="thawUser(scope.row.id)" style="margin-right: 5px;">解冻账号</Button>
            <Button type="primary" size="small"  @click="updatePsd(scope.row.id)" style="margin-right: 5px;">修改密码</Button>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div style="margin: 10px;overflow: hidden">
      <div style="float: right;">
        <Page show-elevator :total="parseInt(totalNum)" :page-size="searchFilter.limit"  @on-change="changePage"></Page>
      </div>
    </div>
    <!-- 用户详情弹出层 -->
    <Modal v-model="checkUsersDetailModel" title="用户详情" @on-ok="checkUsersDetailModel=false">
      <Form ref="checkUsersDetailRef" :model="usersDetail" :label-width="80" >
        <FormItem label="用户名:" prop="userName">
          <span>{{usersDetail.userName}}</span>
        </FormItem>
        <FormItem label="用户头像:" prop="headImg">
          <span class="imgStyle">
            <img v-if="usersDetail.headImg"  :src="usersDetail.headImg" alt="">
            <img v-else src="../../../assets/images/default.png" alt="">
          </span>
        </FormItem>
        <FormItem label="用户昵称:" prop="nickName">
          <span>{{usersDetail.nickName || '无'}}</span>
        </FormItem>
        <FormItem label="联系电话:" prop="contactCell">
          <span>{{usersDetail.contactCell || '无'}}</span>
        </FormItem>
        <FormItem label="注册时间:" prop="addTime">
          <span>{{formatData(usersDetail.addTime)|| '无'}}</span>
        </FormItem>
      </Form>
    </Modal>
    <!-- 修改密码 -->
    <Modal v-model="updatePsdModel" title="修改密码" ok-text="提交修改" @on-ok="submit()">
      <Form ref="changePasswordRef" :label-width="100" :model="changePassword" :rules="psdRules">
        <FormItem label="新密码" prop="newPwd">
          <Input type="password" v-model="changePassword.newPwd" placeholder="请输入新密码"/>
        </FormItem>
        <FormItem label="确认密码" prop="confirmPwd">
          <Input type="password" v-model="changePassword.confirmPwd" placeholder="请重复输入新密码"/>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref ,reactive,getCurrentInstance} from 'vue'
import { Message,Modal } from 'view-ui-plus'
import { user } from '@/request/api'
import moment from 'moment'

export default defineComponent({
  components:{
    
  },
  setup() {
    const confirmPwdCheck = (rule, value, callback)=>{
      if (value != changePassword.value.newPwd) {
        callback(new Error('两次输入密码不一致'))
      }else{
        callback()
      }
    }
    let dataLoading = ref(false) //是否在加载中
    let usersList = ref([])
    let totalNum = ref(0)
    let imgDefault = '../../../assets/images/default.png'
    let updatePsdModel = ref(false)
    let checkUsersDetailModel = ref(false)
    let searchFilter = reactive({
      orgId:'',    //订单状态
      userName:'',        //用户名
      startDate: '',      //订单开始日期(yyyy-MM-dd)
      endDate: '',        //订单结束日期(yyyy-MM-dd)
      offset: 0,
      limit:10,
      nickName:''
    })
    let usersDetail = ref({})
    let changePassword = ref({
      id:'',
      newPwd: '',    //新密码
      confirmPwd:'',      //确认密码
    })
    let changePasswordRef = ref()
    let psdRules = {                //验证规则
      newPwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { type: 'string', min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
      ],
      confirmPwd:[
        { required: true, message: '请重复输入新密码', trigger: 'blur' },
        { type: 'string', min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
        { validator: confirmPwdCheck, trigger: 'blur' },
      ]
    }
    const usersListTable = ref()

    // 格式化日期
    function formatData(date) {
      return moment(date).format("YYYY-MM-DD");
    }

    async function initData() {
      dataLoading.value = true
      getUsersList()
      dataLoading.value = false
    }

    async function getUsersList() {
      await user.GetUsersList({...searchFilter
      }).then(res => {
        if (res.code == '101') {
            usersList.value = res.data || []
            totalNum.value = res.total || 0
        } else {
            Message.error(res.message || "获取平台用户信息出错")
        }
      })
    }

    //更改页码
    function changePage(page) {
      searchFilter.offset = (page - 1) * searchFilter.limit
      getUsersList()
    }

    //更改开始时间
    function changeStartTime(time){
      searchFilter.startDate = time
      // this.getData()
    }

    //更改截止时间
    function changeEndTime(time){
      searchFilter.endDate = time
      // this.getData()
    }

    /*=====搜索=====*/
    function searchItem() {
      getUsersList()
    }
    function checkUsersDetail(item) {
      usersDetail.value = item
      checkUsersDetailModel.value = true
    }

    async function frozenUser(...args) {
      let params

      if (args[0] == "MULTI") {
        var selection = usersListTable.value.store.states.selection._rawValue,
          ids = selection.map(val => val.id).join(',')
          params = {ids: ids}
      }else {
        params = {ids: args[0]}
      }

      await user.FrozenUser(params).then(res => {
          if (res.code == '101') {
            Message.success(res.message || "冻结成功")
            getUsersList()
          } else {
            Message.error(res.message || "冻结失败")
          }
      })
    }

    async function thawUser(id) {
      await user.ThawUser({
        id:id
      }).then(res => {
          if (res.code == '101') {
            Message.success(res.message || "解冻成功")
            getUsersList()
          } else {
            Message.error(res.message || "解冻失败")
          }
      })
    }

    function updatePsd(id) {
      changePassword.value.id = id
      updatePsdModel.value = true
    }

    function submit (name) {
      changePasswordRef.value.validate(async (valid) => {
        if(valid){     //验证通过
          await user.UpdatePassWord({
            id:changePassword.value.id,
            newPwd: changePassword.value.newPwd,
            confirmPwd: changePassword.value.confirmPwd
          }).then((res)=>{
            if(res.code == '101'){
              Message.success("密码修改成功")
              changePasswordRef.value.resetFields()//将数据置空(清除callback函数影响)
              updatePsdModel.value = false
              changePassword.value.newPwd = ''
              changePassword.value.confirmPwd = ''
            }else{
              Message.error(res.message)
            }
          }).catch((err) => {
            Message.error(err)
          })
        } else {   //验证失败
            Message.error('提交失败!');
        }
      })
    }

    onMounted(()=>{
      initData()
    })

    return {
      dataLoading,usersList,totalNum,updatePsdModel,checkUsersDetailModel,searchFilter,usersDetail,changePassword,psdRules,
      usersListTable,changePasswordRef,imgDefault,
      getUsersList,changePage,changeStartTime,changeEndTime,searchItem,checkUsersDetail,frozenUser,thawUser,updatePsd,submit,formatData,initData
    }
  },
})
</script>

<style lang="scss" scoped>
.ecommerceList{
  padding: 1em;
  .el-table{
    width: 100%;
    font-size: 12px;
  }
  .imgStyle {
    width: 100px;
    height: 100px;
    display: table;
    overflow: hidden;
    img {
      vertical-align: middle;
      max-width: 100px;
      max-height: 100px;
    }
  }
}
</style>