<template>
  <a-row class="head-top">
    <a-col :span="3" class="head-no bg flex items-center justify-center"
      ><a-badge status="processing" /> 浇铸炉号：{{ info.billetHotsendChangeShift.heatNo }}
    </a-col>
    <a-col :span="1" class="amount-no bg flex items-center justify-center">
      <a-statistic title="支数" :value="info.currentCastingFurnaceAmount || 0" />
    </a-col>
    <a-col :span="2" class="amount-no bg flex items-center justify-center">
      <a-statistic title="重量/t" :value="info.currentCastingFurnace ? info.currentCastingFurnace.toFixed(3) : 0" />
    </a-col>
    <a-col :span="1" class="flex items-center justify-center">
      <a-button type="primary" class="change-heat" @click="switchHeatNo" :loading="changeHeatLoading">换炉</a-button>
    </a-col>
    <a-col :span="1" class="current-shift flex items-center justify-center">当班统计：</a-col>
    <a-col :span="1" class="flex items-center justify-center">
      <a-statistic title="总支数" :value="info.billetHotsendChangeShift.shiftSum" />
    </a-col>
    <a-col :span="2" class="flex items-center justify-center">
      <a-statistic title="总重量/t" :value="info.billetHotsendChangeShift.shiftProduct ? info.billetHotsendChangeShift.shiftProduct.toFixed(3) : 0" />
    </a-col>
    <a-col :span="3" class="flex flex-col" v-for="item of typeList">
      <div class="type-item">
        <span class="type-title" :style="{ color: item.titleColor }">{{ item.title }}：</span> {{ item.amount }} 支 / {{ item.weight }} t
      </div>
      <div class="type-item" v-for="ele of item.dtlList">
        <div class="type-item-dtl">
          <span class="type-title">{{ ele.size }}：</span> {{ ele.nums }} 支 / {{ ele.weight }} t
        </div>
      </div>
    </a-col>
    <a-col :span="2" class="paihao flex items-center justify-center">当前牌号：<component :is="renderDictTag(info.brandNum, 'billet_spec')" /></a-col>
    <a-col :span="2" class="current-shift flex items-center justify-center">
      <a-button type="primary" danger @click="openPaihaoModal = true">切换牌号</a-button>
    </a-col>
  </a-row>
  <a-modal
    v-model:open="openPaihaoModal"
    title="切换牌号"
    centered
    width="400px"
    ok-text="确认"
    :okButtonProps="{ loading: okLoading }"
    cancel-text="取消"
    @ok="switchSteelOne"
    @cancel="
      () => {
        openPaihaoModal = false;
        newBrandNum = '';
      }
    "
  >
    <div class="flex justify-center items-center" style="margin: 20px 0">
      <div>选择牌号：</div>
      <JSearchSelect type="list" style="width: 277px" v-model:value="newBrandNum" dict="billet_spec" placeholder="请选择" allowClear />
    </div>
  </a-modal>
  <!-- 切换炉号确认 -->
  <changeHeatModal @register="registerChangeHeatModal" @ok="() => {}" />
