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

import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { getAIStartStopData, updateAIStartStopData, updateAIStartStopOptimize } from '@/api';
import { CtrlCabinetStartType } from '@/constants';

import type { SegmentedBaseOption } from 'ant-design-vue/es/segmented/src/segmented';
import type { AIStartStopDeviceItem, GroupModuleInfo } from '@/types';

interface Props {
  info: GroupModuleInfo;
}

const props = defineProps<Props>();

interface ModeTypeItem extends SegmentedBaseOption {
  value: CtrlCabinetStartType;
  payload: {
    title: string;
    confirmTip: string;
  };
}

const modeTypes = computed<ModeTypeItem[]>(() => {
  return [
    {
      value: CtrlCabinetStartType.FullAuto,
      payload: {
        title: t('realTimeMonitor.fullAutoMode'),
        confirmTip: t('realTimeMonitor.fullAutoConfirmTip'),
      },
    },
    {
      value: CtrlCabinetStartType.HalfAuto,
      payload: {
        title: t('realTimeMonitor.halfAutoMode'),
        confirmTip: t('realTimeMonitor.halfAutoConfirmTip'),
      },
    },
    {
      value: CtrlCabinetStartType.Jog,
      disabled: true,
      payload: {
        title: t('realTimeMonitor.jogMode'),
        confirmTip: '',
      },
    },
  ];
});

const currentModeType = computed<CtrlCabinetStartType>(() => {
  return props.info.moduleInfoAi?.aiStartType ?? CtrlCabinetStartType.FullAuto;
});

watch(currentModeType, () => {
  deviceList.value = [];
  getDeviceList();
});

const handleModeClick = (option: ModeTypeItem) => {
  if (option.disabled || option.value === currentModeType.value) {
    return;
  }

  Modal.confirm({
    title: t('realTimeMonitor.confirmSwitchToMode', { mode: option.payload.title }),
    content: option.payload.confirmTip,
    closable: true,
    centered: true,
    onOk() {
      handleRequest(async () => {
        const id = props.info.moduleInfoAi.id;
        const groupId = props.info.groupId;

        await updateAIStartStopOptimize({
          id,
          groupId,
          aiStartType: option.value,
        });
      });
    },
  });
};

const { isLoading, handleRequest } = useRequest();
const deviceList = ref<AIStartStopDeviceItem[]>([]);
let deviceTimer: number | undefined;

onMounted(() => {
  getDeviceList();
});

onUnmounted(() => {
  deviceList.value = [];
  clearTimeout(deviceTimer);
});

const getDeviceList = () => {
  clearTimeout(deviceTimer);

  handleRequest(async () => {
    const groupId = props.info.groupId;
    const startType = props.info.moduleInfoAi.aiStartType;
    deviceList.value = await getAIStartStopData(groupId, startType);
  });

  deviceTimer = window.setTimeout(getDeviceList, 3000);
};

const handleFullStartStatusSwitch = () => {
  const device = deviceList.value[0];
  const title = device.startStatus ? t('realTimeMonitor.confirmFullPowerOff') : t('realTimeMonitor.confirmFullPowerOn');
  const content = device.startStatus
    ? t('realTimeMonitor.confirmFullPowerOffTip')
    : t('realTimeMonitor.confirmFullPowerOnTip');

  Modal.confirm({
    title,
    content,
    closable: true,
    centered: true,
    onOk() {
      handleRequest(async () => {
        await updateAIStartStopData({
          deviceId: device.deviceId,
          status: device.startStatus ? 0 : 1,
          startType: currentModeType.value,
        });
      });
    },
  });
};

const handleStartStatusSwitch = (device: AIStartStopDeviceItem) => {
  const title = device.startStatus ? t('common.confirmClose') : t('common.confirmOpen');

  Modal.confirm({
    title: title + device.deviceName,
    closable: true,
    centered: true,
    onOk() {
      handleRequest(async () => {
        await updateAIStartStopData({
          deviceId: device.deviceId,
          status: device.startStatus ? 0 : 1,
          startType: currentModeType.value,
        });
      });
    },
  });
};
</script>

