<template>
  <div class="app-container">
    <div
      class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
    >
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <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="email">
          <el-input
            v-model="queryParams.email"
            placeholder="请输入用户邮箱"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="邀请码" prop="invitationCode">
          <el-input
            v-model="queryParams.invitationCode"
            placeholder="请输入用户邀请码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in sys_general_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value == 0 ? 1 : 0"
            />
          </el-select>
        </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>
    </div>

    <div
      class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
    >
      <el-row :gutter="10" class="mb8">
        <!-- <el-col :span="1.5">
                    <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['service:appUser:export']"
                    >
                        导出
                    </el-button>
                </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['service:appUser:export']"
          >
            积分充值
          </el-button>
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </div>

    <div
      class="background-color-fff padding-20 border-radius-8px margin-bottom-20"
    >
      <el-table
        v-loading="loading"
        :data="appUserList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="用户昵称" align="center" prop="nickName" />
        <el-table-column
          label="上级邀请码"
          align="center"
          prop="supInvitationCode"
        />
        <el-table-column label="手机号码" align="center" prop="mobile" />
        <el-table-column label="邀请码" align="center" prop="invitationCode" />
        <!-- <el-table-column label="总积分" align="center" prop="totalPoints">
                    <template #default="scope">
                        <el-tag type="warning" size="small">
                            {{ scope.row.totalPoints || 0 }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="可用积分" align="center" prop="availablePoints">
                    <template #default="scope">
                        <el-tag type="success" size="small">
                            {{ scope.row.availablePoints || 0 }}
                        </el-tag>
                    </template>
                </el-table-column> -->
        <el-table-column label="帐号状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag
              :options="sys_general_status"
              :value="scope.row.status == 0 ? 1 : 0"
            />
          </template>
        </el-table-column>
        <el-table-column label="最后登录IP" align="center" prop="loginIp" />
        <el-table-column
          label="最后登录时间"
          align="center"
          prop="loginDate"
          width="180"
        >
          <template #default="scope">
            <span>{{
              parseTime(scope.row.loginDate, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="240"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              v-if="scope.row.nickName !== 'admin'"
              @click="handleDetails(scope.row)"
              v-hasPermi="['service:appUser:edit']"
            >
              查看详情
            </el-button>
            <el-button
              link
              type="primary"
              icon="Edit"
              v-if="scope.row.nickName !== 'admin'"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['service:appUser:edit']"
            >
              更改等级
            </el-button>
            <el-button
              link
              type="success"
              icon="Coin"
              @click="handlePoints(scope.row)"
              v-hasPermi="['service:appUser:edit']"
            >
              积分充值
            </el-button>
            <el-button
              link
              type="warning"
              icon="Key"
              v-if="scope.row.nickName !== 'admin'"
              @click="handleResetPwd(scope.row)"
              v-hasPermi="['system:appUser:resetPwd']"
            >
              重置密码
            </el-button>
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-if="scope.row.status == 0 && scope.row.nickName !== 'admin'"
              v-hasPermi="['service:appUser:remove']"
            >
              加入黑名单
            </el-button>
            <el-button
              link
              type="info"
              icon="Unlock"
              @click="handleWhite(scope.row)"
              v-if="scope.row.status == 1 && scope.row.nickName !== 'admin'"
              v-hasPermi="['service:appUser:remove']"
            >
              解除黑名单
            </el-button>
          </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"
      />
    </div>

    <!-- 添加或修改移动端用户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="appUserRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="top"
      >
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            v-model="form.nickName"
            disabled
            placeholder="请输入用户昵称"
          />
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input
            v-model="form.email"
            disabled
            placeholder="请输入用户邮箱"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="form.mobile"
            disabled
            placeholder="请输入手机号码"
          />
        </el-form-item>
        <el-form-item label="最后登录IP" prop="loginIp">
          <el-input
            v-model="form.loginIp"
            disabled
            placeholder="请输入最后登录IP"
          />
        </el-form-item>
        <el-form-item label="最后登录时间" prop="loginDate">
          <el-date-picker
            clearable
            v-model="form.loginDate"
            disabled
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择最后登录时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 积分发放对话框 -->
    <el-dialog
      :title="pointsDialog.title"
      v-model="pointsDialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="pointsFormRef"
        :model="pointsForm"
        :rules="pointsRules"
        label-width="100px"
      >
        <el-form-item label="用户昵称">
          <el-input v-model="pointsForm.nickName" disabled />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="pointsForm.mobile" disabled />
        </el-form-item>
        <el-form-item label="当前积分">
          <el-input v-model="pointsForm.currentPoints" disabled />
        </el-form-item>
        <el-form-item label="积分数额" prop="points">
          <el-input-number
            v-model="pointsForm.points"
            :min="1"
            :max="1000000"
            :step="1"
            placeholder="请输入积分数额"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="pointsForm.remark"
            type="textarea"
            placeholder="请输入发放积分的备注信息"
            :rows="3"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitPointsForm"
            :loading="pointsLoading"
          >
            确 定
          </el-button>
          <el-button @click="pointsDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          {{ $t("user-index-1991357fa9c4d3208-2") }}
          <em>{{ $t("user-index-1991357fa9c4d3208-3") }}</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />
              {{ $t("user-index-1991357fa9c4d3208-4") }}
            </div>
            <span>{{ $t("user-index-1991357fa9c4d3208-5") }}</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
            >
              {{ $t("user-index-1991357fa9c4d3208-6") }}
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">
            {{ $t("user-index-1991357fa9c4d3208-7") }}
          </el-button>
          <el-button @click="upload.open = false">
            {{ $t("user-index-1991357fa9c4d3208-8") }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="更改用户等级"
      v-model="updateLevelDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="levelRef"
        :model="updateForm"
        label-width="80px"
        label-position="top"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="updateForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="等级代码" prop="levelCode">
          <el-input
            v-model="updateForm.levelCode"
            placeholder="请输入等级代码"
          />
        </el-form-item>
        <el-form-item label="等级名称" prop="levelName">
          <el-input
            v-model="updateForm.levelName"
            placeholder="请输入等级名称"
          />
        </el-form-item>
        <el-form-item label="等级数值" prop="levelValue">
          <el-input
            v-model="updateForm.levelValue"
            placeholder="请输入等级数值"
          />
        </el-form-item>
        <el-form-item label="上级关系处理">
          <el-radio-group v-model="updateForm.keepOriginalSup">
            <el-radio :label="true">保持原上级</el-radio>
            <el-radio :label="false">清空上级</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!updateForm.keepOriginalSup" label="指定新上级">
          <el-input
            v-model="updateForm.invitationCode"
            placeholder="请输入新的上级用户邀请码"
            clearable
          />
          <div class="form-tip">如果留空，用户将成为独立用户</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormUpdateLevel"
            >确 定</el-button
          >
          <el-button @click="cancelLevel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AppUser">
import { getToken } from "@/utils/auth";
import {
  listAppUser,
  getAppUser,
  delAppUser,
  addAppUser,
  updateAppUser,
  resetUserPwd,
  unblockAppUser,
} from "@/api/service/appUser";
import {
  listRelation,
  getLevelDetails,
  getTeamStatistics,
  updateRelation,
} from "@/api/system/relation";
import {
  triggerIMImport,
  triggerSyncFromDBToIM,
} from "@/api/service/userContacts";

// 积分相关API
import { addUserPoints, updateUserPoints } from "@/api/system/userPoints";

const { proxy } = getCurrentInstance();
const { sys_general_status } = proxy.useDict("sys_general_status");
const router = useRouter();

const appUserList = ref([]);
const open = ref(false);
const updateLevelDialogVisible = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 积分发放相关
const pointsDialog = reactive({
  visible: false,
  title: "发放积分",
});

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/userPoints/importData",
});

const pointsLoading = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    nickName: null,
    email: null,
    mobile: null,
    sex: null,
    avatar: null,
    password: null,
    openid: null,
    unionid: null,
    salt: null,
    status: null,
    loginIp: null,
    loginDate: null,
  },
  // 积分发放表单
  pointsForm: {
    userId: null,
    nickName: "",
    mobile: "",
    currentPoints: 0,
    points: 1,
    remark: "",
  },
  // 积分发放规则
  pointsRules: {
    points: [
      { required: true, message: "请输入积分数额", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value < 1) {
            callback(new Error("积分数额必须大于0"));
          } else if (value > 1000000) {
            callback(new Error("积分数额不能超过100万"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
    remark: [{ required: true, message: "请输入备注信息", trigger: "blur" }],
  },
  rules: {
    userName: [
      { required: true, message: "用户账号不能为空", trigger: "blur" },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
  },
  updateForm: {
    userId: null,
    levelCode: null,
    levelName: null,
    levelValue: null,
    keepOriginalSup: true,
    newSupUserId: null,
    confirmChangeSup: false,
  },
});

const { queryParams, form, rules, pointsForm, pointsRules, updateForm } =
  toRefs(data);

function handleDetails(row) {
  router.push({
    path: "appUserDetails",
    name: "AppUserDetails",
    query: {
      userId: row.userId,
    },
  });
}

/** 查询移动端用户信息列表 */
function getList() {
  loading.value = true;
  listAppUser(queryParams.value)
    .then((response) => {
      appUserList.value = response.rows.map((user) => ({
        ...user,
        totalPoints: user.totalPoints || 0,
        availablePoints: user.availablePoints || 0,
      }));
      total.value = response.total;
      loading.value = false;
    })
    .catch((error) => {
      console.error("获取用户列表失败:", error);
      loading.value = false;
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "积分充值导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "system/userPoints/importTemplate",
    {},
    `user_points_${new Date().getTime()}.xlsx`,
  );
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    t("user-index-1991357fa9c4d3208-34"),

    { dangerouslyUseHTMLString: true },
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

// 表单重置
function reset() {
  form.value = {
    userId: null,
    userName: null,
    nickName: null,
    email: null,
    mobile: null,
    sex: null,
    avatar: null,
    password: null,
    openid: null,
    unionid: null,
    salt: null,
    status: null,
    delFlag: null,
    loginIp: null,
    loginDate: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("appUserRef");
}

// 重置积分表单
function resetPointsForm() {
  pointsForm.value = {
    userId: null,
    nickName: "",
    mobile: "",
    currentPoints: 0,
    points: 1,
    remark: "",
  };
  proxy.$refs.pointsFormRef?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _userId = row.userId || ids.value;
  getLevelDetails(_userId).then((response) => {
    updateForm.value = response.data;
    updateLevelDialogVisible.value = true;
    updateForm.value.keepOriginalSup = true;
    updateForm.value.invitationCode = null;
  });
}

function cancelLevel() {
  updateLevelDialogVisible.value = false;
  updateForm.value = {};
}

function submitFormUpdateLevel() {
  proxy.$modal
    .confirm(
      '是否确认修改用户信息编号为"' + updateForm.value.userId + '"的等级？',
    )
    .then(function () {
      updateRelation(updateForm.value).then((res) => {
        cancelLevel();
        getList();
        proxy.$modal.msgSuccess("操作成功");
      });
    });
}

/** 发放积分 */
function handlePoints(row) {
  resetPointsForm();
  pointsForm.value.userId = row.userId;
  pointsForm.value.nickName = row.nickName;
  pointsForm.value.mobile = row.mobile;
  pointsForm.value.currentPoints = row.availablePoints || 0;
  pointsDialog.title = `发放积分 - ${row.nickName}`;
  pointsDialog.visible = true;
}

/** 提交积分发放表单 */
function submitPointsForm() {
  proxy.$refs.pointsFormRef.validate((valid) => {
    if (valid) {
      pointsLoading.value = true;
      addUserPoints(pointsForm.value)
        .then((response) => {
          proxy.$modal.msgSuccess("积分发放成功");
          pointsDialog.visible = false;
          // 刷新用户列表
          getList();
        })
        .catch((error) => {
          console.error("积分发放失败:", error);
          proxy.$modal.msgError(error.msg || "积分发放失败");
        })
        .finally(() => {
          pointsLoading.value = false;
        });
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appUserRef"].validate((valid) => {
    if (valid) {
      if (form.value.userId != null) {
        updateAppUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAppUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleWhite(row) {
  const _userIds = row.userId || ids.value;
  proxy.$modal
    .confirm('是否确认移动端用户信息编号为"' + _userIds + '"解除黑名单？')
    .then(function () {
      return unblockAppUser({ userId: _userIds });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

function handleTriggerSync(row, num) {
  const _userIds = row.userId || ids.value;
  const msg =
    num == 1
      ? '是否确认移动端用户信息编号为"' + _userIds + "导出IM好友"
      : '是否确认移动端用户信息编号为"' + _userIds + "导入IM好友";
  proxy.$modal
    .confirm(msg)
    .then(function () {
      return num == 1
        ? triggerIMImport(_userIds)
        : triggerSyncFromDBToIM(_userIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _userIds = row.userId || ids.value;
  proxy.$modal
    .confirm('是否确认移动端用户信息编号为"' + _userIds + '"加入黑名单？')
    .then(function () {
      return delAppUser(_userIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

/** 重置密码按钮操作 */
function 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.userId, value).then((response) => {
        proxy.$modal.msgSuccess("修改成功" + value);
      });
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "service/appUser/export",
    {
      ...queryParams.value,
    },
    `appUser_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>

<style scoped>
.app-container {
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
  padding: 20px;
}

.background-color-fff {
  background-color: #fff;
}

.padding-20 {
  padding: 20px;
}

.border-radius-8px {
  border-radius: 8px;
}

.margin-bottom-20 {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.w-full {
  width: 100%;
}

/* 按钮样式优化 */
.el-button--link {
  padding: 0 8px;
}

/* 积分发放表单样式 */
.el-input-number.w-full {
  width: 100%;
}

.el-textarea {
  width: 100%;
}
</style>
