<template>
  <a-spin :spinning="isSpinning" wrapperClassName="car-info-spin">
    <a-tabs v-model:activeKey="activeKey" type="card" @change="tabChange">
      <a-tab-pane :key="item" :tab="'车位' + item" v-for="item in carPosition[ccmNo]">
        <div class="car-info-wrapper">
          <div class="licensePlate"
            >装运车辆：{{ vehicleInfo['info' + item] && vehicleInfo['info' + item].licensePlate ? vehicleInfo['info' + item].licensePlate : '' }}</div
          >
          <print-car-info
            :ref="printCarInfoRefs[`infoRef${item}`]"
            :carPositon="item"
            :ccm-no="ccmNo"
            :info="vehicleInfo['info' + item]"
            @change="handleChange"
            @refresh="refreshCarList"
          />
          <div class="print">
            <a-button
              type="primary"
              v-if="vehicleInfo['info' + item] && vehicleInfo['info' + item].id"
              @click="
                () =>
                  openPrintModal(true, {
                    record: vehicleInfo['info' + item],
                    typeConfigId: !vehicleInfo['info' + item].typeConfigId ? '1024' : vehicleInfo['info' + item].typeConfigId,
                    type: 'offline',
                  })
              "
              >打印</a-button
            >
          </div>
          <div class="change-type flex items-center" v-if="vehicleInfo['info' + item] && Object.keys(vehicleInfo['info' + item]).includes('btype')">
            <span>{{ vehicleInfo['info' + item].ccmNo_dictText }}</span>
            <span>/</span>
            <a-switch
              v-model:checked="vehicleInfo['info' + item].btype"
              checked-value="0"
              @change="(checked) => handleBtypeChange(checked, vehicleInfo['info' + item])"
              checked-children="热坯"
              un-checked-value="1"
              un-checked-children="冷坯"
            />
          </div>
        </div>
      </a-tab-pane>
      <!-- <a-tab-pane key="2" tab="车位2" force-render>Content of Tab Pane 2</a-tab-pane> -->
    </a-tabs>
    <div class="flex justify-between refresh-wrapper" :style="{ left: carPosition[ccmNo].length * 70 + 20 + 'px' }">
      <a-button size="large" type="primary" style="font-size: 18px" @click="refresh(1)"> 刷新 </a-button>
      <RouterLink :to="'/shippingBill/' + ccmNo" target="_blank">
        <a-button size="large" type="primary" style="font-size: 18px"> 装运列表 </a-button>
      </RouterLink>
    </div>
    <div class="stack-divider flex justify-between items-center">
      <div class="flex items-center">
        {{ stackInfo.typeName || '' }}
        <div style="margin-left: 20px">
          <a-button size="large" type="primary" style="font-size: 18px" @click="refresh(2)"> 刷新 </a-button>
        </div>
      </div>
      <div>
        <a-button
          type="primary"
          v-if="vehicleInfo['info' + activeKey] && vehicleInfo['info' + activeKey].id && !vehicleInfo['info' + activeKey].outTime"
          danger
          @click="stackToCar"
        >
          堆垛装车
        </a-button>
        <a-button style="background-color: #f5f5f5; color: #838383" v-else disabled>堆垛装车</a-button>
      </div>
    </div>
    <div class="stacking-wrapper selected-divider" id="operatorCC-stacking-wrapper">
      <div class="selected-divider-row flex" :id="`stackLayer${pitem.value}`" v-for="pitem in stackingList" :key="pitem.value">
        <!-- <a-divider orientation="left" class="stacking-list-divider">{{ pitem.label }}</a-divider> -->
        <div class="p-layer">{{ pitem.value }}</div>
        <div
          v-for="item in stackingObj[pitem.value]"
          class="p-stack-col stacking-list-row flex-1"
          @click="handleStackClick(item)"
          :class="{ 'selected-row': selectedAddressId.includes(item.id) }"
        >
          <a-dropdown :trigger="['contextmenu']">
            <div class="stack-col" :class="{ 'hemp-texture': !!item.steelBillet.length }">{{ item.heatNo }}</div>
            <template #overlay v-if="item.billetNos">
              <a-menu @click="menuClick($event, item)" style="min-width: 100px">
                <a-menu-item key="1" style="background-color: #b7eb8f; color: #000; text-align: center">更换位置</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
    </div>
  </a-spin>
  <!-- 打印 -->
  <printModal @register="registerPrintModal" />
