<template>
  <div class="stacking-manage-wrapper">
    <div class="stacking-manage-left">
      <template v-if="machineConfig['5'][MachineConfigType.STACKING].length">
        <!-- <div class="nb-stack-num">5#</div> -->
        <a-card
          :class="item.id === selectedStack ? 'selected-card' : ''"
          v-for="item in machineConfig['5'][MachineConfigType.STACKING]"
          :key="item.id"
          hoverable
          :bordered="false"
          style="width: 120px; background: transparent"
          @click="getStackInfoList(item.id)"
          :body-style="{ padding: 0 }"
        >
          <div class="nb-stack"> </div>
          <div class="nb-txt">{{ item.typeName }}</div>
          <template #actions>
            <a-button size="small" type="primary" @click="startStack(item)">起垛</a-button>
            <a-button size="small" type="primary" danger @click="handleWastes(item)">判废</a-button>
          </template>
        </a-card>
      </template>

      <template v-if="machineConfig['6'][MachineConfigType.STACKING].length">
        <!-- <div class="nb-stack-num">6#</div> -->
        <a-card
          :class="item.id === selectedStack ? 'selected-card' : ''"
          v-for="item in machineConfig['6'][MachineConfigType.STACKING]"
          :key="item.id"
          hoverable
          :bordered="false"
          style="width: 120px; background: transparent"
          @click="getStackInfoList(item.id)"
          :body-style="{ padding: 0 }"
        >
          <div class="nb-stack"> </div>
          <div class="nb-txt">{{ item.typeName }}</div>
          <template #actions>
            <a-button size="small" type="primary" @click="startStack(item)">起垛</a-button>
            <a-button size="small" type="primary" danger @click="handleWastes(item)">判废</a-button>
          </template>
        </a-card>
      </template>
    </div>
    <div class="stacking-manage-center selected-divider">
      <a-spin :spinning="isSpinning" wrapperClassName="table-spin">
        <a-row class="selected-divider-row" :id="`stackLayer${pitem.value}`" :gutter="[30, 20]" v-for="pitem in stackingList" :key="pitem.value">
          <a-divider orientation="left" class="stacking-list-divider">{{ pitem.label }}</a-divider>
          <a-col :span="3" v-for="item in stackingObj[pitem.value]" class="p-stack-col">
            <a-tooltip
              placement="left"
              :title="
                item.billetNos
                  ? `${item.steelBillet[0]}、${item.steelBillet[1]},${item.steelBillet[2]}、${item.steelBillet[3]}`.replace(/,/, '\r\n')
                  : ''
              "
            >
              <a-dropdown :trigger="['contextmenu']">
                <a-row
                  justify="start"
                  :class="{ 'selected-row': selectedAddress === item.id }"
                  class="stacking-list-row"
                  @click="handleStackClick(item)"
                >
                  <a-col class="stack-col" :class="{ 'hemp-texture': !!item.steelBillet[0] }" :span="6">{{ item.steelBillet[0] }}</a-col>
                  <a-col class="stack-col" :class="{ 'hemp-texture': !!item.steelBillet[1] }" :span="6">{{ item.steelBillet[1] }}</a-col>
                  <a-col class="stack-col" :class="{ 'hemp-texture': !!item.steelBillet[2] }" :span="6">{{ item.steelBillet[2] }}</a-col>
                  <a-col class="stack-col" :class="{ 'hemp-texture': !!item.steelBillet[3] }" :span="6">{{ item.steelBillet[3] }}</a-col>
                </a-row>
                <template #overlay v-if="item.billetNos">
                  <a-menu @click="menuClick($event, item)" style="min-width: 100px">
                    <a-menu-item key="1" style="background-color: #f56c6c; color: #fff; text-align: center">判废</a-menu-item>
                    <a-menu-item key="2" style="background-color: #b7eb8f; color: #000; text-align: center; margin-top: 8px">更换位置</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-tooltip>
          </a-col>
        </a-row>
      </a-spin>
    </div>
    <stackDrawer ref="stackDrawerRef" />
    <!-- 新增堆垛 -->
    <stacking @register="registerStackingModal" :machine="machine" @success="handleSuccess" :machineConfigType="MachineConfigType.STACKING" />
    <!-- 堆垛判废 -->
    <wastes @register="registerWastesModal" :machine="machine" @success="handleSuccess" />
    <!-- 堆垛位置更换 -->
    <changePosition @register="registerChangePositionModal" :machine="machine" @success="handleSuccess" />
  </div>
