<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="用戶名稱" prop="username">
        <el-input
            v-model="queryParams.username"
            placeholder="請輸入用戶名稱"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="用戶暱稱" prop="nickname">-->
<!--        <el-input-->
<!--            v-model="queryParams.nickname"-->
<!--            placeholder="請輸入用戶暱稱"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="手機號碼" prop="phone">
        <el-input
            v-model="queryParams.phone"
            placeholder="請輸入手機號碼"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="是否為代理" prop="isAgent">-->
<!--        <el-select v-model="queryParams.isAgent" placeholder="請選擇是否為代理" clearable style="width: 240px">-->
<!--          <el-option-->
<!--              label="是"-->
<!--              :value="true"-->
<!--          />-->
<!--          <el-option-->
<!--              label="否"-->
<!--              :value="false"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="狀態" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="用戶狀態" clearable style="width: 240px">-->
<!--          <el-option-->
<!--              v-for="dict in sys_normal_disable"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="所屬代理ID" prop="agentId">-->
<!--        <el-input-->
<!--            v-model="queryParams.agentId"-->
<!--            placeholder="請輸入所屬代理ID"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜尋</el-button>
        <el-button icon="Refresh" @click="resetQuery">重設</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="Plus"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['system:loanuser:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['system:loanuser:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="Delete"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['system:loanuser:remove']"-->
<!--        >刪除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="Download"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['system:loanuser:export']"-->
<!--        >匯出</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="loanuserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="使用者ID" align="center" prop="loanUserId" />
      <el-table-column label="使用者名稱" align="center" prop="username" :show-overflow-tooltip="true" />
      <el-table-column label="使用者暱稱" align="center" prop="nickname" :show-overflow-tooltip="true" />
      <el-table-column label="頭像" align="center" prop="avatar" width="100">
        <template #default="{ row }">
          <image-preview :src="getImageUrl(row.avatar)" :width="40" :height="40"/>
        </template>
      </el-table-column>
      <el-table-column label="手機號碼" align="center" prop="phone" width="120" />
      <el-table-column label="通訊錄上傳狀態" align="center" prop="upContact">
        <template #default="{ row }">
          <span>{{ upText(row.upContact) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="簡訊上傳狀態" align="center" prop="upSms">
        <template #default="{ row }">
          <span>{{ upText(row.upSms) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="通話記錄上傳狀態" align="center" prop="upCall">
        <template #default="{ row }">
          <span>{{ upText(row.upCall) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户定位上傳狀態" align="center" prop="upPosition">
        <template #default="{ row }">
          <span>{{ upText(row.upPosition) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户圖片上傳狀態" align="center" prop="upImage">
        <template #default="{ row }">
          <span>{{ upText(row.upImage) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="代理" align="center" prop="isAgent">
        <template #default="{ row }">
          <span>{{ row.isAgent ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属代理ID" align="center" prop="agentId" />
      <el-table-column label="狀態" align="center" prop="status">
        <template #default="{ row }">
          <dict-tag :options="sys_normal_disable" :value="row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="建立時間" align="center" prop="createTime" width="160">
        <template #default="{ row }">
          <span>{{ proxy.parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="更新時間" align="center" prop="updateTime" width="180">-->
      <!--        <template #default="{ row }">-->
      <!--          <span>{{ parseTime(row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" width="140" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-tooltip content="查看" placement="top">
            <el-button link type="primary" icon="View" @click.stop="handleView(row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 新增或修改会员对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" :disabled="isUpdate || isView" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" :disabled="isView" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="頭像" prop="avatar">
          <image-preview :src="getImageUrl(form.avatar)"  :limit="1" :width="80" :height="80" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" :disabled="isView" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="代理" prop="isAgent">
          <el-radio-group v-model="form.isAgent" :disabled="isView">
            <el-radio
                key="true"
                :label="true"
            >是</el-radio>
            <el-radio
                key="false"
                :label="false"
            >否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" :disabled="isView">
            <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
<!--          <el-button type="primary" :disabled="isView" @click="submitForm">确 定</el-button>-->
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Loanuser">
import { ref, reactive, getCurrentInstance, onMounted, nextTick } from 'vue'
import { getMyAgentMember } from "@/api/system/myuser.js"
import { ElMessageBox, ElMessage } from 'element-plus'
import { isExternal } from '@/utils/validate'

const { proxy } = getCurrentInstance()
const { sys_show_hide, sys_normal_disable } = proxy.useDict("sys_show_hide", "sys_normal_disable")

// 獲取文件路徑前綴
const filePath = import.meta.env.VITE_APP_FILE_PATH || ''

// 獲取完整的圖片URL
const getImageUrl = (url) => {
  if (!url) return ''
  // 如果是外部鏈接，直接返回
  if (isExternal(url)) {
    return url
  }
  // 如果已經包含文件路徑前綴，直接返回
  if (filePath && url.startsWith(filePath)) {
    return url
  }
  // 在前面加上文件路徑前綴
  return filePath ? filePath + url : url
}

// 響應式數據
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const loanuserList = ref([])
const title = ref("")
const open = ref(false)
const openUserPassword = ref(false)
const isUpdate = ref(false)
const isView = ref(false)
const adminPassword = ref('')

// 查询参数（对齐 index.vue：pageNum/pageSize）
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: null,
  nickname: null,
  phone: null,
  status: null,
  isAgent: null,
  agentId: null
})

// 表单参数
const form = ref({})

// 表单校验
const rules = reactive({
  username: [
    { required: true, message: "使用者名稱不能為空", trigger: "blur" }
  ],
  nickname: [
    { required: true, message: "使用者暱稱不能為空", trigger: "blur" }
  ],
  password: [
    { required: true, message: "密碼不能為空", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "手機號碼不能為空", trigger: "blur" }
  ],
  status: [
    { required: true, message: "狀態不能為空", trigger: "change" }
  ],
  isAgent: [
    { required: true, message: "代理不能為空", trigger: "change" }
  ],
  adminPassword: [{ required: true, message: "管理員密碼不能為空", trigger: "blur" }],
})

// 获取ref引用
const queryFormRef = ref()
const formRef = ref()
const formpasswordRef = ref()



onMounted(() => {
  getList()
})

/** 查询会员管理列表 */
const getList = () => {
  loading.value = true
  const params = {
    pageNumber: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    username: queryParams.username,
    nickname: queryParams.nickname,
    phone: queryParams.phone,
    status: queryParams.status,
    isAgent: queryParams.isAgent,
    agentId: queryParams.agentId,
  }
  getMyAgentMember(params).then(response => {
    loanuserList.value = response.data.records
    total.value = response.data.total
    loading.value = false
    console.log(loanuserList)
  })
}

const upText = (type) => {
  switch (type) {
    case true:
      return '已上傳'
    case false:
      return '拒絕'
    default:
      return type
  }
}

/** 重设密码按钮操作 */
const handleResetPwd = (row) => {
  proxy.$prompt('請輸入"' + row.username + '"的新密碼', "提示", {
    confirmButtonText: "確定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "使用者密碼長度必須介於 5 和 20 之間",
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return "不能包含非法字元：< > \" ' \\\ |"
      }
    },
  }).then(({ value }) => {
    // resetUserPwd(row.loanUserId, value).then(response => {
    //   proxy.$modal.msgSuccess("修改成功，新密碼是：" + value)
    // })
  }).catch(() => {})
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
  isView.value = false
}

// 表单重设
const reset = () => {
  form.value = {
    loanUserId: null,
    username: null,
    nickname: null,
    password: null,
    avatar: null,
    phone: null,
    status: null,
    uniqueidentifier: null,
    delFlag: null,
    createTime: null,
    updateTime: null,
    isAgent: false,
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 多选框选中资料
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.loanUserId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset()
  open.value = true
  isUpdate.value = false
  isView.value = false
  title.value = "新增會員管理"
  nextTick(() => {
    if (formRef.value) formRef.value.clearValidate && formRef.value.clearValidate()
  })
}

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset()
  const loanUserId = row.loanUserId || ids.value
  // 直接使用表格行数据打开对话框，后续如需从后端拉取明细，可替换为接口填充
  form.value = { ...row }
  open.value = true
  isUpdate.value = true
  isView.value = false
  title.value = "修改會員管理"
  nextTick(() => {
    if (formRef.value) formRef.value.clearValidate && formRef.value.clearValidate()
  })
}

/** 查看按钮操作 */
const handleView = (row) => {
  reset()
  form.value = { ...row }
  isUpdate.value = false
  isView.value = true
  open.value = true
  title.value = "查看會員管理"
  nextTick(() => {
    if (formRef.value) formRef.value.clearValidate && formRef.value.clearValidate()
  })
}

const handleUpdatePasswrod = (row) => {
  const loanUserId = row.loanUserId || ids.value
  // getLoanuser(loanUserId).then(response => {
  //   form.value = response.data
  //   openUserPassword.value = true
  // })
}

const submitChangePassword = (row) => {
  const loanUserIds = row.loanUserId || ids.value
  ElMessageBox.confirm('是否確認重置會員密碼為123456？').then(() => {
    // return delLoanuser(loanUserIds)
  }).then(() => {
    getList()
    ElMessage.success("重置成功")
  }).catch(() => {})
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (form.value.loanUserId != null) {
        // updateLoanuser(form.value).then(response => {
        //   proxy.$modal.msgSuccess("修改成功")
        //   open.value = false
        //   getList()
        // })
      } else {
        // addLoanuser(form.value).then(response => {
        //   proxy.$modal.msgSuccess("新增成功")
        //   open.value = false
        //   getList()
        // })
      }
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (row) => {
  const loanUserIds = row.loanUserId || ids.value
  ElMessageBox.confirm('是否確認刪除會員管理編號為"' + loanUserIds + '"的資料項？').then(() => {
    // return delLoanuser(loanUserIds)
  }).then(() => {
    getList()
    ElMessage.success("刪除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy.download('system/loanuser/export', {
    pageNumber: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    username: queryParams.username,
    nickname: queryParams.nickname,
    phone: queryParams.phone,
    status: queryParams.status,
    isAgent: queryParams.isAgent,
    agentId: queryParams.agentId,
  }, `loanuser_${new Date().getTime()}.xlsx`)
}
</script>
