<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item :label="t('myuser.username')" prop="username">
        <el-input
            v-model="queryParams.username"
            :placeholder="t('myuser.pleaseEnterUsername')"
            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="t('myuser.phone')" prop="phone">
        <el-input
            v-model="queryParams.phone"
            :placeholder="t('myuser.pleaseEnterPhone')"
            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">{{ t('common.search') }}</el-button>
        <el-button icon="Refresh" @click="resetQuery">{{ t('common.reset') }}</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="t('myuser.userId')" align="center" prop="loanUserId" />
      <el-table-column :label="t('myuser.userName')" align="center" prop="username" :show-overflow-tooltip="true" />
      <el-table-column :label="t('myuser.nickname')" align="center" prop="nickname" :show-overflow-tooltip="true" />
      <el-table-column :label="t('myuser.avatar')" 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="t('myuser.phone')" align="center" prop="phone" width="120" />
      <el-table-column :label="t('myuser.contactUploadStatus')" align="center" prop="upContact">
        <template #default="{ row }">
          <span>{{ upText(row.upContact) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('myuser.smsUploadStatus')" align="center" prop="upSms">
        <template #default="{ row }">
          <span>{{ upText(row.upSms) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('myuser.callUploadStatus')" align="center" prop="upCall">
        <template #default="{ row }">
          <span>{{ upText(row.upCall) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('myuser.positionUploadStatus')" align="center" prop="upPosition">
        <template #default="{ row }">
          <span>{{ upText(row.upPosition) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('myuser.imageUploadStatus')" align="center" prop="upImage">
        <template #default="{ row }">
          <span>{{ upText(row.upImage) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('myuser.agent')" align="center" prop="isAgent">
        <template #default="{ row }">
          <span>{{ row.isAgent ? t('myuser.yes') : t('myuser.no') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('myuser.agentId')" align="center" prop="agentId" />
      <el-table-column :label="t('myuser.status')" align="center" prop="status">
        <template #default="{ row }">
          <dict-tag :options="sys_normal_disable" :value="row.status"/>
        </template>
      </el-table-column>
      <el-table-column :label="t('myuser.createTime')" 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="t('myuser.operation')" align="center" width="140" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-tooltip :content="t('myuser.view')" 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="140px">
        <el-form-item :label="t('myuser.userInfo')" prop="username">
          <el-input v-model="form.username" :disabled="isUpdate || isView" :placeholder="t('myuser.pleaseEnterUserInfo')" />
        </el-form-item>
        <el-form-item :label="t('myuser.userNickname')" prop="nickname">
          <el-input v-model="form.nickname" :disabled="isView" :placeholder="t('myuser.pleaseEnterUserNickname')" />
        </el-form-item>
        <el-form-item :label="t('myuser.avatar')" prop="avatar">
          <image-preview :src="getImageUrl(form.avatar)"  :limit="1" :width="80" :height="80" />
        </el-form-item>
        <el-form-item :label="t('myuser.phoneNumber')" prop="phone">
          <el-input v-model="form.phone" :disabled="isView" :placeholder="t('myuser.pleaseEnterPhoneNumber')" />
        </el-form-item>
        <el-form-item :label="t('myuser.agent')" prop="isAgent">
          <el-radio-group v-model="form.isAgent" :disabled="isView">
            <el-radio
                key="true"
                :label="true"
            >{{ t('myuser.yes') }}</el-radio>
            <el-radio
                key="false"
                :label="false"
            >{{ t('myuser.no') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('myuser.status')" prop="status">
          <el-radio-group v-model="form.status" :disabled="isView">
            <el-radio
                v-for="dict in statusOptions"
                :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">{{ t('common.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

const { t } = useI18n()

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

// 状态选项（国际化）
const statusOptions = computed(() => {
  if (!sys_normal_disable.value || !Array.isArray(sys_normal_disable.value)) {
    return []
  }
  return sys_normal_disable.value.map(dict => {
    // 根据字典值返回对应的翻译
    if (dict.value === '0' || dict.value === 0) {
      return { ...dict, label: t('myuser.statusNormal') }
    } else if (dict.value === '1' || dict.value === 1) {
      return { ...dict, label: t('myuser.statusDisable') }
    }
    return dict
  })
})

// 獲取文件路徑前綴
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 = computed(() => ({
  username: [
    { required: true, message: t('myuser.usernameRequired'), trigger: "blur" }
  ],
  nickname: [
    { required: true, message: t('myuser.nicknameRequired'), trigger: "blur" }
  ],
  password: [
    { required: true, message: t('myuser.passwordRequired'), trigger: "blur" }
  ],
  phone: [
    { required: true, message: t('myuser.phoneRequired'), trigger: "blur" }
  ],
  status: [
    { required: true, message: t('myuser.statusRequired'), trigger: "change" }
  ],
  isAgent: [
    { required: true, message: t('myuser.agentRequired'), trigger: "change" }
  ],
  adminPassword: [{ required: true, message: t('myuser.adminPasswordRequired'), 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 t('myuser.uploaded')
    case false:
      return t('myuser.rejected')
    default:
      return type
  }
}

/** 重设密码按钮操作 */
const handleResetPwd = (row) => {
  proxy.$prompt(t('myuser.resetPasswordPrompt', { username: row.username }), t('login.tip'), {
    confirmButtonText: t('common.confirm'),
    cancelButtonText: t('common.cancel'),
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: t('myuser.passwordLengthError'),
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return t('myuser.invalidChars')
      }
    },
  }).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 = t('myuser.addMember')
  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 = t('myuser.editMember')
  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 = t('myuser.viewMember')
  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(t('myuser.resetPasswordConfirm')).then(() => {
    // return delLoanuser(loanUserIds)
  }).then(() => {
    getList()
    ElMessage.success(t('myuser.resetPasswordSuccess'))
  }).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(t('myuser.deleteConfirm', { id: loanUserIds })).then(() => {
    // return delLoanuser(loanUserIds)
  }).then(() => {
    getList()
    ElMessage.success(t('myuser.deleteSuccess'))
  }).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>