</template>
<script setup lang="ts">
  import { ref, onMounted, onUnmounted, h } from 'vue';
  import printCarInfo from './printCarInfo.vue';
  import { useTimeoutFn } from '/@/hooks/core/useTimeout';
  import { list, edit } from '../../shippingBill/shippingBill.api';
  import { getStackInfo, stackLoadSave, stackLocationChange } from '../../hotDelivery/hotDelivery.api';
  import { getMachineConfig, MachineConfigType, destinationOptions } from '../../hotDelivery/common.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import printModal from '../../shippingBill/components/printModal.vue';
  import { useModal } from '/@/components/Modal';
  import { render } from '/@/utils/common/renderUtils';

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

  const { createConfirm, createMessage } = useMessage();

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

  const isSpinning = ref(false);

  const activeKey = ref(1);
  const carPosition = {
    '5': [1, 2],
    '6': [2, 3, 4],
  };
  // 车辆信息
  const infoRef1 = ref();
  const infoRef2 = ref();
  const infoRef3 = ref();
  const infoRef4 = ref();
  const printCarInfoRefs = { infoRef1, infoRef2, infoRef3, infoRef4 };

  // 5号机堆垛
  const stackingList = ref<any[]>([]);
  const stackingObj = ref<any>({});
  const stackInfo = ref<any>({});

  // 车位1车辆信息
  // id: '',
  // licensePlate: '',
  // destination: '',
  // typeConfigId: undefined,
  // ccmNo: '',
  // ccmNo_dictText: '',
  // amountTotal: 0,
  // steel: '',
  // size: '',
  // positionNum: '',
  const vehicleInfo = ref<any>({
    info1: {},
    info2: {},
    info3: {},
    info4: {},
  });

  const getInfo = async (type?: number | undefined) => {
    // 获取车位1车辆信息
    try {
      isSpinning.value = true;
      if (type === 1 || type === undefined) {
        const fetchArr: any = [];
        carPosition[props.ccmNo].forEach((item) => {
          fetchArr.push(
            list({
              column: 'createTime',
              order: 'desc',
              pageNo: 1,
              pageSize: 1,
              positionNum: item,
              ...(item == 2 ? {} : { ccmNo: props.ccmNo }),
            })
          );
        });

        await Promise.all(fetchArr).then((res) => {
          if (Array.isArray(res)) {
            res.forEach((item, index) => {
              if (item.records[0]) {
                vehicleInfo.value[`info${index + 1}`] = {
                  ...item.records[0],
                  oldLicensePlate: item.records[0].licensePlate,
                  oldTypeConfigId: item.records[0].typeConfigId === '1024' ? undefined : item.records[0].typeConfigId,
                  typeConfigId: item.records[0].typeConfigId === '1024' ? undefined : item.records[0].typeConfigId,
                  oldBrandNum: item.records[0].brandNum,
                  oldSize: item.records[0].size,
                };
              }
            });
            setTimeout(() => {
              printCarInfoRefs[`infoRef${activeKey.value}`] &&
                printCarInfoRefs[`infoRef${activeKey.value}`].value &&
                printCarInfoRefs[`infoRef${activeKey.value}`].value[0].getTableList();
            }, 50);
          }
        });
      }

      const machineConfig = await getMachineConfig(props.ccmNo)[MachineConfigType.STACKING];

      stackInfo.value = machineConfig[0];
      if (type === 2 || type === undefined) {
        await getStackInfoList(machineConfig[0].id);
      }
    } catch (error) {
      console.log(error);
    } finally {
      isSpinning.value = false;
      start();
    }
  };

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

  // 获取堆垛机堆垛信息
  // 获取当前堆垛信息
  const getStackInfoList = async (typeConfigId) => {
    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(`operatorCC-stacking-wrapper`);
    //   if (element) {
    //     element.scrollIntoView({
    //       behavior: 'smooth',
    //       block: 'center',
    //       inline: 'center',
    //     });
    //   }
    // });
  };

  // 修改类型
  function handleBtypeChange(v, record) {
    stop();
    createConfirm({
      iconType: 'warning',
      title: '确认修改',
      width: '460px',
      content: () => {
        return h('div', { style: { fontSize: '16px' } }, [
          h('span', null, `是否将车牌为`),
          h('span', { style: { fontSize: '18px', color: '#d48806' } }, `${record.licensePlate}`),
          h('span', null, `的`),
          h('span', { style: { fontSize: '18px', color: v === '1' ? '#cd201f' : '#3b5999' } }, `${v === '1' ? ' 热坯 ' : ' 冷坯 '}`),
          h('span', null, `改为`),
          h('span', { style: { fontSize: '18px', color: v === '1' ? '#3b5999' : '#cd201f' } }, `${v === '1' ? ' 冷坯 ' : ' 热坯 '}`),
          h('span', null, `?`),
        ]);
      },
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return edit({ id: record.id, btype: v }).then(() => {
          getInfo();
        });
      },
      onCancel: () => {
        start();
        record.btype = v === '1' ? '0' : '1';
      },
    });
  }

  // 修改牌号，车号，目的地
  const handleChange = (options) => {
    const { type, value, carPositon } = options;
    console.log(options, value, value === undefined);
    if (value === undefined) return;
    stop();
    createConfirm({
      iconType: 'warning',
      title: '确认修改',
      width: '460px',
      content: () => {
        let title = '',
          content: any = '';
        if (type === 'licensePlate') {
          title = '是否修改车牌号为：';
          content = value;
        } else if (type === 'destination') {
          title = '是否修改目的地为：';
          const curDestination = destinationOptions[props.ccmNo].find((item) => item.value === value);
          content = curDestination ? curDestination.label : '';
        } else if (type === 'brandNum') {
          title = '是否修改牌号为：';
          content = render.renderDict(value, 'billet_spec');
        } else if (type === 'size') {
          title = '是否修改定尺为：';
          content = value;
        }
        return h('div', { style: { fontSize: '16px' } }, [
          h('span', null, title),
          h('span', { style: { fontSize: '18px', color: '#d48806' } }, content),
        ]);
      },
      onOk: () => {
        let params = { ...vehicleInfo.value[`info${carPositon}`] };
        if (type === 'destination') {
          const curDestination = destinationOptions[props.ccmNo].find((item) => item.value === value);
          params.destination = curDestination.label;
        }
        return edit(params).then(() => {
          getInfo();
        });
      },
      onCancel: () => {
        start();
        if (type === 'licensePlate') {
          vehicleInfo.value[`info${carPositon}`].licensePlate = vehicleInfo.value[`info${carPositon}`].oldLicensePlate;
        } else if (type === 'destination') {
          vehicleInfo.value[`info${carPositon}`].typeConfigId = vehicleInfo.value[`info${carPositon}`].oldTypeConfigId;
        } else if (type === 'brandNum') {
          vehicleInfo.value[`info${carPositon}`].brandNum = vehicleInfo.value[`info${carPositon}`].oldBrandNum;
        } else if (type === 'size') {
          vehicleInfo.value[`info${carPositon}`].size = vehicleInfo.value[`info${carPositon}`].oldSize;
        }
      },
    });
  };

  // 选择堆垛位置装车
  const selectedAddressId = ref<any[]>([]);
  const selectedAddress = ref<any[]>([]);

  const getSelectedStack = () => {
    return selectedAddress.value || [];
  };

  // 右键换位置
  const menuClick = (e, info) => {
    if (e.key === '1') {
      const selectedStackList = selectedAddress.value.filter((item) => !item.billetNos);
      if (!selectedStackList.length) {
        createMessage.error('请选择要移动的位置，且位置上没有钢坯！');
        return;
      }

      if (selectedStackList.length > 1) {
        createMessage.error('钢坯移动的空位置只能选择一个！');
        return;
      }
      createConfirm({
        iconType: 'warning',
        title: '确认更换位置',
        width: '460px',
        content: () => {
          return h('div', { style: { fontSize: '16px' } }, [
            h('span', null, `是否将`),
            h('span', { style: { fontSize: '18px', color: '#d48806' } }, `${info.layer}层${info.address}`),
            h('span', null, `更换到`),
            h('span', { style: { fontSize: '18px', color: '#cd201f' } }, `${selectedStackList[0].layer}层${selectedStackList[0].address}`),
            h('span', null, `?`),
          ]);
        },
        okText: '更换',
        cancelText: '取消',
        onOk: () => {
          const params = {
            stackId: info.id,
            locationChangeId: selectedStackList[0].id,
          };

          return stackLocationChange(params).then(() => {
            selectedAddressId.value = [];
            selectedAddress.value = [];
            refresh(2);
          });
        },
      });
    }
  };

  const tabChange = (key) => {
    printCarInfoRefs[`infoRef${key}`] && printCarInfoRefs[`infoRef${key}`].value && printCarInfoRefs[`infoRef${key}`].value[0].getTableList();
  };

  const handleStackClick = (v) => {
    const index = selectedAddressId.value.indexOf(v.id);
    if (index > -1) {
      selectedAddressId.value.splice(index, 1);
      selectedAddress.value.splice(index, 1);
    } else {
      selectedAddressId.value.push(v.id);
      selectedAddress.value.push(v);
    }
  };
  const stackToCar = async () => {
    try {
      const valiDesRes = validateCarDestination();
      if (!valiDesRes) {
        return;
      }
      const selectedStackList = selectedAddress.value.filter((item) => item.billetNos);
      if (!selectedStackList.length) {
        createMessage.error('请选择有钢坯的堆垛位置装车！');
        return;
      }

      const curDestination =
        destinationOptions[props.ccmNo].find((item) => item.value === vehicleInfo.value[`info${activeKey.value}`].typeConfigId) || {};

      const params = {
        storageBill: vehicleInfo.value[`info${activeKey.value}`] || {},
        belongTable: stackInfo.value?.belongTable,
        billetHotsendTypeConfigId: stackInfo.value.id,
        stackingAndLoadingVehiclesList: selectedStackList,
        destination: vehicleInfo.value[`info${activeKey.value}`].destination,
        destinationId: vehicleInfo.value[`info${activeKey.value}`].typeConfigId,
        destinationTable: curDestination.belongTable,

        billetHotsend: {
          ccmNo: props.ccmNo,
          isUpd: false,
        },
      };
      stop();
      isSpinning.value = true;
      await stackLoadSave(params);

      getInfo();
    } catch (error) {
      isSpinning.value = false;
    } finally {
      selectedAddressId.value = [];
      selectedAddress.value = [];
    }
  };

  // 验证是否有目的地
  const validateCarDestination = () => {
    const curVehicleInfo = vehicleInfo.value[`info${activeKey.value}`];
    if (!curVehicleInfo.typeConfigId || !curVehicleInfo.destination || curVehicleInfo.typeConfigId == 1024) {
      createMessage.error('请先选择装运单库名！');
      printCarInfoRefs[`infoRef${activeKey.value}`].value && printCarInfoRefs[`infoRef${activeKey.value}`].value[0].focusDestination();
      return false;
    }
    return true;
  };

  // 刷新
  const refresh = (type) => {
    stop();
    getInfo(type);
  };

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

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

  const refreshCarList = () => {
    selectedAddressId.value = [];
    selectedAddress.value = [];
    stop();
    getInfo();
  };

  defineExpose({
    getSelectedStack,
    getStackInfo: () => stackInfo.value,
    getCurrentCar: () => vehicleInfo.value[`info${activeKey.value}`],
    refreshCarList: refreshCarList,
    valirDest: validateCarDestination,
  });
