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

import ConfirmModal from '@/components/ConfirmModal.vue';
import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import {
  addDeviceGroup,
  addDeviceGroupUpdate,
  deleteDeviceGroup,
  getDeviceGroupList,
  getPageList,
  groupList,
} from '@/api';

import type { DefaultOptionType, SelectValue } from 'ant-design-vue/es/select';
import type { ValueType } from 'ant-design-vue/es/vc-cascader/Cascader';
import type {
  DeviceGroup,
  DeviceGroupItem,
  EquipmentInformationForm,
  EquipmentTypeItem,
  UseGuideStepItemProps,
} from '@/types';

const props = defineProps<UseGuideStepItemProps<EquipmentInformationForm>>();

const { handleRequest } = useRequest();

const modalComponentRef = useTemplateRef('modalComponent');
const deviceGroup = ref<DeviceGroupItem[]>([]);
const equipmentType = ref<EquipmentTypeItem[]>([]);
const addGroupingOpen = ref<boolean>(false);
const editorGroupName = ref<string>('');
const titleGrouping = ref<boolean>(true);
const groupName = ref<string>('');
const parentId = ref<number | undefined>(undefined);
const editorParentId = ref<number[]>([]);
const oneDeviceGroup = ref<DeviceGroup[]>([]);

const selectTypeRquipment = (value: SelectValue, option: DefaultOptionType) => {
  props.form.imgUrl = option.imgUrl;
};

const imgUrl = computed(() => {
  if (props.form.imgUrl) {
    return import.meta.env.VITE_IMG_API + '/' + props.form.imgUrl;
  } else {
    return '';
  }
});

const editorGroupingName = () => {
  if (!props.form.deviceData || props.form.deviceData.length === 0) {
    return message.warning(t('createDevice.pleaseEquipmentGroup'));
  }
  addGroupingOpen.value = true;
  titleGrouping.value = false;
  groupName.value = editorGroupName.value;
};

const addGroupingName = () => {
  addGroupingOpen.value = true;
  titleGrouping.value = true;
  groupName.value = '';
};

const groupingNameOk = () => {
  if (titleGrouping.value) {
    if (!parentId.value) {
      return message.warning(t('createDevice.pleaseSelectSuperiorGroup'));
    }
    if (!groupName.value) {
      return message.warning(t('createDevice.pleaseEnterGroupName'));
    }
    handleRequest(async () => {
      await addDeviceGroup({
        groupName: groupName.value,
        parentId: parentId.value,
      });
      getDeviceGroup();
      addGroupingOpen.value = false;
    });
  } else {
    if (!groupName.value) {
      return message.warning(t('createDevice.pleaseEnterNameSecondaryGroup'));
    }
    handleRequest(async () => {
      await addDeviceGroupUpdate({
        id: editorParentId.value[1],
        groupName: groupName.value,
        parentId: editorParentId.value[0],
      });
      getDeviceGroup();
      addGroupingOpen.value = false;
    });
  }
};

const confirm = () => {
  handleRequest(async () => {
    if (editorParentId.value.length === 2) {
      await deleteDeviceGroup(editorParentId.value[1]);
      modalComponentRef.value?.hideView();
      addGroupingOpen.value = false;
      props.form.deviceData = [];
      getDeviceGroup();
    }
  });
};

const getDeviceGroup = () => {
  handleRequest(async () => {
    deviceGroup.value = await getPageList();
  });
};

const groupingNameDelete = () => {
  modalComponentRef.value?.showView();
};

const chooseGroup = (value: ValueType, selectOptions: DefaultOptionType[] | DefaultOptionType[][]) => {
  if (selectOptions && selectOptions.length === 2) {
    editorGroupName.value = (selectOptions as DeviceGroupItem[])[1].groupName;
    editorParentId.value = value as number[];
  }
};

onMounted(() => {
  getDeviceGroup();
  handleRequest(async () => {
    equipmentType.value = await groupList({
      dataType: 1,
    });
    oneDeviceGroup.value = await getDeviceGroupList({
      parentId: -1,
      haveChild: false,
    });
  });
});
</script>

