<script setup>
import { Search, Plus } from '@element-plus/icons-vue'
import { apiCustomerUser } from '@/api/customer'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox,dayjs } from 'element-plus'
import EnableUser from './components/EnableUser.vue'

const router = useRouter()

const filterState = reactive({
  keyword: '',
  seller: '',
  status: '',
  register: '',
  subscribe: '',
  regsiterTime: [],
  createTime: [],
  sortType:'',
  sortVal:''
})


const tableColOpt = [
  {
    label: '姓名',
    key: 'RealName'
  },
  {
    label: '手机号',
    key: 'Phone'
  },
  {
    label: '邮箱',
    key: 'Email'
  },
  {
    label: '营业部/销售',
    key: 'SellerName'
  },
  {
    label: '用户状态',
    key: 'Status',
    width: '100px'
  },
  {
    label: '有效期',
    key: 'ValidStartTime',
    width: '200px'
  },
  {
    label: '到期时长',
    key: 'RestDate',
    sort: true,
    width: '120px'
  },
  {
    label: '是否注册',
    key: 'IsRegistered',
    width: '100px'
  },
  {
    label: '注册时间',
    key: 'RegisterTime',
    sort: true,
    headerTips: '用户首次登录小程序的时间'
  },
  {
    label: '创建时间',
    key: 'CreateTime',
    sort: true,
    headerTips: '系统中新增该用户的时间'
  },
  {
    label: '是否关注公众号',
    key: 'IsSubscribed'
  },
]
const userList = ref([])
const page = ref(1)
const pageSize = ref(10)
const tableLoading = ref(false)
const totals = ref(0)
async function getUserList() {
  tableLoading.value = true
  const res = await apiCustomerUser.userList({
    PageSize: pageSize.value,
    CurrentIndex: page.value,
    SellerId: filterState.seller ? filterState.seller.join(',') : '',
    Status: filterState.status,
    KeyWord: filterState.keyword,
    IsRegistered: filterState.register,
    IsSubscribed: filterState.subscribe,
    RegisterStartDate: filterState.regsiterTime ? filterState.regsiterTime[0] : '',
    RegisterEndDate: filterState.regsiterTime ? filterState.regsiterTime[1] : '',
    CreateStartDate: filterState.createTime ? filterState.createTime[0] : '',
    CreateEndDate: filterState.createTime ? filterState.createTime[1] : '',
    SortParam:filterState.sortType,
    SortType:filterState.sortVal
  })
  tableLoading.value = false
  if (res.Ret === 200) {
    userList.value = res.Data.List || []
    totals.value = res.Data.Paging.Totals
  }
}
getUserList()
function handlePageChange(e) {
  page.value = e
  getUserList()
}
function handleTableSort(e) {
  // console.log(e);
  const { order, prop } = e//order:"descending",prop: "RegisterTime"
  filterState.sortType=prop
  if(!order){
    filterState.sortVal=''
  }else{
    filterState.sortVal=order==='descending'?'desc':'asc'
  }
  
  handleFilterList()
}
function handleFilterList() {
  page.value = 1
  getUserList()
}





function handleEditUser(e) {
  const link=router.resolve({
    path: '/customer/userEdit',
    query: {
      id: e.UserId
    }
  }).href
  window.open(link,'__blank')
}

// 禁用用户
async function handleDisabledUser(row) {
  const res = await apiCustomerUser.setUserStatus({
    UserId: row.UserId,
    IsEnabled: false
  })
  if (res.Ret !== 200) return
  ElMessage.success('禁用成功')
  getUserList()
}

// 启用用户
const showEnableUserPop = ref(false)
const enableUserId = ref(0)
function handleEnableUser(row) {
  enableUserId.value = row.UserId
  showEnableUserPop.value = true
}

// 删除用户
function handleDelUser(row) {
  ElMessageBox.confirm(
    '该操作会删除该用户所有相关信息，不可恢复，确认删除吗？',
    '提示'
  ).then(() => {
    apiCustomerUser.userDelete({
      UserId: row.UserId
    }).then(res => {
      if (res.Ret === 200) {
        ElMessage.success('删除成功')
        getUserList()
      }

    })
  }).catch(() => { })
}

// 跳转详情
function handleGoDetail(e){
  const link=router.resolve({
    path:'/customer/userDetail',
    query:{
      id:e.UserId
    }
  }).href
  window.open(link,'__blank')
}


</script>