</template>
<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue';
  import AStatistic from 'ant-design-vue/lib/statistic/Statistic';
  import { getOnDutyInfo, getTeamShift, getSteelPileBaseInfo, groupBy } from '../../Dashboard/dashboard.api';
  import { useTimeoutFn } from '/@/hooks/core/useTimeout';
  import { switchSteel, returnFurnaceChange } from '../operator.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { render } from '/@/utils/common/renderUtils';
  import changeHeatModal from './changeHeatModal.vue';
  import { useModal } from '/@/components/Modal';

  const { createMessage } = useMessage();

  // 注册打印modal
  const [registerChangeHeatModal, { openModal: openChangeHeatModal }] = useModal();

  const emits = defineEmits(['shiftChange', 'lengthChange']);

  const props = defineProps({
    ccmNo: {
      type: String,
      default: '5',
    },
  });

  const info = ref<any>({
    brandNum: '',
    billetHotsendChangeShift: {
      heatNo: '',
      shiftGroup: '',
      shift: '',
      wasteAmount: 0,
      shiftProduct: 0,
      shiftSum: 0,
      wasteBlankOutput: 0,
    },
    currentCastingFurnaceAmount: null,
    currentCastingFurnace: null,
  });

  // typeList
  const typeList = ref<any>([
    { title: '棒一', titleColor: '#f50', amount: 0, weight: 0, dtlList: [] },
    { title: '热装', titleColor: '#f50', amount: 0, weight: 0, dtlList: [] },
    { title: '堆垛', titleColor: '#b8ceff', amount: 0, weight: 0, dtlList: [] },
  ]);
  // 渲染字典标签
  const renderDictTag = (value: string, dictCode: string) => {
    return render.renderDict(value, dictCode);
  };

  // 获取班组班别
  const getShiftInfo = () => {
    emits('shiftChange', getTeamShift(info.value.billetHotsendChangeShift.shift, info.value.billetHotsendChangeShift.shiftGroup), {
      shift: info.value.billetHotsendChangeShift.shift,
      shiftGroup: info.value.billetHotsendChangeShift.shiftGroup,
    });
  };

  // 获取当前班次信息
  const getInfo = async () => {
    try {
      const infoRes = await getOnDutyInfo({ ccmNo: props.ccmNo });
      if (infoRes) {
        info.value = infoRes;
        try {
          let standObj = {};
          (JSON.parse(infoRes.standNoSize) || []).forEach((item) => {
            standObj[item.strandNo] = item.length;
          });
          emits('lengthChange', JSON.stringify(standObj));
        } catch (error) {
          console.log(error);
        }
      }

      // 获取明细
      const dtlRes = await getSteelPileBaseInfo({ ccmNo: props.ccmNo });
      // 按照目的地分组
      if (dtlRes) {
        const destinationArr = dtlRes.reduce((acc, cur) => {
          acc[cur.belongTable] = acc[cur.belongTable] || [];
          acc[cur.belongTable].push(cur);
          return acc;
        }, {});

        // roll_club_one 棒一
        // roll_club_two 棒二
        // roll_club_three 棒三
        // roll_out_shipp 上若
        // roll_height 高线
        // stacking_and_loading_vehicles 堆垛
        let hotsendData: any = [],
          hotSendSum = 0,
          hotSendTotalWeight = 0,
          hotchargeData: any = [],
          hotChargeSum = 0,
          hotChargeTotalWeight = 0,
          stackingData: any = [],
          stackingSum = 0,
          stackingTotalWeight = 0;
        // 计算棒一
        if (destinationArr['roll_club_one']) {
          hotsendData = Object.values(groupBy(destinationArr['roll_club_one'] || [], 'length')).map((one: any) => {
            hotSendSum += one.nums;
            hotSendTotalWeight += one.weight;
            return {
              ...one,
              weight: one.weight.toFixed(3),
              size: one.size / 1000,
            };
          });
        }

        // 计算热装
        if (destinationArr['roll_club_two'] || destinationArr['roll_club_three'] || destinationArr['roll_out_shipp']) {
          const concatArr = [
            ...(destinationArr['roll_club_two'] || []),
            ...(destinationArr['roll_club_three'] || []),
            ...(destinationArr['roll_out_shipp'] || []),
          ];
          hotchargeData = Object.values(groupBy(concatArr, 'length')).map((one: any) => {
            hotChargeSum += one.nums;
            hotChargeTotalWeight += one.weight;
            return {
              ...one,
              weight: one.weight.toFixed(3),
              size: one.size / 1000,
            };
          });
        }

        // 计算堆垛
        if (destinationArr['stacking_and_loading_vehicles']) {
          stackingData = Object.values(groupBy(destinationArr['stacking_and_loading_vehicles'] || [], 'length')).map((one: any) => {
            stackingSum += one.nums;
            stackingTotalWeight += one.weight;
            return {
              ...one,
              weight: one.weight.toFixed(3),
              size: one.size / 1000,
            };
          });
        }

        typeList.value = [
          {
            title: '棒一',
            titleColor: '#f50',
            amount: hotSendSum || 0,
            weight: hotSendTotalWeight ? hotSendTotalWeight.toFixed(3) : 0,
            dtlList: hotsendData,
          },
          {
            title: '热装',
            titleColor: '#f50',
            amount: hotChargeSum || 0,
            weight: hotChargeTotalWeight ? hotChargeTotalWeight.toFixed(3) : 0,
            dtlList: hotchargeData,
          },
          {
            title: '堆垛',
            titleColor: '#b8ceff',
            amount: stackingSum || 0,
            weight: stackingTotalWeight ? stackingTotalWeight.toFixed(3) : 0,
            dtlList: stackingData,
          },
        ];

        getShiftInfo();
      }
    } catch (error) {
    } finally {
      start();
    }
  };

  const { start, stop } = useTimeoutFn(getInfo, 5000);

  // 换炉
  const changeHeatLoading = ref(false);
  const switchHeatNo = async () => {
    try {
      if (!info.value.billetHotsendChangeShift.heatNo) return;
      changeHeatLoading.value = true;
      const heatInfo = await returnFurnaceChange({
        heatNo: Number(info.value.billetHotsendChangeShift.heatNo) + 1,
      });

      if (heatInfo) {
        openChangeHeatModal(true, {
          record: { ...heatInfo, ccmNo: heatInfo.ccmNo || props.ccmNo },
        });
      }
      changeHeatLoading.value = false;
    } catch (error) {
      changeHeatLoading.value = false;
    }
  };

  // 切换牌号
  const openPaihaoModal = ref(false);
  const newBrandNum = ref('');
  const okLoading = ref(false);
  const switchSteelOne = async () => {
    try {
      if (newBrandNum.value == '') {
        createMessage.error('请选择牌号');
        return;
      }
      okLoading.value = true;
      await switchSteel({
        ccmNo: props.ccmNo,
        brandNum: newBrandNum.value,
      });

      getInfo();
      openPaihaoModal.value = false;
      newBrandNum.value = '';
      okLoading.value = false;
    } catch (error) {
      okLoading.value = false;
    }
  };

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

  onUnmounted(() => {
    stop();
  });

  defineExpose({
    reload: () => {
      stop();
      getInfo();
    },
  });
