<script setup lang="ts">
import { ref, useTemplateRef } from 'vue';
import { message } from 'ant-design-vue';
import dayjs, { Dayjs } from 'dayjs';

import ConfirmModal from '@/components/ConfirmModal.vue';
import OrganizationalStructure from '@/components/OrganizationalStructure.vue';
import { useRequest } from '@/hooks/request';
import { useUserInfoStore } from '@/stores/user-info';
import { t } from '@/i18n';
import { addAccount, batchDeleteAccount, getFindRolesByOrgIds, getUserPageList, updateAccount } from '@/api';
import { OperatePermission } from '@/utils/permission-type';

import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import type { Key } from 'ant-design-vue/es/table/interface';
import type { AccountForm, CharacterPageItem, UserPageItem, UserPageParams } from '@/types';

const { booleanPermission } = useUserInfoStore();
const modalComponentRef = useTemplateRef('modalComponent');
const { handleRequest } = useRequest();
const accountKeys = ref<Key[]>([]);
const searchContent = ref<string>('');
const accountTerm = ref<[Dayjs, Dayjs]>();
const orgId = ref<number>();
const formRef = ref<FormInstance>();
const titleAccount = ref<boolean>(true);
const accountId = ref<number>(0);
const accountPageParam = ref<UserPageParams>({
  pageIndex: 1,
  pageSize: 10,
  userName: '',
  mobile: '',
  startTenancy: '',
  endTenancy: '',
  enabled: undefined,
  orgId: undefined,
  roleId: undefined,
});
const accountTotal = ref<number>();
const accountOpen = ref<boolean>(false);
const characterPageList = ref<CharacterPageItem[]>([]);
const accountForm = ref<AccountForm>({
  userName: '',
  mobile: '',
  password: '',
  enabled: true,
  roleId: undefined,
  accountTerm: undefined,
});
const accountList = ref<UserPageItem[]>([]);
const accountColumns = [
  {
    title: t('userManage.mobilePhoneNumber'),
    dataIndex: 'mobile',
    key: 'mobile',
    ellipsis: true,
  },
  {
    title: t('userManage.fullName'),
    dataIndex: 'userName',
    key: 'userName',
    ellipsis: true,
  },
  {
    title: t('userManage.role'),
    dataIndex: 'roleName',
    key: 'roleName',
    ellipsis: true,
  },
  {
    title: t('userManage.createDate'),
    dataIndex: 'startTenancy',
    key: 'startTenancy',
    ellipsis: true,
  },
  {
    title: t('userManage.expiryDate'),
    dataIndex: 'endTenancy',
    key: 'endTenancy',
    ellipsis: true,
  },
  {
    title: t('common.status'),
    dataIndex: 'enabled',
    key: 'enabled',
    ellipsis: true,
  },
];
const rules: Record<string, Rule[]> = {
  userName: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  mobile: [
    { required: true, message: t('common.cannotEmpty'), trigger: 'change' },
    {
      validator: (_rule: unknown, value: string) => {
        if (!isValidPhone(value)) {
          return Promise.reject(t('userManage.mobileNumberFormatError'));
        }
        return Promise.resolve();
      },
    },
  ],
  password: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  enabled: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  roleId: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  accountTerm: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
};
// 手机号校验函数
const isValidPhone = (phone: string): boolean => {
  return /^1[3-9]\d{9}$/.test(phone);
};
const accountChange = (selectedRowKeys: Key[]) => {
  accountKeys.value = selectedRowKeys;
};
const confirm = () => {
  handleRequest(async () => {
    await batchDeleteAccount(accountKeys.value as number[]);

    message.success(t('common.deleteSuccess'));
    getUserList();
    modalComponentRef.value?.hideView();
  });
};
const addDelete = () => {
  if (accountKeys.value.length === 0) {
    return message.warning(t('deviceList.pleaseSelectItemDelete'));
  }
  modalComponentRef.value?.showView();
};
const addOpenAccount = () => {
  accountOpen.value = true;
  titleAccount.value = true;
};
const addCheck = (item: UserPageItem) => {
  accountOpen.value = true;
  titleAccount.value = false;

  const { userName, mobile, roleId, enabled, startTenancy, endTenancy, id } = item;
  accountId.value = id;
  Object.assign(accountForm.value, {
    userName,
    mobile,
    roleId,
    password: '',
    enabled: enabled === 1 ? true : false,
    accountTerm: [dayjs(startTenancy, 'YYYY-MM-DD'), dayjs(endTenancy, 'YYYY-MM-DD')],
  });
};
const addQuery = () => {
  if (accountTerm.value) {
    accountPageParam.value.startTenancy = accountTerm.value[0].format('YYYY-MM-DD');
    accountPageParam.value.endTenancy = accountTerm.value[1].format('YYYY-MM-DD');
  } else {
    accountPageParam.value.startTenancy = '';
    accountPageParam.value.endTenancy = '';
  }
  accountPageParam.value.mobile = searchContent.value;
  accountPageParam.value.userName = searchContent.value;
  accountPageParam.value.pageIndex = 1;
  getUserList();
};