</template>
<script setup lang="ts" name="stackManage">
  import { ref, onMounted, nextTick } from 'vue';
  import { queryBilletNameList, getStackInfo, deleteJunk } from '../hotDelivery/hotDelivery.api';
  import { MachineConfigType, getMachineNum } from '../hotDelivery/common.data';
  import stackDrawer from './stackDrawer.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import stacking from './components/stacking.vue';
  import wastes from './components/wastes.vue';
  import changePosition from './components/changePosition.vue';

  const { createConfirm } = useMessage();

  const machineConfig = ref<any>({
    5: {
      [MachineConfigType.STACKING]: [],
    },
    6: {
      [MachineConfigType.STACKING]: [],
    },
  });
  const selectedStack = ref<string>('');
  const selectedAddress = ref<string>('');
  const machine = getMachineNum();

  // 堆垛
  const [registerStackingModal, { openModal: openStackingModal }] = useModal();
  // 堆垛判废
  const [registerWastesModal, { openModal: openWastesModal }] = useModal();
  // 堆垛位置更换
  const [registerChangePositionModal, { openModal: openChangePositionModal }] = useModal();

  // 根据铸机号获取配置信息
  const getMachineConfig = async (machineNum) => {
    if (!machineNum || machineConfig.value[machineNum][MachineConfigType.STACKING].length) {
      return;
    }
    try {
      const res = await queryBilletNameList({ ccmNo: machineNum });
      if (!machineConfig.value[machineNum]) {
        machineConfig.value[machineNum] = {};
      }
      if (res.length) {
        let configNameList = {
          [MachineConfigType.RODLINE]: [],
          [MachineConfigType.STACKING]: [],
        };
        res.forEach((item) => {
          configNameList[item.belongType].push(item);
        });
        machineConfig.value[machineNum] = configNameList;
      }

      selectedStack.value = machineConfig.value[machineNum][MachineConfigType.STACKING][0].id;
      getStackInfoList(machineConfig.value[machineNum][MachineConfigType.STACKING][0].id);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  // 获取堆垛信息
  const stackingObj = ref<any>({});
  const stackingList = ref<any[]>([]);
  const isSpinning = ref(true);
  // 获取当前堆垛信息
  const getStackInfoList = async (typeConfigId) => {
    selectedStack.value = typeConfigId;
    isSpinning.value = true;
    const stackingInfo = await getStackInfo({ typeConfigId });
    let layerObj = {};
    if (stackingInfo.length) {
      stackingInfo.forEach((item) => {
        if (!layerObj[item.layer]) layerObj[item.layer] = [];

        layerObj[item.layer].push({ ...item, steelBillet: item.billetNos ? item.billetNos.split(',') : [] });
      });
    }
    stackingObj.value = layerObj;
    stackingList.value = Object.keys(layerObj)
      .sort((a, b) => Number(b) - Number(a))
      .map((item) => ({ label: `第${item}层`, value: item }));

    nextTick(() => {
      const element = document.getElementById(`stackLayer1`);
      if (element) {
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'center',
          inline: 'center',
        });
      }
    });

    isSpinning.value = false;
  };

  const stackDrawerRef = ref<any>(null);
  const handleStackClick = (item) => {
    selectedAddress.value = item.id;
    stackDrawerRef.value && stackDrawerRef.value.openIt(item);
  };

  const menuClick = (e, info) => {
    if (e.key === '1') {
      const params = {
        belongTable: 'stacking_and_loading_vehicles',
        billetHotsendTypeConfigId: selectedStack.value,
        stackingAndLoadingVehiclesList: [info],
        billetHotsend: {
          ccmNo: '6',
        },
      };
      createConfirm({
        iconType: 'error',
        title: '确认判废',
        content: `确认判废${info.layer}层${info.address}位置，钢坯${info.billetNos} ?`,
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          await deleteJunk(params);
          getStackInfoList(selectedStack.value);
        },
      });

      return;
    }
    if (e.key === '2') {
      openChangePositionModal(true, {
        basicInfo: info,
      });
      return;
    }
  };

  const handleSuccess = () => {
    getStackInfoList(selectedStack.value);
  };

  const startStack = (item) => {
    console.log('startStack', item);
    openStackingModal(true, {
      stacking: item,
      basicInfo: { ccmNo: machine },
    });
  };

  // 堆垛判废
  const handleWastes = (item) => {
    // 弹框
    openWastesModal(true, {
      basicInfo: { ccmNo: machine },
      machineConfig: item,
    });
  };

  // 获取堆垛
  onMounted(() => {
    getMachineConfig(machine);
  });
</script>
<style lang="less" scoped>
  @import '/@/assets/less/font.less';
  @import '../hotDelivery/components/metal.less';
  .stacking-manage-wrapper {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 10px;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 10px;

    .table-spin {
      height: 100%;

      :deep(.ant-spin-container) {
        height: 100%;
        overflow: hidden auto;
        padding: 20px 10px 50px 0;
      }
    }

    .stacking-manage-left {
      display: flex;
      gap: 20px;
      padding: 10px;
      margin-right: 10px;
      background: #ececec;

      .selected-card {
        box-shadow:
          0 4px 4px var(--vxe-primary-color),
          0 6px 6px var(--vxe-primary-color);
      }

      .nb-stack {
        width: 100px;
        height: 100px;
        background-image: url(/@/assets/images/billetHome/stacking.png);
        margin: 5px auto;
        background-size: cover;
        background-repeat: no-repeat;
      }

      .nb-txt {
        font-family: 'Kingsoft_Cloud_Font';
        text-align: center;
        margin-top: 10px;
      }

      .nb-stack-num {
        width: 100px;
        height: 43px;
        background-image: url(/@/assets/images/billetHome/stacking-desc.png);
        font-family: 'Kingsoft_Cloud_Font';
        text-align: center;
        background-size: cover;
        background-repeat: no-repeat;
        color: #fff;
        line-height: 43px;
        margin-left: 30px;
      }

      :deep(.ant-card-actions) {
        & > li {
          margin: 5px 0;
        }
      }
    }

    .stacking-manage-center {
      overflow: hidden;
      padding: 0;
      margin-top: 10px;

      .stacking-list-row {
        cursor: pointer;
      }

      .selected-divider-row {
        row-gap: 10px !important;
        margin-top: 10px;
      }

      .stacking-list-divider {
        margin: 0;
        color: var(--vxe-danger-color, #f56c6c);
      }

      .stack-col {
        overflow: hidden;
      }

      .p-stack-col {
        padding-right: 0 !important;
        max-width: 11%;
      }
    }
  }
</style>