<template>
  <div class="ctrl-panel-scroll-container ai-start-stop-container">
    <ASegmented :value="currentModeType" :options="modeTypes">
      <template #label="option">
        <span @click="handleModeClick(option as ModeTypeItem)">{{ option.payload.title }}</span>
      </template>
    </ASegmented>
    <template v-if="currentModeType === CtrlCabinetStartType.FullAuto">
      <div class="power-button" @click="handleFullStartStatusSwitch">
        <div class="power-button-content">
          <SvgIcon name="power-off" />
          <div>
            {{ deviceList[0]?.startStatus ? $t('realTimeMonitor.fullPowerOff') : $t('realTimeMonitor.fullPowerOn') }}
          </div>
        </div>
        <div class="power-button-segmented-border"></div>
      </div>
    </template>
    <div v-else-if="currentModeType === CtrlCabinetStartType.HalfAuto" class="ctrl-panel-scroll-content">
      <div v-for="(item, index) in deviceList" :key="index" class="device-item">
        <div>
          <span :class="['device-item-tag', { 'device-tag-run': item.runningStatus === 1 }]">
            {{ item.runningStatus === 1 ? $t('common.run') : $t('common.shutDown') }}
          </span>
          <span class="device-item-title">{{ item.deviceName }}</span>
        </div>
        <ASwitch
          :checked="item.startStatus"
          :checked-value="1"
          :un-checked-value="0"
          :checked-children="$t('common.on')"
          :un-checked-children="$t('common.off')"
          @click="handleStartStatusSwitch(item)"
        />
      </div>
    </div>
    <ASpin v-if="isLoading" class="center-loading" :spinning="true" />
  </div>
</template>

<style lang="scss" scoped>
.power-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 214px;
  color: #fff;
  cursor: pointer;
  background-color: rgba(var(--antd-color-primary-rgb), 0.04);
  border: 1px solid rgba(var(--antd-color-primary-rgb), 0.08);

  &,
  &::before,
  &::after {
    position: absolute;
    top: 50%;
    left: 50%;
    aspect-ratio: 1;
    border-radius: 50%;
    transform: translate(-50%, -50%);
  }

  &::before,
  &::after {
    display: block;
    content: '';
  }

  &::before {
    width: 166px;
    background-color: rgba(var(--antd-color-primary-rgb), 0.1);
    border: 1px solid rgba(var(--antd-color-primary-rgb), 0.12);
  }

  &::after {
    width: 120px;
    background: linear-gradient(
      219deg,
      var(--antd-color-primary-border-hover) 0%,
      var(--antd-color-primary) 51%,
      var(--antd-color-primary-active) 100%
    );
    box-shadow: inset 0 0 8px 0 var(--antd-color-primary-bg-hover);
  }
}

.power-button-segmented-border {
  position: absolute;
  width: calc(100% + 4px);
  height: calc(100% + 4px);
  content: '';

  /* 生成三段60度的深色边框，间隔60度 */
  background: conic-gradient(
    var(--antd-color-primary-active) 0deg 60deg,
    transparent 60deg 120deg,
    var(--antd-color-primary-active) 120deg 180deg,
    transparent 180deg 240deg,
    var(--antd-color-primary-active) 240deg 300deg,
    transparent 300deg 360deg
  );
  border-radius: 50%;

  /* 通过遮罩仅显示边框区域 */
  mask: radial-gradient(
    circle,
    transparent calc(53% - 1px),
    #000 calc(53% - 1px) calc(53% + 1px),
    transparent calc(53% + 1px)
  );
}

.power-button-content {
  z-index: 5;
  font-size: 16px;
  font-weight: 500;
  line-height: 22px;
  color: #fff;
  text-align: center;

  i {
    font-size: 24px;
  }
}

.device-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: rgb(255 255 255 / 8%);
  border-radius: 4px;

  & + & {
    margin-top: 16px;
  }
}

.device-item-tag {
  padding: 2px 8px;
  margin-right: 16px;
  font-size: 12px;
  font-weight: 500;
  line-height: 20px;
  color: rgb(255 255 255 / 65%);
  background: rgb(255 255 255 / 16%);
  border: 1px solid rgb(255 255 255 / 24%);
  border-radius: 4px;
}

.device-tag-run {
  color: #52c41a;
  background: rgb(103 194 58 / 16%);
  border-color: rgb(82 196 26 / 50%);
}

.device-item-title {
  font-size: 14px;
  font-weight: 500;
  line-height: 22px;
  color: #fff;
}
</style>