const resetItem = () => {
  searchContent.value = '';
  accountTerm.value = undefined;
  accountPageParam.value.startTenancy = '';
  accountPageParam.value.endTenancy = '';
  accountPageParam.value.pageIndex = 1;
  accountPageParam.value.enabled = undefined;
  accountPageParam.value.roleId = undefined;
  getUserList();
};

const handleClose = () => {
  accountForm.value = {
    userName: '',
    mobile: '',
    password: '',
    enabled: true,
    roleId: undefined,
    accountTerm: undefined,
  };
};
const addReset = () => {
  resetItem();
};
const switchPages = () => {};
const bindingAccount = () => {
  formRef.value
    ?.validate()
    .then(() => {
      handleRequest(async () => {
        const { userName, mobile, password, enabled, roleId, accountTerm } = accountForm.value;
        if (titleAccount.value) {
          await addAccount({
            userName,
            mobile,
            password,
            roleId: roleId as number,
            enabled: enabled ? '1' : '0',
            startTenancy: accountTerm![0].format('YYYY-MM-DD'),
            endTenancy: accountTerm![1].format('YYYY-MM-DD'),
            orgId: orgId.value as number,
          });
          message.success(t('common.addSuccess'));
        } else {
          await updateAccount({
            id: accountId.value,
            userName,
            mobile,
            password,
            roleId: roleId as number,
            enabled: enabled ? '1' : '0',
            startTenancy: accountTerm![0].format('YYYY-MM-DD'),
            endTenancy: accountTerm![1].format('YYYY-MM-DD'),
            orgId: orgId.value as number,
          });
          message.success(t('common.editSuccess'));
        }
        getUserList();

        accountOpen.value = false;
      });
    })
    .catch(() => {});
};

const clickOrganizationChange = (id: number) => {
  orgId.value = id;
  searchContent.value = '';
  accountTerm.value = undefined;
  accountPageParam.value.startTenancy = '';
  accountPageParam.value.endTenancy = '';
  handleRequest(async () => {
    characterPageList.value = await getFindRolesByOrgIds([id]);
    getUserList();
  });
};

const getUserList = () => {
  handleRequest(async () => {
    accountPageParam.value.orgId = orgId.value;
    accountPageParam.value.mobile = searchContent.value;
    accountPageParam.value.userName = searchContent.value;
    const { records, total } = await getUserPageList(accountPageParam.value);
    accountList.value = records;
    accountTotal.value = total;
  });
};
</script>