<template>
  <div class="customer-user-list-page">
    <div>
      <el-button
        type="primary"
        :icon="Plus"
        @click="$router.push('/customer/userAdd')"
        v-permission="'user:add'"
        >新增</el-button
      >
      <el-input
        placeholder="姓名/手机号/邮箱"
        v-model="filterState.keyword"
        :prefix-icon="Search"
        clearable
        style="max-width: 359px;float: right"
        @input="handleFilterList"
      />
    </div>
    <div class="flex filter-wrap">
      <all-user-for-depart
        style="width: 165px"
        v-model="filterState.seller"
        :props="{
          emitPath: false,
          multiple: true,
        }"
        clearable
        filterable
        @change="handleFilterList"
      />
      <el-select
        placeholder="用户状态"
        v-model="filterState.status"
        style="width: 165px"
        @change="handleFilterList"
        clearable
      >
        <el-option label="启用" value="正式"></el-option>
        <el-option label="禁用" value="禁用"></el-option>
      </el-select>
      <el-select
        placeholder="注册状态"
        v-model="filterState.register"
        style="width: 165px"
        clearable
        @change="handleFilterList"
      >
        <el-option label="是" value="是"></el-option>
        <el-option label="否" value="否"></el-option>
      </el-select>
      <el-select
        placeholder="是否关注公众号"
        v-model="filterState.subscribe"
        style="width: 165px"
        clearable
        @change="handleFilterList"
      >
        <el-option label="是" value="是"></el-option>
        <el-option label="否" value="否"></el-option>
      </el-select>
      <div style="width: 235px">
        <el-date-picker
          style="width: 235px"
          v-model="filterState.regsiterTime"
          type="daterange"
          range-separator="至"
          start-placeholder="注册时间"
          end-placeholder="注册时间"
          clearable
          value-format="YYYY-MM-DD"
          @change="handleFilterList"
        />
      </div>
      <div style="width: 235px">
        <el-date-picker
          style="width: 235px"
          v-model="filterState.createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="创建时间"
          end-placeholder="创建时间"
          value-format="YYYY-MM-DD"
          clearable
          @change="handleFilterList"
        />
      </div>
      
    </div>
    <div class="userlist-wrap" style="margin-top: 20px">
      <el-table
        :data="userList"
        border
        stripe
        highlight-current-row
        element-loading-text="数据加载中..."
        v-loading="tableLoading"
        @sort-change="handleTableSort"
        @row-click="handleGoDetail"
      >
        <el-table-column
          v-for="column in tableColOpt"
          :key="column.key"
          :prop="column.key"
          :label="column.label"
          :sortable="column.sort ? 'custom' : false"
          :width="column.width"
        >
          <template v-if="column.headerTips" #header>
            <span>{{ column.label }}</span>
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="column.headerTips"
              placement="top"
            >
              <el-icon style="position: relative; top: 2px"
                ><i-ep-QuestionFilled
              /></el-icon>
            </el-tooltip>
          </template>
          <template #default="{ row }">
            <span
              v-if="column.key === 'Status'"
              :style="{ color: !row.Status ? '#f00' : '' }"
              >{{ row.Status ? "启用" : "禁用" }}</span
            >
            <span v-else-if="column.key === 'IsRegistered'">{{
              row.IsRegistered ? "是" : "否"
            }}</span>
            <span v-else-if="column.key === 'IsSubscribed'">{{
              row.IsSubscribed ? "是" : "否"
            }}</span>
            <span v-else-if="column.key === 'ValidStartTime'"
              >{{ formatTime(row.ValidStartTime, "YYYY-MM-DD") }}~{{
                formatTime(row.ValidEndTime, "YYYY-MM-DD")
              }}</span
            >
            <span v-else-if="column.key === 'RegisterTime'">{{
              formatTime(row.RegisterTime)
            }}</span>
            <span v-else-if="column.key === 'CreateTime'">{{
              formatTime(row.CreateTime)
            }}</span>
            <span v-else>{{ row[column.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button
              v-permission="'user:edit'"
              type="primary"
              link
              @click.stop="handleEditUser(row)"
              >编辑</el-button
            >
            <el-button
              v-permission="'user:editEnabled'"
              type="danger"
              link
              v-if="row.Status"
              @click.stop="handleDisabledUser(row)"
              >禁用</el-button
            >
            <el-button
              v-permission="'user:editEnabled'"
              type="primary"
              link
              v-else
              @click.stop="handleEnableUser(row)"
              >启用</el-button
            >
            <el-button
              v-permission="'user:delete'"
              type="danger"
              link
              @click.stop="handleDelUser(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total,prev,pager,next,jumper"
        :current-page="page"
        :page-size="pageSize"
        :total="totals"
        @current-change="handlePageChange"
        style="margin-top: 30px; justify-content: flex-end"
      />
    </div>
  </div>

  <!-- 开启用户 -->
  <EnableUser
    v-model:show="showEnableUserPop"
    :userId="enableUserId"
    @success="getUserList()"
  />
</template>

<style lang="scss" scoped>
.customer-user-list-page {
  width: 100%;
  overflow: hidden;
  .filter-wrap {
    margin-top: 10px;
    flex-wrap: wrap;
    gap: 10px;
  }
}
</style>