</script>
<style lang="less" scoped>
  @import '../../hotDelivery/components/metal.less';
  .car-info-spin {
    position: relative;
    height: 100%;

    :deep(.ant-spin-container) {
      display: flex;
      flex-direction: column;
      height: 100%;
      overflow: hidden;
    }

    .refresh-wrapper {
      position: absolute;
      left: 100px;
      right: 170px;
    }

    .ant-tabs {
      color: #dadada;

      :deep(.ant-tabs-tab) {
        font-size: 16px;
        background: #01396c;

        &.ant-tabs-tab-active {
          background: #0085ff;

          .ant-tabs-tab-btn {
            color: #fff;
          }
        }
      }
    }
  }

  .car-info-wrapper {
    position: relative;
    padding: 30px 10px 10px;
    border: 1px solid var(--op-border-color);
    border-radius: 6px;

    .licensePlate {
      width: 190px;
      background-color: #010c3a;
      position: absolute;
      top: -15px;
      left: 30px;
      font-size: 16px;
      color: var(--op-text-color-fff);
      text-align: center;
    }

    .print {
      position: absolute;
      right: 22px;
      top: 40px;
    }

    .change-type {
      position: absolute;
      right: 22px;
      top: -50px;
      gap: 10px;
      color: var(--op-text-color-fff);
      font-size: 20px;

      .ant-switch {
        background-color: #3b5999;

        :deep(.ant-switch-inner) {
          .ant-switch-inner-checked,
          .ant-switch-inner-unchecked {
            font-size: 17px;
          }
        }
      }

      .ant-switch.ant-switch-checked {
        background-color: #cd201f;
      }
    }
  }

  .stack-divider {
    font-size: 16px;
    margin-top: 10px;
    color: var(--op-text-color-fff);
  }

  .stacking-wrapper {
    flex: 1;
    overflow: auto;
    padding: 0;
    margin-top: 6px;
    padding-bottom: 20px;

    .selected-divider-row {
      margin-top: 5px;
      gap: 3px;
    }

    &.selected-divider .selected-divider-row .stacking-list-row {
      cursor: pointer;
      height: 24px;
      line-height: 20px;
      border: 1px solid var(--op-border-color);
      border-radius: 4px;
      font-size: 20px;
    }

    .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%;
    }

    .p-layer {
      width: 20px;
      margin-right: 10px;
      font-size: 20px;
      color: #f50;
      font-family: 'Kingsoft_Cloud_Font';
      line-height: 24px;
      text-align: center;
    }
  }
</style>