<template>
  <div>
    <AFlex justify="space-between" class="account-header">
      <div class="text-top">{{ t('userManage.accountManagement') }}</div>
      <div>
        <AButton
          v-if="booleanPermission(OperatePermission.删除账户)"
          class="icon-button default-button"
          @click="addDelete"
        >
          <AFlex align="center">
            <SvgIcon name="delete" />
            <span>{{ t('common.delete') }}</span>
          </AFlex>
        </AButton>
        <AButton
          v-if="booleanPermission(OperatePermission.新增账户)"
          type="primary"
          class="icon-button button-monitoring"
          @click="addOpenAccount"
        >
          <AFlex align="center">
            <SvgIcon name="plus" />
            <span> {{ t('common.add') }} </span>
          </AFlex>
        </AButton>
      </div>
    </AFlex>
    <AFlex>
      <OrganizationalStructure @change="clickOrganizationChange" />
      <div class="account-content">
        <AFlex wrap="wrap" justify="space-between">
          <AFlex align="center" class="margin-bottom">
            <div class="account-content-text">{{ $t('common.search') }}</div>
            <AInput
              v-model:value="searchContent"
              class="input-width"
              :placeholder="t('userManage.pleaseEnterMobileNumber')"
            />
          </AFlex>
          <AFlex align="center" class="margin-bottom">
            <div class="account-content-text">{{ t('userManage.role') }}</div>

            <ASelect
              class="input-width"
              v-model:value="accountPageParam.roleId"
              :options="characterPageList"
              :field-names="{ label: 'roleName', value: 'id' }"
              :placeholder="t('common.plzSelect')"
              :allow-clear="true"
            />
          </AFlex>
          <AFlex align="center" class="margin-bottom">
            <div class="account-content-text">{{ t('userManage.createDate') }}</div>
            <ARangePicker
              v-model:value="accountTerm"
              class="input-width"
              :allow-clear="true"
              :separator="$t('common.to')"
            />
          </AFlex>

          <AFlex align="center" class="margin-bottom">
            <div class="account-content-text">{{ $t('common.status') }}</div>
            <ASelect
              class="input-width"
              v-model:value="accountPageParam.enabled"
              :placeholder="$t('common.plzSelect')"
              :allow-clear="true"
            >
              <ASelectOption value="1">{{ t('envMonitor.normal') }}</ASelectOption>
              <ASelectOption value="0">{{ t('common.deactivated') }}</ASelectOption>
            </ASelect>
          </AFlex>
        </AFlex>
        <AFlex class="margin-bottom" justify="flex-end">
          <AButton type="primary" @click="addQuery"> {{ t('common.query') }} </AButton>
          <AButton class="default-button margin-left" @click="addReset"> {{ t('common.reset') }} </AButton>
        </AFlex>
        <ATable
          :row-selection="
            booleanPermission(OperatePermission.删除账户)
              ? {
                  type: 'checkbox',
                  selectedRowKeys: accountKeys,
                  onChange: accountChange,
                }
              : undefined
          "
          row-key="id"
          :columns="accountColumns"
          :data-source="accountList"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'mobile'">
              <div v-if="!booleanPermission(OperatePermission.编辑账户)">{{ record.mobile }}</div>
              <div v-else @click="addCheck(record as UserPageItem)" class="mobile-phone">{{ record.mobile }}</div>
            </template>
            <template v-if="column.key === 'enabled'">
              <div v-if="record.enabled == 1" class="tag-style success">{{ t('common.activating') }}</div>
              <div v-else class="tag-style default">{{ t('common.deactivated') }}</div>
            </template>
          </template>
        </ATable>
        <br />
        <br />
        <AFlex justify="flex-end" class="footer">
          <APagination
            v-model:current="accountPageParam.pageIndex"
            v-model:page-size="accountPageParam.pageSize"
            :total="accountTotal"
            :show-size-changer="true"
            @change="switchPages"
            show-quick-jumper
            :show-total="(total) => $t('common.pageTotal', { total })"
          />
        </AFlex>
      </div>
    </AFlex>
    <AModal
      v-model:open="accountOpen"
      :title="titleAccount ? t('common.add') : t('common.editor')"
      width="460px"
      :footer="null"
      :mask-closable="false"
      :keyboard="false"
      :after-close="handleClose"
    >
      <AForm
        ref="formRef"
        :colon="false"
        label-align="left"
        :model="accountForm"
        :rules="rules"
        :label-col="{ span: 5 }"
        class="form-style"
      >
        <AFlex :vertical="true">
          <AFormItem :label="t('userManage.fullName')" name="userName">
            <AInput class="input-width" v-model:value="accountForm.userName" :placeholder="t('common.pleaseEnter')" />
          </AFormItem>
          <AFormItem :label="t('userManage.mobilePhoneNumber')" name="mobile">
            <AInputNumber
              class="input-width"
              v-model:value="accountForm.mobile"
              :placeholder="t('common.pleaseEnter')"
            />
          </AFormItem>
          <AFormItem :label="t('userManage.role')" name="roleId">
            <ASelect
              class="input-width"
              v-model:value="accountForm.roleId"
              :options="characterPageList"
              :field-names="{ label: 'roleName', value: 'id' }"
              :placeholder="t('common.plzSelect')"
            />
          </AFormItem>
          <AFormItem :label="t('userManage.expiryDate')" name="accountTerm">
            <ARangePicker
              v-model:value="accountForm.accountTerm"
              class="input-width"
              :allow-clear="false"
              :separator="$t('common.to')"
            />
          </AFormItem>
          <AFormItem :label="t('userManage.password')" name="password">
            <AInput
              class="input-width"
              v-model:value="accountForm.password"
              :placeholder="t('userManage.defaultPassword')"
            />
          </AFormItem>
          <AFormItem :label="t('alarmManage.enable')" name="enabled">
            <ASwitch v-model:checked="accountForm.enabled" />
          </AFormItem>
        </AFlex>
      </AForm>

      <AFlex justify="flex-end">
        <AButton class="button-style" type="primary" ghost @click="accountOpen = false">{{
          $t('common.cancel')
        }}</AButton>
        <AButton class="button-style" type="primary" @click="bindingAccount">{{ $t('common.save') }}</AButton>
      </AFlex>
    </AModal>
    <ConfirmModal
      ref="modalComponent"
      :title="t('common.deleteConfirmation')"
      :description-text="t('common.confirmDeletion')"
      :icon="{ name: 'delete' }"
      :icon-bg-color="'#F56C6C'"
      @confirm="confirm"
    />
  </div>