</script>
<style lang="less" scoped>
  .head-top {
    height: 130px;
    font-size: 16px;
    color: var(--op-text-color-fff);
    border: 1px solid var(--op-border-color);
    border-radius: 6px;
    background-color: #01396c;
    overflow: hidden;

    .ant-col {
      height: 130px;
      border-right: 1px solid var(--op-border-color);
      overflow: hidden auto;
      padding: 10px;
      font-size: 16px;

      &:last-child {
        border-right: none;
      }
    }

    .head-no {
      height: 130px;
      font-size: 24px;
      font-family: 'Kingsoft_Cloud_Font';
    }
    .bg {
      background: #0085ff;
    }

    .ant-statistic {
      :deep(.ant-statistic-title),
      :deep(.ant-statistic-content-value-int),
      :deep(.ant-statistic-content-value-decimal) {
        color: var(--op-text-color-fff);
        text-align: center;
        font-size: 16px;
      }

      :deep(.ant-statistic-content-value-int),
      :deep(.ant-statistic-content-value-decimal) {
        font-size: 30px;
      }

      :deep(.ant-statistic-content) {
        text-align: center;
      }
    }

    .ant-btn {
      height: 80px;
      font-size: 18px;
      padding: 4px 10px;
    }

    .paihao {
      color: #f50;
      font-size: 16px;
    }

    .type-item {
      font-size: 16px;
    }

    .type-title {
      display: inline-block;
      width: 50px;
    }

    .change-heat.is-disabled {
      background: #d9d9d9;
      color: #8a8a8a;
    }

    .ant-badge {
      width: 12px;
      height: 12px;
      line-height: 12px;
      margin-right: 8px;
      margin-top: -7px;

      :deep(.ant-badge-status-dot) {
        width: 12px;
        height: 12px;
        color: #00fb6f;
        background-color: #00fb6f;
      }
    }

    @keyframes antStatusProcessing {
      0% {
        transform: scale(0.8);
        opacity: 0.8;
      }
      100% {
        transform: scale(2.4);
        opacity: 0.2;
      }
    }
  }
</style>
