<template>
  <div class="p-2">
    <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" label-width="140px">
            <el-form-item :label="t('tenant.search.tenantId')" prop="tenantId">
              <el-input v-model="queryParams.tenantId" :placeholder="t('tenant.search.tenantIdPlaceholder')" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item :label="t('tenant.search.contactUserName')" prop="contactUserName">
              <el-input v-model="queryParams.contactUserName" :placeholder="t('tenant.search.contactUserNamePlaceholder')" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item :label="t('tenant.search.contactPhone')" prop="contactPhone">
              <el-input v-model="queryParams.contactPhone" :placeholder="t('tenant.search.contactPhonePlaceholder')" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item :label="t('tenant.search.companyName')" prop="companyName">
              <el-input v-model="queryParams.companyName" :placeholder="t('tenant.search.companyNamePlaceholder')" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">{{ t('tenant.search.search') }}</el-button>
              <el-button icon="Refresh" @click="resetQuery">{{ t('tenant.search.reset') }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:add']" type="primary" plain icon="Plus" @click="handleAdd">{{ t('tenant.button.add') }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >{{ t('tenant.button.edit') }}</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">
              {{ t('tenant.button.delete') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:tenant:export']" type="warning" plain icon="Download" @click="handleExport">{{ t('tenant.button.export') }}</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button v-if="userId === 1" type="success" plain icon="Refresh" @click="handleSyncTenantDict">同步租户字典</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button v-if="userId === 1" type="success" plain icon="Refresh" @click="handleSyncTenantConfig">同步租户参数配置</el-button>-->
<!--          </el-col>-->
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="tenantList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" :label="t('tenant.table.id')" align="center" prop="id" />
        <el-table-column :label="t('tenant.table.tenantId')" align="center" prop="tenantId" />
        <el-table-column :label="t('tenant.table.contactUserName')" align="center" prop="contactUserName" />
        <el-table-column :label="t('tenant.table.contactPhone')" align="center" prop="contactPhone" />
        <el-table-column :label="t('tenant.table.companyName')" align="center" prop="companyName" />
        <el-table-column :label="t('tenant.table.licenseNumber')" align="center" prop="licenseNumber" />
        <el-table-column :label="t('tenant.table.expireTime')" align="center" prop="expireTime" width="180">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('tenant.table.status')" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column width="150" :label="t('tenant.table.operation')" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip :content="t('tenant.tooltip.edit')" placement="top">
              <el-button v-hasPermi="['system:tenant:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip :content="t('tenant.tooltip.syncPackage')" placement="top">
              <el-button v-hasPermi="['system:tenant:edit']" link type="primary" icon="Refresh" @click="handleSyncTenantPackage(scope.row)">
              </el-button>
            </el-tooltip>
            <el-tooltip :content="t('tenant.tooltip.delete')" placement="top">
              <el-button v-hasPermi="['system:tenant:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改企业对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="180px">
        <el-form-item :label="t('tenant.form.companyName')" prop="companyName">
          <el-input v-model="form.companyName" :placeholder="t('tenant.form.companyNamePlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.contactUserName')" prop="contactUserName">
          <el-input v-model="form.contactUserName" :placeholder="t('tenant.form.contactUserNamePlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.contactPhone')" prop="contactPhone">
          <el-input v-model="form.contactPhone" :placeholder="t('tenant.form.contactPhonePlaceholder')" />
        </el-form-item>
        <el-form-item v-if="!form.id" :label="t('tenant.form.username')" prop="username">
          <el-input v-model="form.username" :placeholder="t('tenant.form.usernamePlaceholder')" maxlength="30" />
        </el-form-item>
        <el-form-item v-if="!form.id" :label="t('tenant.form.password')" prop="password">
          <el-input v-model="form.password" type="password" :placeholder="t('tenant.form.passwordPlaceholder')" maxlength="20" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.packageId')" prop="packageId">
          <el-select v-model="form.packageId" :disabled="!!form.tenantId" :placeholder="t('tenant.form.packageIdPlaceholder')" clearable style="width: 100%">
            <el-option v-for="item in packageList" :key="item.packageId" :label="item.packageName" :value="item.packageId" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('tenant.form.expireTime')" prop="expireTime">
          <el-date-picker v-model="form.expireTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" :placeholder="t('tenant.form.expireTimePlaceholder')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="t('tenant.form.accountCount')" prop="accountCount">
          <el-input v-model="form.accountCount" :placeholder="t('tenant.form.accountCountPlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.domain')" prop="domain">
          <el-input v-model="form.domain" :placeholder="t('tenant.form.domainPlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.address')" prop="address">
          <el-input v-model="form.address" :placeholder="t('tenant.form.addressPlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.licenseNumber')" prop="licenseNumber">
          <el-input v-model="form.licenseNumber" :placeholder="t('tenant.form.licenseNumberPlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.intro')" prop="intro">
          <el-input v-model="form.intro" type="textarea" :placeholder="t('tenant.form.introPlaceholder')" />
        </el-form-item>
        <el-form-item :label="t('tenant.form.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="t('tenant.form.remarkPlaceholder')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">{{ t('tenant.button.submit') }}</el-button>
          <el-button @click="cancel">{{ t('tenant.button.cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tenant" lang="ts">
import {
  listTenant,
  getTenant,
  delTenant,
  addTenant,
  updateTenant,
  changeTenantStatus,
  syncTenantPackage,
  syncTenantDict,
  syncTenantConfig
} from '@/api/system/tenant';
import { selectTenantPackage } from '@/api/system/tenantPackage';
import { useUserStore } from '@/store/modules/user';
import { TenantForm, TenantQuery, TenantVO } from '@/api/system/tenant/types';
import { TenantPkgVO } from '@/api/system/tenantPackage/types';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userStore = useUserStore();
const userId = ref(userStore.userId);
const tenantList = ref<TenantVO[]>([]);
const packageList = ref<TenantPkgVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const tenantFormRef = ref<ElFormInstance>();

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

const initFormData: TenantForm = {
  id: undefined,
  tenantId: undefined,
  contactUserName: '',
  contactPhone: '',
  username: '',
  password: '',
  companyName: '',
  licenseNumber: '',
  domain: '',
  address: '',
  intro: '',
  remark: '',
  packageId: '',
  expireTime: '',
  accountCount: 0,
  status: '0'
};
const data = reactive<PageData<TenantForm, TenantQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: '',
    contactUserName: '',
    contactPhone: '',
    companyName: ''
  },
  rules: {
    id: [{ required: true, message: t('tenant.rule.idRequired'), trigger: 'blur' }],
    tenantId: [{ required: true, message: t('tenant.rule.tenantIdRequired'), trigger: 'blur' }],
    contactUserName: [{ required: true, message: t('tenant.rule.contactUserNameRequired'), trigger: 'blur' }],
    contactPhone: [{ required: true, message: t('tenant.rule.contactPhoneRequired'), trigger: 'blur' }],
    companyName: [{ required: true, message: t('tenant.rule.companyNameRequired'), trigger: 'blur' }],
    username: [
      { required: true, message: t('tenant.rule.usernameRequired'), trigger: 'blur' },
      { min: 2, max: 20, message: t('tenant.rule.usernameLength'), trigger: 'blur' }
    ],
    password: [
      { required: true, message: t('tenant.rule.passwordRequired'), trigger: 'blur' },
      { min: 5, max: 20, message: t('tenant.rule.passwordLength'), trigger: 'blur' }
    ]
  }
});

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

/** 查询所有租户套餐 */
const getTenantPackage = async () => {
  const res = await selectTenantPackage();
  packageList.value = res.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) => {
  const text = row.status === '0' ? t('tenant.message.statusEnable') : t('tenant.message.statusDisable');
  try {
    await proxy?.$modal.confirm(t('tenant.message.statusChangeConfirm', { text, name: row.companyName }));
    await changeTenantStatus(row.id, row.tenantId, row.status);
    proxy?.$modal.msgSuccess(t('tenant.message.statusChangeSuccess', { text }));
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getTenantPackage();
  dialog.visible = true;
  dialog.title = t('tenant.dialog.add');
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TenantVO) => {
  reset();
  await getTenantPackage();
  const _id = row?.id || ids.value[0];
  const res = await getTenant(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = t('tenant.dialog.edit');
};

/** 提交按钮 */
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(t('tenant.message.operationSuccess'));
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenantVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm(t('tenant.message.deleteConfirm', { ids: _ids }));
  loading.value = true;
  await delTenant(_ids).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess(t('tenant.message.deleteSuccess'));
};

/** 同步企业套餐按钮操作 */
const handleSyncTenantPackage = async (row: TenantVO) => {
  try {
    await proxy?.$modal.confirm(t('tenant.message.syncPackageConfirm', { tenantId: row.tenantId }));
    loading.value = true;
    await syncTenantPackage(row.tenantId, row.packageId);
    await getList();
    proxy?.$modal.msgSuccess(t('tenant.message.syncSuccess'));
  } catch {
    return;
  } finally {
    loading.value = false;
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/tenant/export',
    {
      ...queryParams.value
    },
    `tenant_${new Date().getTime()}.xlsx`
  );
};

/**同步企业字典*/
const handleSyncTenantDict = async () => {
  await proxy?.$modal.confirm(t('tenant.message.syncDictConfirm'));
  const res = await syncTenantDict();
  proxy?.$modal.msgSuccess(res.msg);
};

/**同步企业参数配置*/
const handleSyncTenantConfig = async () => {
  await proxy?.$modal.confirm(t('tenant.message.syncConfigConfirm'));
  const res = await syncTenantConfig();
  proxy?.$modal.msgSuccess(res.msg);
};

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