<template>
  <div class="page-container">
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="title">连锁品牌管理</span>
          </div>
          <div class="header-right">
            <el-input
              v-model="queryParams.content"
              placeholder="品牌名称/联系人"
              class="search-input"
              prefix-icon="Search"
              clearable
              @keyup.enter="handleQuery"
            />
            <el-input
              v-model="queryParams.address"
              placeholder="搜索地址"
              class="search-input"
              prefix-icon="Location"
              clearable
              @keyup.enter="handleQuery"
            />
            <el-select v-model="queryParams.status" placeholder="状态" class="status-select" clearable @change="handleQuery">
              <el-option label="正常" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:tenant:add']">新增品牌</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="tenantList" style="width: 100%" :header-cell-style="{ background: '#f8f9fb', color: '#606266' }">
        <el-table-column label="Logo" align="center" width="100">
          <template #default="scope">
            <div class="logo-wrapper">
              <image-preview :src="scope.row.logoUrl" :width="40" :height="40" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="品牌名称" prop="companyName" min-width="150" />
        <el-table-column label="商户账号" prop="username" min-width="120" />
        <el-table-column label="联系人" prop="contactUserName" width="100" />
        <el-table-column label="联系电话" prop="contactPhone" width="130" />
<!--        <el-table-column label="旗下门店数" align="center" width="120" sortable>-->
<!--          <template #default="scope">-->
<!--            <span class="count-text">{{ scope.row.storeCount || 0 }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="总部地址" prop="address" min-width="180" show-overflow-tooltip />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-if="checkPermi(['system:tenant:changeStatus'])"
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            />
            <el-tag v-else :type="scope.row.status === '0' ? 'success' : 'danger'" size="small" effect="light" class="status-tag">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="品牌简介" prop="intro" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" align="right" width="220" fixed="right">
          <template #default="scope">
            <div class="op-btns">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:tenant:edit']">编辑</el-button>
              <el-button link type="primary" @click="handleResetPwd(scope.row)" v-hasPermi="['system:tenant:edit']">重置密码</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['system:tenant:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 添加或修改品牌对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="品牌名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUserName">
          <el-input v-model="form.contactUserName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="管理员账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入管理员账号" maxlength="30" />
        </el-form-item>
        <el-form-item v-if="!form.id" label="管理员密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入管理员密码" maxlength="20" />
        </el-form-item>
        <el-form-item label="总部地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入总部地址" />
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="form.intro" type="textarea" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="LOGO" prop="logo">
          <image-upload v-model="form.logo" :limit="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPwdDialog.visible" :title="resetPwdDialog.title" width="400px" append-to-body>
      <el-form ref="resetPwdFormRef" :model="resetPwdForm" :rules="resetPwdRules" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPwdForm.newPassword" type="password" placeholder="请输入新密码" maxlength="20" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetPwdDialog.visible = false">取 消</el-button>
          <el-button :loading="resetPwdButtonLoading" type="primary" @click="submitResetPwdForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tenant" lang="ts">
import {
  listTenant,
  getTenant,
  delTenant,
  addTenant,
  updateTenant,
  changeTenantStatus,
  resetTenantAdminPwd
} from '@/api/system/tenant';
import { selectTenantPackage } from '@/api/system/tenantPackage';
import { useUserStore } from '@/store/modules/user';
import { checkPermi } from '@/utils/permission';
import { TenantForm, TenantQuery, TenantVO } from '@/api/system/tenant/types';
import { TenantPkgVO } from '@/api/system/tenantPackage/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();

const tenantList = ref<TenantVO[]>([]);
const packageList = ref<TenantPkgVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const tenantFormRef = ref<ElFormInstance>();
const resetPwdFormRef = ref<ElFormInstance>();

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

const resetPwdDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const resetPwdButtonLoading = ref(false);
const resetPwdForm = ref({
  id: undefined as number | undefined,
  newPassword: ''
});
const resetPwdRules = {
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 5, max: 20, message: '新密码长度必须介于 5 和 20 之间', trigger: 'blur' }
  ]
};

const initFormData: TenantForm = {
  id: undefined,
  tenantId: undefined,
  contactUserName: '',
  contactPhone: '',
  username: '',
  password: '',
  companyName: '',
  licenseNumber: '',
  domain: '',
  address: '',
  intro: '',
  remark: '',
  packageId: '',
  expireTime: '',
  accountCount: -1,
  status: '0',
  logo: undefined
};
const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    content: '',
    address: '',
    status: undefined
  },
  rules: {
    contactUserName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
    contactPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
    username: [
      { required: true, message: '用户名不能为空', trigger: 'blur' },
      { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
    ]
  }
});

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

/** 查询品牌列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenant(queryParams.value);
  tenantList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 状态修改 */
const handleStatusChange = async (row: TenantVO) => {
  let text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.companyName + '"品牌吗？');
    await changeTenantStatus(row.id, row.tenantId, row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch (err) {
    row.status = row.status === '0' ? '1' : '0';
  }
};

/** 搜索及重置逻辑由 handleQuery 统一处理 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加品牌';
};

/** 修改按钮操作 */
const handleUpdate = async (row: TenantVO) => {
  reset();
  const res = await getTenant(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改品牌';
};

/** 重置密码按钮操作 */
const handleResetPwd = (row: TenantVO) => {
  resetPwdForm.value.id = row.id as any;
  resetPwdForm.value.newPassword = '';
  resetPwdDialog.visible = true;
  resetPwdDialog.title = '重置管理员密码';
  nextTick(() => {
    resetPwdFormRef.value?.clearValidate();
  });
};

/** 提交按钮 */
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateTenant(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addTenant(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 提交重置密码按钮 */
const submitResetPwdForm = () => {
  resetPwdFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      resetPwdButtonLoading.value = true;
      try {
        await resetTenantAdminPwd(resetPwdForm.value);
        proxy?.$modal.msgSuccess('密码重置成功');
        resetPwdDialog.visible = false;
      } finally {
        resetPwdButtonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: TenantVO) => {
  await proxy?.$modal.confirm(`是否确认删除品牌"${row.companyName}"？`);
  loading.value = true;
  await delTenant(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.page-container {
  padding: 20px;
  background-color: #f5f7f9;
  min-height: 100%;
}

.table-card {
  border: none;
  border-radius: 8px;

  :deep(.el-card__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.header-right {
  display: flex;
  gap: 12px;

  .search-input {
    width: 200px;

    :deep(.el-input__wrapper) {
      background-color: #f4f5f7;
      box-shadow: none;
      border: 1px solid transparent;

      &:hover, &.is-focus {
        border-color: #409eff;
        background-color: #fff;
      }
    }
  }

  .status-select {
    width: 120px;
    :deep(.el-input__wrapper) {
      background-color: #f4f5f7;
      box-shadow: none;
    }
  }
}

.logo-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
}

.count-text {
  font-weight: 600;
  color: #606266;
}

.status-tag {
  border: none;
  font-weight: 500;
}

.op-btns {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  --el-table-border-color: #f0f0f0;

  th.el-table__cell {
    font-weight: 600;
  }

  td.el-table__cell {
    padding: 12px 0;
  }
}
</style>