</template>

<style lang="scss" scoped>
.check-div {
  margin-top: 24px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: #666;
  text-align: justify;
}

.check-text {
  color: #333;
}

.check-div > div {
  margin-bottom: 16px;
}

.check-div .margin-top {
  margin-bottom: 24px;
}

.mobile-phone {
  color: var(--antd-color-primary-hover);
  cursor: pointer;
}

.form-style {
  margin-top: 24px;
}

.button-style {
  width: 76px;
  margin-left: 16px;
}

.default {
  width: 40px;
  color: #666;
  background: #f8f8f8;
  border: 1px solid #e5e5e5;
}

.success {
  width: 52px;
  color: #52c41a;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
}

.tag-style {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  height: 24px;
  font-size: 12px;
  border-radius: 4px;
}

.margin-left {
  margin-left: 12px;
}

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

.input-width {
  width: 256px;
}

.account-content-text {
  width: 56px;
  margin-right: 12px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: rgb(0 0 0 / 85%);
  text-align: right;
}

.account-content {
  width: 100%;
  height: calc(100vh - 80px);
  padding: 24px;
  background: #fff;
  border-radius: 16px;
}

.account-header {
  margin-bottom: 16px;
}

.button-monitoring {
  margin-left: 16px;
}

.text-top {
  font-size: 20px;
  font-style: normal;
  font-weight: 500;
  line-height: 32px;
  color: rgb(0 0 0 / 85%);
  text-align: left;
}
</style>
