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

import ModalGuidance from '@/layout/ModalGuidance.vue';
import ConfirmModal from '@/components/ConfirmModal.vue';
import { useRequest } from '@/hooks/request';
import { useUserInfoStore } from '@/stores/user-info';
import { t } from '@/i18n';
import { deviceDeletion, getPageList, groupList, queryDevicesList } from '@/api';
import { OperatePermission } from '@/utils/permission-type';

import CreateDevice from '../create-device/CreateDevice.vue';

import type { Key } from 'ant-design-vue/es/table/interface';
import type { DeviceGroupItem, DevicesList, DevicesListItem, EquipmentTypeItem } from '@/types';

const devicesColumns = [
  {
    title: t('deviceList.equipmentName'),
    dataIndex: 'deviceName',
    key: 'deviceName',
    ellipsis: true,
  },
  {
    title: t('createDevice.equipmentGroup'),
    dataIndex: 'groupName',
    key: 'groupName',
    ellipsis: true,
  },
  {
    title: t('deviceList.equipmentCategory'),
    dataIndex: 'deviceTypeName',
    key: 'deviceTypeName',
    ellipsis: true,
  },
  {
    title: t('deviceList.operatingStatus'),
    dataIndex: 'runningStatus',
    key: 'runningStatus',
    ellipsis: true,
  },
  {
    title: t('deviceList.faultCondition'),
    dataIndex: 'errorStatus',
    key: 'errorStatus',
    ellipsis: true,
  },
  {
    title: t('createDevice.brand'),
    dataIndex: 'brandName',
    key: 'brandName',
    ellipsis: true,
  },
  {
    title: t('createDevice.modelNumber'),
    dataIndex: 'modelName',
    key: 'modelName',
    ellipsis: true,
  },
  {
    title: t('createDevice.gatewaySerialNumber'),
    dataIndex: 'snCode',
    key: 'snCode',
    ellipsis: true,
  },
];
const { booleanPermission } = useUserInfoStore();
const router = useRouter();
const modalGuidanceRef = useTemplateRef('modalGuidance');
const devicesList = ref<DevicesListItem[]>([]);

const devicesKeys = ref<Key[]>([]);
const route = useRoute();
const devicesTotal = ref<number>();

const devicePageParam = ref<DevicesList>({
  pageIndex: 1,
  pageSize: 10,
  groupId: undefined,
  deviceType: undefined,
  searchContent: undefined,
  brandName: undefined,
  modelName: undefined,
  gatewaySnCode: undefined,
  deviceName: undefined,
  runningStatus: undefined,
  errorStatus: undefined,
});

const groupIdKeys = ref<number[]>([]);

const deviceGroup = ref<DeviceGroupItem[]>([]);
const equipmentType = ref<EquipmentTypeItem[]>([]);
const equipmentListShow = ref<boolean>(true);

const modalComponentRef = useTemplateRef('modalComponent');

const { handleRequest } = useRequest();

const confirm = () => {
  handleRequest(async () => {
    await deviceDeletion(devicesKeys.value as number[]);
    modalComponentRef.value?.hideView();
    addQueryDevicesList();
  });
};

const postDeviceDeletion = () => {
  if (devicesKeys.value.length === 0) {
    return message.warning(t('deviceList.pleaseSelectItemDelete'));
  }
  modalComponentRef.value?.showView();
};

const addQueryDevicesList = () => {
  devicePageParam.value.pageIndex = 1;
  postQueryDevicesList();
};

const postQueryDevicesList = () => {
  handleRequest(async () => {
    if (groupIdKeys.value) {
      devicePageParam.value.groupId = groupIdKeys.value[1] ? groupIdKeys.value[1] : groupIdKeys.value[0];
    } else {
      devicePageParam.value.groupId = undefined;
    }

    const { records, total } = await queryDevicesList(devicePageParam.value);
    devicesList.value = records;
    devicesTotal.value = total;
  });
};

const devicesChange = (selectedRowKeys: Key[]) => {
  devicesKeys.value = selectedRowKeys;
};

const switchPages = () => {
  postQueryDevicesList();
};

