<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 { t } from '@/i18n';
import { addAccount, batchDeleteAccount, getFindRolesByOrgIds, getUserPageList, updateAccount } from '@/api';

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 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: '手机号',
    dataIndex: 'mobile',
    key: 'mobile',
    ellipsis: true,
  },
  {
    title: '姓名',
    dataIndex: 'userName',
    key: 'userName',
    ellipsis: true,
  },
  {
    title: '角色',
    dataIndex: 'roleName',
    key: 'roleName',
    ellipsis: true,
  },
  {
    title: '创建日期',
    dataIndex: 'startTenancy',
    key: 'startTenancy',
    ellipsis: true,
  },
  {
    title: '到期日期',
    dataIndex: 'endTenancy',
    key: 'endTenancy',
    ellipsis: true,
  },
  {
    title: '状态',
    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('手机号格式错误');
        }
        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[]);
    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 = '';
  }
  console.log(searchContent.value);
  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,
          });
        } 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,
          });
        }
        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">账号管理</div>
      <div>
        <AButton class="icon-button default-button" @click="addDelete">
          <AFlex align="center">
            <SvgIcon name="delete" />
            <span>删除</span>
          </AFlex>
        </AButton>
        <AButton type="primary" class="icon-button button-monitoring" @click="addOpenAccount">
          <AFlex align="center">
            <SvgIcon name="plus" />
            <span> 添加 </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">搜索</div>
            <AInput v-model:value="searchContent" class="input-width" placeholder="请输入手机号、姓名" />
          </AFlex>
          <AFlex align="center" class="margin-bottom">
            <div class="account-content-text">角色</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">创建日期</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">状态</div>
            <ASelect
              class="input-width"
              v-model:value="accountPageParam.enabled"
              :placeholder="$t('common.plzSelect')"
              :allow-clear="true"
            >
              <ASelectOption value="1">正常</ASelectOption>
              <ASelectOption value="0">停用</ASelectOption>
            </ASelect>
          </AFlex>
        </AFlex>
        <AFlex class="margin-bottom" justify="flex-end">
          <AButton type="primary" @click="addQuery"> 查询 </AButton>
          <AButton class="default-button margin-left" @click="addReset"> 重置 </AButton>
        </AFlex>
        <ATable
          :row-selection="{
            type: 'checkbox',
            selectedRowKeys: accountKeys,
            onChange: accountChange,
          }"
          row-key="id"
          :columns="accountColumns"
          :data-source="accountList"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'mobile'">
              <div @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">启用中</div>
              <div v-else class="tag-style default">停用</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 ? '添加' : '编辑'"
      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="姓名" name="userName">
            <AInput class="input-width" v-model:value="accountForm.userName" placeholder="请输入" />
          </AFormItem>
          <AFormItem label="手机号" name="mobile">
            <AInputNumber class="input-width" v-model:value="accountForm.mobile" placeholder="请输入" />
          </AFormItem>
          <AFormItem label="角色" 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="到期日期" name="accountTerm">
            <ARangePicker
              v-model:value="accountForm.accountTerm"
              class="input-width"
              :allow-clear="false"
              :separator="$t('common.to')"
            />
          </AFormItem>
          <AFormItem label="密码" name="password">
            <AInput class="input-width" v-model:value="accountForm.password" placeholder="默认密码8个0" />
          </AFormItem>
          <AFormItem label="启用" 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>
