<script setup lang="ts">
import { computed, onMounted, reactive, ref, useTemplateRef } from 'vue';
import { message } from 'ant-design-vue';
import 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 { getDownloadLogo, getOrganizationAllList, getOrgInfo } from '@/api';
import { OperatePermission } from '@/utils/permission-type';

import EstablishOrganization from '../create-customer/EstablishOrganization.vue';

import type { FormInstance } from 'ant-design-vue';
import type { CreateCustomer, FormRules, OrganizationListItem, RegisterGatewayForm } from '@/types';

const { booleanPermission } = useUserInfoStore();
const organizationOpen = ref<boolean>(false);
const establishOrganizationRef = useTemplateRef('establishOrganization');
const organizationRefs = ref<FormInstance>();
const organizationList = ref<OrganizationListItem[]>([]);
const orgName = ref<string>('');
const organizationId = ref<number>();
const organizationTitle = ref<boolean>(true);
const { handleRequest } = useRequest();
const modalComponentRef = useTemplateRef('modalComponent');
const useForm = reactive<CreateCustomer>({
  orgName: '',
  logo: '',
  themeColor: '#32bac0',
  id: undefined,
  imageUrl: '',
  selectedColor: '#e2550d',
  leaseTerm: [dayjs(), dayjs()],
  stationsNumber: 0,
  dataValidityPeriod: '',
});

const organizationColumns = [
  {
    title: t('organizationManage.organizationName'),
    dataIndex: 'orgName',
    key: 'orgName',
    ellipsis: true,
  },
  {
    title: t('organizationManage.parentOrganization'),
    dataIndex: 'parentOrgName',
    key: 'parentOrgName',
    ellipsis: true,
  },
  {
    title: t('organizationManage.organizationDescription'),
    dataIndex: 'remark',
    key: 'remark',
    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.operation'),
    dataIndex: 'action',
    key: 'action',
    width: 80,
  },
];
const rules = computed<FormRules<RegisterGatewayForm>>(() => {
  return {
    orgName: [
      {
        required: true,
        message: t('common.cannotEmpty'),
        trigger: 'change',
      },
    ],
    leaseTerm: [
      {
        required: true,
        message: t('common.cannotEmpty'),
        trigger: 'change',
      },
    ],
    stationsNumber: [
      {
        required: true,
        message: t('common.cannotEmpty'),
        trigger: 'change',
      },
    ],
    dataValidityPeriod: [
      {
        required: true,
        message: t('common.cannotEmpty'),
        trigger: 'change',
      },
    ],
  };
});
const addOrganization = () => {
  organizationOpen.value = true;
  organizationTitle.value = true;
  useForm.id = undefined;
  useForm.orgName = '';
  useForm.themeColor = '#32BAC0';
  useForm.logo = '';
  useForm.leaseTerm = [dayjs(), dayjs()];
  useForm.dataValidityPeriod = '';
  useForm.stationsNumber = 0;
  useForm.selectedColor = '#e2550d';
  useForm.imageUrl = '';
};
const addQuery = () => {
  getOrganizationAll();
};
const addReset = () => {
  orgName.value = '';
  getOrganizationAll();
};