<template>
  <div>
    <AFlex>
      <div class="grouping-width">
        <AFormItem :label="$t('createDevice.equipmentGroup')" name="deviceData">
          <AFlex align="center">
            <ACascader
              class="equipment-type"
              v-model:value="form.deviceData"
              :field-names="{ label: 'groupName', value: 'id', children: 'deviceGroupChilds' }"
              :options="deviceGroup"
              :placeholder="$t('common.plzSelect')"
              @change="chooseGroup"
            />
            <div @click="editorGroupingName">
              <AFlex justify="center" align="center" class="button-flex">
                <SvgIcon name="edit-o" />
              </AFlex>
            </div>
            <div @click="addGroupingName">
              <AFlex justify="center" align="center" class="button-flex button-plus">
                <SvgIcon name="plus" />
              </AFlex>
            </div>
          </AFlex>
        </AFormItem>
        <AFormItem :label="$t('setupProtocol.deviceType')" name="deviceType">
          <ASelect
            class="equipment-type"
            v-model:value="form.deviceType"
            :options="equipmentType"
            :field-names="{ label: 'dataName', value: 'id' }"
            :placeholder="$t('common.plzSelect')"
            @change="selectTypeRquipment"
          />
        </AFormItem>
        <AFormItem :label="$t('createDevice.deviceName')" name="deviceName">
          <AFlex class="flex-width" align="center">
            <AInput :placeholder="$t('common.pleaseEnter')" class="equipment-type" v-model:value="form.deviceName" />
            <ATooltip placement="top">
              <template #title>
                <span>{{ $t('createDevice.suggestion') }}</span>
              </template>
              <div>
                <SvgIcon class="information-prompt" name="exclamation-circle-o" />
              </div>
            </ATooltip>
          </AFlex>
        </AFormItem>
      </div>
      <div v-if="imgUrl">
        <img class="information-img" referrerpolicy="no-referrer" :src="imgUrl" />
      </div>
    </AFlex>

    <AModal
      v-model:open="addGroupingOpen"
      :title="titleGrouping ? t('createDevice.newlyAddedGroup') : t('createDevice.editGroup')"
      :footer="null"
      width="460px"
      :mask-closable="false"
      :keyboard="false"
    >
      <AFlex v-if="titleGrouping" align="center" class="grouping-name">
        <div class="grouping-text">{{ $t('createDevice.superiorGroup') }}</div>

        <ASelect
          class="equipment-type"
          v-model:value="parentId"
          :options="oneDeviceGroup"
          :field-names="{ label: 'groupName', value: 'id' }"
          :placeholder="$t('common.plzSelect')"
        />
      </AFlex>
      <AFlex align="center" class="grouping-name">
        <div class="grouping-text">
          {{ titleGrouping ? t('createDevice.groupName') : t('createDevice.secondaryGrouping') }}
        </div>
        <AInput class="equipment-type" v-model:value="groupName" :placeholder="$t('common.pleaseEnter')" />
      </AFlex>

      <AFlex justify="flex-end" class="footer">
        <AButton v-if="!titleGrouping" class="default-button" @click="groupingNameDelete">{{
          $t('common.delete')
        }}</AButton>
        <AButton class="default-button cancel-button button-width" @click="addGroupingOpen = false">{{
          $t('common.cancel')
        }}</AButton>
        <AButton class="button-width" type="primary" @click="groupingNameOk">{{ $t('common.confirm') }}</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>
.button-width {
  width: 76px;
}

.cancel-button {
  margin: 0 16px;
}

.footer {
  margin-top: 24px;
}

.grouping-name {
  margin-top: 24px;
}

.grouping-text {
  width: 72px;
}

.grouping-width {
  width: 440px;
}

.button-flex {
  width: 32px;
  height: 32px;
  margin-left: 16px;
  cursor: pointer;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.button-plus {
  margin-left: 12px !important;
  font-size: 16px;
}

.flex-width {
  width: 350px;
}

.information-prompt {
  width: 14px;
  height: 14px;
  margin-left: 12px;
  color: #999;
  cursor: pointer;
}

.information-img {
  width: 180px;
  height: 208px;
  margin-left: 20px;
}

.equipment-type {
  width: 256px;
}
</style>