const addQueryReset = () => {
  devicePageParam.value = {
    pageIndex: 1,
    pageSize: 10,
    groupId: undefined,
    deviceType: undefined,
    searchContent: undefined,
    brandName: undefined,
    modelName: undefined,
    gatewaySnCode: undefined,
    deviceName: undefined,
    runningStatus: undefined,
    errorStatus: undefined,
  };
  groupIdKeys.value = [];
  devicesKeys.value = [];

  addQueryDevicesList();
};

const addEquipmentDetails = (id: number) => {
  router.push(`${'/device-manage/device-list/equipment-details/'}${id}`);
  equipmentListShow.value = false;
};

watch(
  () => route.path,
  (value) => {
    if (value === '/device-manage/device-list') equipmentListShow.value = true;
  },
);
const addEquipment = () => {
  modalGuidanceRef.value?.showView();
};

const getProtocolData = () => {
  postQueryDevicesList();
};

onMounted(() => {
  if (route.path.includes('/device-manage/device-list/equipment-details/')) equipmentListShow.value = false;
  handleRequest(async () => {
    deviceGroup.value = await getPageList();

    equipmentType.value = await groupList({
      dataType: 1,
    });
    addQueryDevicesList();
  });
});
</script>

<template>
  <div>
    <RouterView />
    <div v-show="equipmentListShow">
      <AFlex justify="space-between">
        <div class="text-top">{{ $t('navigation.deviceManage') }}</div>
        <div>
          <AButton
            class="deletion-button default-button"
            @click="postDeviceDeletion"
            v-if="booleanPermission(OperatePermission.删除设备)"
          >
            <AFlex align="center">
              <SvgIcon style="margin-right: 4px" name="delete" />

              <span> {{ $t('common.delete') }} </span>
            </AFlex>
          </AButton>
          <AButton type="primary" @click="addEquipment" v-if="booleanPermission(OperatePermission.新增设备)">
            <AFlex align="center">
              <SvgIcon style="margin-right: 4px" name="plus" />
              <span> {{ $t('common.add') }} </span>
            </AFlex>
          </AButton>
        </div>
      </AFlex>

      <div class="content">
        <AFlex wrap="wrap" justify="space-between">
          <div>
            <div class="query-text">{{ $t('common.search') }}</div>
            <AInput
              :placeholder="$t('deviceList.pleaseEnterQueryContent')"
              class="query-input"
              v-model:value="devicePageParam.searchContent"
            />
          </div>
          <div>
            <div class="query-text">{{ $t('createDevice.equipmentGroup') }}</div>
            <ACascader
              v-model:value="groupIdKeys"
              class="query-input"
              :field-names="{ label: 'groupName', value: 'id', children: 'deviceGroupChilds' }"
              :options="deviceGroup"
              change-on-select
              :placeholder="$t('common.plzSelect')"
            />
          </div>
          <div>
            <div class="query-text">{{ $t('deviceList.equipmentCategory') }}</div>

            <ASelect
              class="query-input"
              v-model:value="devicePageParam.deviceType"
              :options="equipmentType"
              :field-names="{ label: 'dataName', value: 'id' }"
              :placeholder="$t('common.plzSelect')"
              :allow-clear="true"
            />
          </div>
          <div>
            <div class="query-text">{{ $t('deviceList.operatingStatus') }}</div>
            <ASelect
              class="query-input"
              v-model:value="devicePageParam.runningStatus"
              :placeholder="$t('common.plzSelect')"
              :allow-clear="true"
            >
              <ASelectOption :value="0">{{ $t('common.offline') }}</ASelectOption>
              <ASelectOption :value="1">{{ $t('common.shutDown') }}</ASelectOption>
              <ASelectOption :value="2">{{ $t('common.run') }}</ASelectOption>
            </ASelect>
          </div>
          <div>
            <div class="query-text">{{ $t('deviceList.faultCondition') }}</div>
            <ASelect
              class="query-input"
              v-model:value="devicePageParam.errorStatus"
              :placeholder="$t('common.plzSelect')"
              :allow-clear="true"
            >
              <ASelectOption :value="0">{{ $t('envMonitor.normal') }}</ASelectOption>
              <ASelectOption :value="1">{{ $t('common.fault') }}</ASelectOption>
            </ASelect>
          </div>
          <!-- <div>
          <div class="query-text">智控状态</div>
          <ASelect
            class="query-input"
            v-model:value="devicePageParam.deviceType"
            :options="equipmentType"
            :field-names="{ label: 'dataName', value: 'id' }"
            :placeholder="$t('common.plzSelect')"
          />
        </div> -->
        </AFlex>
        <AFlex justify="flex-end">
          <AButton type="primary" class="query-button" @click="addQueryDevicesList">{{ $t('common.query') }}</AButton>
          <AButton class="default-button" @click="addQueryReset">{{ $t('common.reset') }}</AButton>
        </AFlex>
        <ATable
          :row-selection="
            booleanPermission(OperatePermission.删除设备)
              ? {
                  type: 'checkbox',
                  selectedRowKeys: devicesKeys,
                  onChange: devicesChange,
                }
              : undefined
          "
          row-key="id"
          :columns="devicesColumns"
          :data-source="devicesList"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'deviceName'">
              <span class="equipment-name" @click="addEquipmentDetails(record.id)">{{ record.deviceName }}</span>
            </template>
            <template v-if="column.key === 'runningStatus'">
              <div v-if="record.runningStatus == 2" class="tag-style success">{{ $t('common.run') }}</div>
              <div v-else-if="record.runningStatus == 1" class="tag-style failure">{{ $t('common.shutDown') }}</div>
              <div v-else-if="record.runningStatus == 0" class="tag-style default">{{ $t('common.offline') }}</div>
              <div v-else>--</div>
            </template>
            <template v-if="column.key === 'errorStatus'">
              <div v-if="record.errorStatus == 0" class="tag-style success">{{ $t('envMonitor.normal') }}</div>
              <div v-else-if="record.errorStatus == 1" class="tag-style failure" style="width: 64px">
                {{ $t('deviceList.equipmentFailure') }}
              </div>
              <div v-else>--</div>
            </template>

            <template v-if="column.key === 'snCode'">
              {{ record.gatewayInfos.length > 0 ? record.gatewayInfos[0].snCode : '' }}
            </template>
          </template>
        </ATable>
        <br />
        <br />
        <AFlex justify="flex-end" class="footer">
          <APagination
            v-model:current="devicePageParam.pageIndex"
            v-model:page-size="devicePageParam.pageSize"
            :total="devicesTotal"
            :show-size-changer="true"
            @change="switchPages"
            show-quick-jumper
            :show-total="(total) => $t('common.pageTotal', { total })"
          />
        </AFlex>
      </div>
    </div>
  </div>
  <ModalGuidance ref="modalGuidance" @finish="getProtocolData">
    <CreateDevice />
  </ModalGuidance>
  <ConfirmModal
    ref="modalComponent"
    :title="t('common.deleteConfirmation')"
    :description-text="t('common.confirmDeletion')"
    :icon="{ name: 'delete' }"
    :icon-bg-color="'#F56C6C'"
    @confirm="confirm"
  />
</template>

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

.deletion-button {
  width: 84px;
  height: 32px;
  margin-right: 16px;
}

.content {
  padding: 24px;
  margin-top: 24px;
  background: #fff;
  border-radius: 16px;
}

.query-text {
  display: inline-block;
  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;
}

.equipment-name {
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  color: #32bac0;
  text-align: left;
  cursor: pointer;
}

.query-input {
  width: 256px;
  margin-bottom: 16px;
}

.query-button {
  margin-right: 12px;
  margin-bottom: 16px;
}

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

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

.failure {
  width: 40px;
  color: #f5222d;
  background: #fff1f0;
  border: 1px solid #ffa39e;
}

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

:deep(.footer) {
  .ant-pagination-item {
    background-color: #fff;
    border-color: #d6d6d6;
  }

  .ant-pagination-item a {
    color: #666;
  }

  .ant-pagination .ant-pagination-item-active {
    background-color: var(--antd-color-primary-hover);
  }

  .ant-pagination .ant-pagination-item-active a {
    color: #fff;
  }

  .ant-pagination-item-link {
    color: #666;

    // border: 1px solid #d6d6d6;
  }

  .ant-pagination-total-text {
    font-size: 14px;
    font-weight: 400;
    color: #666;
  }
}
</style>