const organizationEditor = (id: number) => {
  organizationOpen.value = true;
  organizationTitle.value = false;
  handleRequest(async () => {
    const { id: OrgId, orgName, themeColor, logo, endTenancy, startTenancy, dataValidityPeriod } = await getOrgInfo(id);
    if (logo) {
      const data = await getDownloadLogo(logo);
      useForm.imageUrl = URL.createObjectURL(data as Blob);
    }
    const colorList = ['#32BAC0', '#256AFE', '#00A94D', '#7866FF'];
    if (colorList.includes(themeColor)) {
      useForm.themeColor = themeColor;
      useForm.selectedColor = '#e2550d';
    } else {
      useForm.selectedColor = themeColor;
      useForm.themeColor = themeColor;
    }
    useForm.id = OrgId;
    useForm.orgName = orgName;

    useForm.logo = logo;
    useForm.leaseTerm = [dayjs(startTenancy, 'YYYY-MM-DD'), dayjs(endTenancy, 'YYYY-MM-DD')];
    useForm.dataValidityPeriod = dataValidityPeriod;
  });
};
// const organizationDelete = (id: number) => {
//   organizationId.value = id;
//   modalComponentRef.value?.showView();
// };
const clickOrganizationChange = () => {
  getOrganizationAll();
};
const cancelOrganization = () => {
  organizationOpen.value = false;
};
const saveOrganization = async () => {
  try {
    await Promise.all([organizationRefs.value?.validate() || Promise.resolve()]);
    await establishOrganizationRef.value?.finish?.();
    if (organizationTitle.value) {
      message.success(t('common.addSuccess'));
    } else {
      message.success(t('common.editSuccess'));
    }
    organizationOpen.value = false;
    getOrganizationAll();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (err) {
    /* empty */
  }
};
const getOrganizationAll = () => {
  handleRequest(async () => {
    organizationList.value = await getOrganizationAllList(orgName.value);
  });
};

const confirm = () => {
  handleRequest(async () => {
    if (organizationId.value) {
      modalComponentRef.value?.hideView();
    }
  });
};

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

<template>
  <div>
    <AFlex justify="space-between" class="div-bottom">
      <div class="text-top">{{ t('navigation.organizationManage') }}</div>
      <AFlex align="center">
        <!--<div class="text-restriction">还可创建1个</div> -->
        <AButton
          type="primary"
          class="icon-button"
          @click="addOrganization"
          v-if="booleanPermission(OperatePermission.新增组织)"
        >
          <AFlex align="center">
            <SvgIcon name="plus" />
            <span> {{ t('common.add') }} </span>
          </AFlex>
        </AButton>
      </AFlex>
    </AFlex>
    <AFlex>
      <OrganizationalStructure @change="clickOrganizationChange" />
      <div class="organization-div">
        <AFlex justify="space-between" class="div-bottom">
          <AFlex align="center">
            <div class="organization-content-text">{{ t('common.search') }}</div>
            <AInput
              v-model:value="orgName"
              class="input-width"
              :placeholder="t('organizationManage.pleaseEnterOrganizationName')"
            />
          </AFlex>
          <div>
            <AButton type="primary" @click="addQuery"> {{ t('common.query') }} </AButton>
            <AButton class="button-left" type="primary" ghost @click="addReset"> {{ t('common.reset') }} </AButton>
          </div>
        </AFlex>
        <div class="organization-table">
          <ATable :columns="organizationColumns" :data-source="organizationList" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <SvgIcon
                  v-if="booleanPermission(OperatePermission.编辑组织)"
                  @click="organizationEditor(record.id)"
                  class="icon-style"
                  name="edit-o"
                />
                <!-- <SvgIcon @click="organizationDelete(record.id)" class="icon-style" name="delete" /> -->
              </template>
            </template>
          </ATable>
        </div>
      </div>
    </AFlex>
    <AModal
      class="organization-modal"
      v-model:open="organizationOpen"
      :title="organizationTitle ? t('common.add') : t('common.editor')"
      width="920px"
      :mask-closable="false"
      :footer="null"
    >
      <AForm ref="organizationRefs" class="organization-form" :model="useForm" label-align="left" :rules="rules">
        <EstablishOrganization
          v-if="organizationOpen"
          ref="establishOrganization"
          :form="useForm"
          :steps="[]"
          :step-index="2"
          :go-to-step="() => {}"
        />
      </AForm>

      <AFlex justify="flex-end" class="footer">
        <AButton type="primary" ghost @click="cancelOrganization">{{ $t('common.cancel') }}</AButton>
        <AButton type="primary" class="dev-left" @click="saveOrganization">{{ 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>
.organization-table {
  height: calc(100vh - 194px);
  overflow: auto;
}

.footer {
  margin-top: 24px;
}

.dev-left {
  margin-left: 16px;
}

.icon-style {
  margin-right: 17px;
  font-size: 24px;
  color: var(--antd-color-primary-hover);
  cursor: pointer;
}

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

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

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

.input-width {
  width: 256px;
}

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

.text-restriction {
  margin-right: 16px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: rgb(0 0 0 / 65%);
  text-align: right;
}

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