<!--
 * @Descripttion: (微信用户表/gift_user)
 * @Author: (admin)
 * @Date: (2025-07-30)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="15" class="mb10">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['giftuser:add']" plain icon="plus" @click="handleAdd">
          {{ $t('btn.add') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="download" @click="handleExport" v-hasPermi="['giftuser:export']">
          {{ $t('btn.export') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      :data="dataList"
      v-loading="loading"
      ref="table"
      border
      header-cell-class-name="el-table-header-cell"
      highlight-current-row
      @sort-change="sortChange">
      <el-table-column prop="id" label="主键ID" align="center" sortable v-if="columns.showColumn('id')" />
      <el-table-column prop="openid" label="微信openid" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('openid')" />
      <el-table-column prop="unionid" label="微信unionid" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('unionid')" />
      <el-table-column prop="nickname" label="昵称" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('nickname')" />
      <el-table-column prop="avatarUrl" label="头像URL" align="center" v-if="columns.showColumn('avatarUrl')">
        <template #default="scope">
          <ImagePreview :src="scope.row.avatarUrl"></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" align="center" v-if="columns.showColumn('gender')">
        <template #default="scope">
          <dict-tag :options="options.sys_user_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center" :show-overflow-tooltip="true" v-if="columns.showColumn('phone')" />
      <el-table-column prop="status" label="状态" align="center" v-if="columns.showColumn('status')">
        <template #default="scope">
          <dict-tag :options="options.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        prop="lastLoginTime"
        label="最后登录时间"
        :show-overflow-tooltip="true"
        sortable
        v-if="columns.showColumn('lastLoginTime')" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="primary" size="small" icon="view" title="详情" @click="handlePreview(scope.row)"></el-button>
          <el-button
            type="success"
            size="small"
            icon="edit"
            title="编辑"
            v-hasPermi="['giftuser:edit']"
            @click="handleUpdate(scope.row)"></el-button>
          <el-button
            type="danger"
            size="small"
            icon="delete"
            title="删除"
            v-hasPermi="['giftuser:delete']"
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :lock-scroll="false" v-model="open">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :lg="24">
            <el-form-item label="微信openid" prop="openid">
              <el-input v-model="form.openid" placeholder="请输入微信openid" />
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="微信unionid" prop="unionid">
              <el-input v-model="form.unionid" placeholder="请输入微信unionid" />
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="头像URL" prop="avatarUrl">
              <UploadImage v-model="form.avatarUrl" :data="{ uploadType: 1 }" />
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option v-for="item in options.sys_user_sex" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in options.sys_normal_disable" :key="item.dictValue" :value="item.dictValue">
                  {{ item.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :lg="24">
            <el-form-item label="最后登录时间" prop="lastLoginTime">
              <el-date-picker v-model="form.lastLoginTime" type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :loading="state.submitLoading" @click="submitForm">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="giftuser">
import { listGiftUser, addGiftUser, delGiftUser, updateGiftUser, getGiftUser } from '@/api/business/giftuser.js'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: 'Id',
  sortType: 'desc',
  nickname: undefined
})
const columns = ref([
  { visible: true, align: 'center', type: '', prop: 'id', label: '主键ID' },
  { visible: true, align: 'center', type: '', prop: 'openid', label: '微信openid', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'unionid', label: '微信unionid', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'nickname', label: '昵称', showOverflowTooltip: true },
  { visible: true, align: 'center', type: 'img', prop: 'avatarUrl', label: '头像URL', showOverflowTooltip: true },
  { visible: true, align: 'center', type: 'dict', prop: 'gender', label: '性别', showOverflowTooltip: true, dictType: 'sys_user_sex' },
  { visible: true, align: 'center', type: '', prop: 'phone', label: '手机号', showOverflowTooltip: true },
  { visible: true, align: 'center', type: 'dict', prop: 'status', label: '状态', showOverflowTooltip: true, dictType: 'sys_normal_disable' },
  { visible: false, align: 'center', type: '', prop: 'lastLoginTime', label: '最后登录时间', showOverflowTooltip: true }
  //{ visible: false, prop: 'actions', label: '操作', type: 'slot', width: '160' }
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

var dictParams = ['sys_user_sex', 'sys_normal_disable']

proxy.getDicts(dictParams).then((response) => {
  response.data.forEach((element) => {
    state.options[element.dictType] = element.list
  })
})

function getList() {
  loading.value = true
  listGiftUser(queryParams).then((res) => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置查询操作
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}
// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

    if (column.prop == 'lastLoginTime') {
      sort = 'last_login_time'
    }
    if (column.prop == 'createTime') {
      sort = 'create_time'
    }
  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref('')
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  rules: {
    openid: [{ required: true, message: '微信openid不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
  },
  options: {
    // 性别 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    sys_user_sex: [],
    // 状态 选项列表 格式 eg:{ dictLabel: '标签', dictValue: '0'}
    sys_normal_disable: []
  }
})

const { form, rules, options, single, multiple } = toRefs(state)

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    id: null,
    openid: null,
    unionid: null,
    nickname: null,
    avatarUrl: null,
    gender: null,
    phone: null,
    status: null,
    lastLoginTime: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm('formRef')
}

/**
 * 查看
 * @param {*} row
 */
function handlePreview(row) {
  reset()
  const id = row.id
  getGiftUser(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '查看'
      opertype.value = 3
      form.value = {
        ...data
      }
    }
  })
}

// 添加按钮操作
function handleAdd() {
  reset()
  open.value = true
  state.submitLoading = false
  title.value = '添加微信用户表'
  opertype.value = 1
}
// 修改按钮操作
function handleUpdate(row) {
  reset()
  state.submitLoading = false
  const id = row.id || ids.value
  getGiftUser(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '修改微信用户表'
      opertype.value = 2

      form.value = {
        ...data
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      state.submitLoading = true

      if (form.value.id != undefined && opertype.value === 2) {
        updateGiftUser(form.value).then((res) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addGiftUser(form.value)
          .then((res) => {
            proxy.$modal.msgSuccess('新增成功')
            open.value = false
            getList()
          })
          .finally(() => {
            setTimeout(() => {
              state.submitLoading = false
            }, 800)
          })
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.id || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', '警告', {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: 'warning'
    })
    .then(function () {
      return delGiftUser(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
}

// 导出按钮操作
function handleExport() {
  proxy
    .$confirm('是否确认导出微信用户表数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      await proxy.downFile('/business/GiftUser/export', { ...queryParams })
    })
}

handleQuery()
</script>
