<template>
  <div class="p-2">
    <!-- 商户登录地址 -->
    <el-alert type="warning" :closable="false" class="mb-[10px]" v-if="loginAddress">
      <template #default>
        <span class="login-url-text">商户登录地址：</span>
        <a :href="loginAddress" target="_blank" class="login-url-link">{{ loginAddress }}</a>
      </template>
    </el-alert>

    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <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="phonenumber">
              <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" 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-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:user:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:user:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:user:remove']"
              >删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="sysMerchantList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="账号名称" align="center" width="200">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.userName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" width="300">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.phonenumber || '-' }}</span>
          </template>
        </el-table-column>

        <!--        <el-table-column label="授权到期" align="center" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ scope.row.expireDate ? parseTime(scope.row.expireDate, '{y}-{m}-{d}') : '-' }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="开通时间" align="center" width="200">
          <template #default="scope">
            <span>{{ scope.row.userInfo?.createTime || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后活跃" align="center" width="200">
          <template #default="scope">
            <span>{{ scope.row.lastActiveTime || '-' }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="状态" align="center" width="80">-->
        <!--          <template #default="scope">-->
        <!--            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">修改用户</el-button>
            <el-button link type="primary" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:edit']">重置密码</el-button>
            <!--            <el-button link type="primary" @click="handleStatusChange(scope.row)" v-hasPermi="['system:sysMerchant:edit']">-->
            <!--              {{ scope.row.status === '0' ? '禁用' : '启用' }}-->
            <!--            </el-button>-->
            <!--            <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['system:sysMerchant: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" />
    </el-card>
    <!-- 添加或修改用户信息拓展对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="sysMerchantFormRef" :model="form" :rules="rules" label-width="100px">
        <!-- 用户基本信息 -->
        <el-divider content-position="left">用户基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账号名称" prop="user.userName">
              <el-input v-model="form.user.userName" placeholder="请输入账号名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="user.nickName">
              <el-input v-model="form.user.nickName" placeholder="用户姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="user.phonenumber">
              <el-input v-model="form.user.phonenumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="user.email">
              <el-input v-model="form.user.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" v-if="!form.merchant?.userId">
            <el-form-item label="密码" prop="user.password">
              <el-input v-model="form.user.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="user.sex">
              <el-select v-model="form.user.sex" placeholder="请选择性别">
                <el-option label="男" value="0" />
                <el-option label="女" value="1" />
                <el-option label="未知" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 用户信息 -->
        <el-divider content-position="left">用户信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属代理人" prop="merchant.agentId">
              <el-select v-model="form.merchant.agentId" placeholder="请选择代理人" clearable filterable style="width: 100%">
                <el-option v-for="agent in agentList" :key="agent.userId" :label="`${agent.userInfo?.userName}(${agent.userInfo?.nickName})`" :value="agent.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="user.codeArr">
              <el-cascader
                v-model="form.user.codeArr"
                :options="regionData as any"
                placeholder="请选择"
                @change="handleChange"
                style="width: 100%"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授权到期" prop="merchant.expireDate">
              <el-date-picker
                clearable
                v-model="form.merchant.expireDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择授权到期时间"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最后活跃" prop="merchant.lastActiveTime">
              <el-date-picker
                clearable
                v-model="form.merchant.lastActiveTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择最后活跃时间"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="merchant.status">
              <el-radio-group v-model="form.merchant.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }} </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="merchant.remark">
          <el-input v-model="form.merchant.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysMerchant" lang="ts">
import { computed } from 'vue';
import { listSysMerchant, getSysMerchant, delSysMerchant, addSysMerchant, updateSysMerchant, resetMerchantPwd } from '@/api/agent/merchant';
import { SysMerchantVO, SysMerchantQuery, SysMerchantForm, SysUserMerchantForm, SysUserForm } from '@/api/agent/merchant/types';
import { listSysAgent } from '@/api/system/sysAgent';
import { SysAgentVO } from '@/api/system/sysAgent/types';
import { regionData } from 'element-china-area-data';
import { ElMessageBox } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable, background_url } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'background_url'));

const sysMerchantList = ref<SysMerchantVO[]>([]);
const agentList = ref<SysAgentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const loginAddress = ref<string>('');

// 商户登录地址 - 从字典获取
const merchantLoginUrl = computed(() => {
  if (!background_url.value || background_url.value.length === 0) {
    return '';
  }
  const urlDict = background_url.value.find((item: any) => item.value === 'merchant_bg');
  return urlDict?.label || '';
});

const queryFormRef = ref<ElFormInstance>();
const sysMerchantFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SysUserMerchantForm = {
  user: {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    userType: undefined,
    identity: undefined,
    email: undefined,
    phonenumber: undefined,
    sex: undefined,
    password: undefined,
    status: '0',
    remark: undefined,
    roleIds: [],
    postIds: [],
    areaCode: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    codeArr: []
  },
  merchant: {
    userId: undefined,
    lastActiveTime: undefined,
    expireDate: undefined,
    status: '0',
    remark: undefined,
    agentId: undefined
  }
};

const data = reactive<PageData<SysUserMerchantForm, SysMerchantQuery>>({
  form: JSON.parse(JSON.stringify(initFormData)),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    tenantId: undefined,
    areaCode: undefined,
    province: undefined,
    city: undefined,
    district: undefined,
    lastActiveTime: undefined,
    expireDate: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    'user.userName': [
      { required: true, message: '账号名称不能为空', trigger: 'blur' },
      { min: 2, max: 30, message: '账号名称长度必须介于 2 和 30 之间', trigger: 'blur' }
    ],
    'user.nickName': [
      { required: true, message: '用户姓名不能为空', trigger: 'blur' },
      { min: 2, max: 30, message: '用户姓名长度必须介于 2 和 30 之间', trigger: 'blur' }
    ],
    'user.password': [{ min: 6, max: 20, message: '密码长度必须介于 6 和 20 之间', trigger: 'blur' }],
    'user.email': [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    'user.phonenumber': [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    'merchant.agentId': [{ required: true, message: '代理人不能为空', trigger: 'change' }],
    'merchant.expireDate': [{ required: true, message: '授权到期不能为空', trigger: 'blur' }],
    'merchant.lastActiveTime': [{ required: true, message: '最后活跃时间不能为空', trigger: 'blur' }],
    'merchant.status': [{ required: true, message: '状态不能为空', trigger: 'change' }],
    'merchant.remark': [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

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

/** 查询用户信息拓展列表 */
const getList = async () => {
  loading.value = true;

  // 转换查询参数为嵌套结构，匹配后端SysUserExtendBo
  const queryParamsConverted = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    'user.userName': queryParams.value.userName,
    'user.phonenumber': queryParams.value.phonenumber,
    'merchant.status': queryParams.value.status,
    'merchant.agentId': queryParams.value.agentId
  };

  const res = await listSysMerchant(queryParamsConverted as any);
  sysMerchantList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询代理人列表 */
const getAgentList = async () => {
  const res = await listSysAgent({ pageNum: 1, pageSize: 1000, status: '0' });
  agentList.value = res.rows;
};

// 构建映射表：code => name
const areaCodeToName: Record<string, string> = {};

function buildAreaMap(data: any[]) {
  data.forEach((node) => {
    areaCodeToName[node.value] = node.label;
    if (node.children) buildAreaMap(node.children);
  });
}

// 初始化时构建一次
buildAreaMap(regionData);

// 区域选择变化处理
const handleChange = (val: string[]) => {
  if (form.value.user) {
    form.value.user.areaCode = val.join(',');
    form.value.user.province = areaCodeToName[val[0]] || '';
    form.value.user.city = areaCodeToName[val[1]] || '';
    form.value.user.district = areaCodeToName[val[2]] || '';
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = JSON.parse(JSON.stringify(initFormData));
  sysMerchantFormRef.value?.resetFields();
};

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: SysMerchantVO[]) => {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  await getAgentList();
  dialog.visible = true;
  dialog.title = '添加用户信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SysMerchantVO) => {
  reset();
  await getAgentList();

  if (row && row.userInfo) {
    // 将用户基本信息从 userInfo 赋值给 user
    if (form.value.user) {
      form.value.user.userId = row.userInfo.userId;
      form.value.user.userName = row.userInfo.userName;
      form.value.user.nickName = row.userInfo.nickName;
      form.value.user.email = row.userInfo.email;
      form.value.user.phonenumber = row.userInfo.phonenumber;
      form.value.user.sex = row.userInfo.sex;
      form.value.user.status = row.userInfo.status;
      form.value.user.remark = row.userInfo.remark;
      form.value.user.deptId = row.userInfo.deptId;

      // 设置区域信息
      form.value.user.areaCode = row.userInfo.areaCode;
      form.value.user.province = row.userInfo.province;
      form.value.user.city = row.userInfo.city;
      form.value.user.district = row.userInfo.district;

      // 设置级联选择器的值
      if (row.userInfo.areaCode) {
        form.value.user.codeArr = row.userInfo.areaCode.split(',');
      }
    }

    // 将商户信息从顶层赋值给 merchant
    if (form.value.merchant) {
      form.value.merchant.userId = row.userId;
      form.value.merchant.lastActiveTime = row.lastActiveTime;
      form.value.merchant.expireDate = row.expireDate;
      form.value.merchant.status = row.status;
      form.value.merchant.remark = row.remark;
      form.value.merchant.agentId = row.agentId;
    }
  }

  dialog.visible = true;
  dialog.title = '修改用户信息';
};

/** 提交按钮 */
const submitForm = () => {
  // 动态设置密码验证规则
  const isEdit = !!form.value.merchant?.userId;
  if (!isEdit) {
    // 新增模式下密码必填
    if (!form.value.user?.password) {
      proxy?.$modal.msgError('密码不能为空');
      return;
    }
  }

  sysMerchantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (isEdit) {
        await updateSysMerchant(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSysMerchant(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 状态修改 */
const handleStatusChange = async (row: SysMerchantVO) => {
  const currentStatus = row.status;
  const newStatus = currentStatus === '0' ? '1' : '0';
  const statusText = newStatus === '0' ? '启用' : '停用';

  try {
    await proxy?.$modal.confirm(`确认要${statusText}用户"${row.userInfo?.nickName}"吗？`);

    // 构建更新数据，只更新状态
    const updateData: SysUserMerchantForm = {
      user: {
        userId: row.userId,
        status: newStatus
      },
      merchant: {
        userId: row.userId,
        status: newStatus
      }
    };

    await updateSysMerchant(updateData);
    proxy?.$modal.msgSuccess(`${statusText}成功`);
    await getList();
  } catch (error) {
    console.error('状态修改失败:', error);
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: SysMerchantVO) => {
  const _userIds = row?.userId || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户信息编号为"' + _userIds + '"的数据项？').finally(() => (loading.value = false));
  await delSysMerchant(_userIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 重置密码按钮操作 */
const handleResetPwd = async (row: SysMerchantVO) => {
  try {
    const userName = row.userInfo?.nickName || row.userInfo?.userName || '';
    const res = await ElMessageBox.prompt('请输入"' + userName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      inputValidator: (value) => {
        if (/<|>|"|'|\||\\/.test(value)) {
          return '不能包含非法字符：< > " \' \\ |';
        }
      }
    });

    if (res) {
      await resetMerchantPwd(row.userId, res.value);
      proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value);
    }
  } catch (error) {
    // 用户取消操作，不需要处理
  }
};

onMounted(() => {
  getList();
  proxy?.getConfigKey('merchant.login.address').then((response) => {
    loginAddress.value = response.data;
  });
});
</script>

<style scoped>
/* 登录地址样式 */
.login-url-text {
  font-size: 14px;
  color: #606266;
}

.login-url-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}

.login-url-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>
