<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    :title="isEditCard ? '编辑装运单' : '装运单打印'"
    :height="400"
    :width="800"
    :ok-text="isEditCard ? '确认' : '打印'"
    @ok="onPrint"
  >
    <section ref="print" style="padding: 10px 10px 0; position: relative; border: 1px solid #c5c5c5; background: beige; width: 98%" id="printContent">
      <span style="position: absolute; right: 20px; top: 10px; font-size: 16px; font-weight: bold; cursor: pointer" @click="changeBtype">
        {{ info.ccmNo }}#机 / {{ info.btype === '1' ? '冷' : info.btype === '0' ? '热' : '' }}
      </span>
      <div class="ticket next-ticket">
        <div style="text-align: center">
          <p style="font-size: 24px; font-weight: 800; display: inline-block; border-bottom: 2px solid #000; margin-bottom: 16px; line-height: 30px">
            龙钢公司钢坯装运单
          </p>
        </div>
        <div class="flex" style="line-height: 24px">
          <div class="flex-1">
            库名：
            <span v-if="isEditCard">{{ info.destination }}</span>
            <JSearchSelect
              v-else
              type="list"
              style="width: 120px"
              :bordered="false"
              v-model:value="info.typeConfigId"
              :options="destinationOptions[info.ccmNo]"
              placeholder="请选择"
              allowClear
              @change="(v) => handleDestinationIdChange(v)"
            />
          </div>
          <div class="flex-1" style="text-align: center; font-size: 13px">
            <a-date-picker
              class="lgprint-date-picker"
              v-model:value="info.arrivalTimeDay"
              format="YYYY 年 MM 月 DD 日 HH 时 mm 分"
              showTime
              :bordered="false"
            />
            <!-- <a-input v-model:value="info.arrivalTimeDay" class="lgprint-date-picker" :bordered="false" /> -->
          </div>
          <div class="flex-1" style="text-align: right; font-size: 14px">
            <!-- <a-input v-model:value="info.classes" style="font-size: 14px; padding: 0; width: 100%; text-align: right" :bordered="false" /> -->
            <JSearchSelect
              type="list"
              :bordered="false"
              v-model:value="info.shift"
              dict="lg_bb"
              style="width: 60px; font-size: 14px; text-align: right"
              placeholder="班别"
            />
            /
            <JSearchSelect
              type="list"
              :bordered="false"
              v-model:value="info.shiftGroup"
              dict="lg_bz"
              style="width: 50px; font-size: 14px; text-align: left"
              placeholder="班组"
            />
          </div>
        </div>
        <a-descriptions style="margin-top: 6px; margin-bottom: 4px" layout="vertical" bordered :column="8" size="small">
          <a-descriptions-item style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px" label="序号">
            <div style="min-height: 80px; display: flex; align-items: center; justify-content: center" @click="numberEdit.value.focus()">
              <a-input
                ref="numberEdit"
                v-model:value="info.number"
                style="font-size: 14px; padding: 0; width: 28px; text-align: center"
                :bordered="false"
              />
            </div>
          </a-descriptions-item>
          <a-descriptions-item style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px" label="车号">
            <!-- {{ info.licensePlate }} -->
            <JSearchSelect
              type="list"
              :bordered="false"
              v-model:value="info.licensePlate"
              dict="lg_car"
              style="width: 110px; font-size: 14px"
              placeholder="请选择"
              allowClear
            />
          </a-descriptions-item>
          <a-descriptions-item style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px" label="牌号">
            <!-- <component :is="renderDictTag(info.brandNum, 'billet_spec')" /> -->
            <JSearchSelect
              type="list"
              style="width: 110px; font-size: 14px"
              :bordered="false"
              v-model:value="info.brandNum"
              dict="billet_spec"
              placeholder="请选择"
              allowClear
            />
          </a-descriptions-item>
          <a-descriptions-item
            class="heat-wrapper"
            style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px; position: relative"
            label="炉号"
          >
            <div style="min-width: 120px">
              <div class="heatNo-item" v-for="(item, sindex) in headDtl" :key="item.id">
                {{ item.heatNo }} - {{ item.heatNum ? item.heatNum : item.billetNos.length }}
                <div class="op jian" @click="deleteHeatDtl(sindex)"><Icon icon="ant-design:delete-outlined" /></div>
                <div class="op add" @click="editHeatDtl(sindex)">
                  <Icon icon="ant-design:edit-outlined" />
                </div>
              </div>
            </div>
            <div class="add-heatNo" @click="addHeatDtl">+</div>
          </a-descriptions-item>
          <a-descriptions-item style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px" label="规格">
            <div style="min-width: 120px">
              <span> 170 /</span>
              <!-- {{ sizeInfo.join(',') }} -->
              <span v-if="isEditCard">{{ info.size }}</span>
              <!-- <JSelectMultiple type="list" :bordered="false" v-model:value="info.size" dictCode="lg_dcgg" placeholder="请选择" allowClear /> -->
              <a-input v-else v-model:value="info.size" :bordered="false" style="width: 80px; padding: 0; font-size: 14px; display: inline-block" />
            </div>
          </a-descriptions-item>
          <a-descriptions-item style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px" label="名称">
            <div style="min-width: 40px"> 方坯 </div>
          </a-descriptions-item>
          <a-descriptions-item style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px" label="支数">
            <span v-if="isEditCard">{{ info.amountTotal }}</span>
            <!-- {{ info.amountTotal }} -->
            <a-input-number
              v-else
              :bordered="false"
              style="min-width: 50px; width: 50px; font-size: 14px; text-align: center"
              v-model:value="info.amountTotal"
              :min="0"
              :max="99"
              :precision="0"
              :controls="false"
            />
          </a-descriptions-item>
          <!-- <a-descriptions-item style="border: 1px solid #bfbfbf; font-size: 14px; padding: 4px; text-align: center; height: 36px" label="重量">
            <a-input-number
              :bordered="false"
              style="min-width: 80px; width: 80px; font-size: 14px; text-align: center"
              v-model:value="info.weight"
              :min="0"
              :max="99"
              :precision="4"
            />
          </a-descriptions-item> -->
        </a-descriptions>
        <a-descriptions style="padding: 0 30px" size="small" v-if="!isEditCard">
          <a-descriptions-item label="储运中心"> </a-descriptions-item>
          <a-descriptions-item label="轧钢厂"> </a-descriptions-item>
          <a-descriptions-item label="炼钢厂"> </a-descriptions-item>
        </a-descriptions>
      </div>
    </section>
    <div v-if="!isCanEdit" class="mask-disabled-edit"></div>
    <div class="add-heat" v-if="showAddHeat" style="margin: 20px">
      <a-input-group size="large">
        <a-row :gutter="8">
          <a-col :span="6">
            <a-input-number placeholder="请输入炉号" style="min-width: 180px" size="large" v-model:value="headValue" :precision="0" />
          </a-col>
          <a-col :span="4">
            <a-input-number placeholder="请输入支数" v-model:value="heatNum" size="large" :precision="0" />
          </a-col>
          <a-button type="primary" @click="confirmAddHeatDtl">添加</a-button>
        </a-row>
      </a-input-group>
    </div>
    <div style="position: absolute; left: -1000px">{{ getAllAmount }}</div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { computed, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import dayjs from 'dayjs';
  // import { render } from '/@/utils/common/renderUtils';
  import { printJS } from '/@/hooks/web/usePrintJS';
  import { listShippingBill, saveBeforePrint, getByStorageBillId, list } from '../shippingBill.api';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  // import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { destinationOptions } from '../../hotDelivery/common.data';
  import { useUserStore } from '/@/store/modules/user';

  const userStore = useUserStore();
  const { createMessage } = useMessage();
  const props = defineProps({
    api: {
      type: Function as PropType<(params: any) => Promise<any>>,
      default: listShippingBill,
    },
  });
  const emits = defineEmits(['success', 'register']);

  const info = ref<any>({});
  const headDtl = ref<any[]>([]);
  const weight = ref<number>(0);
  const sizeInfo = ref<string[]>([]);
  const numberEdit = ref();
  const isEditCard = ref(false);
  //表单赋值
  const [registerModal, { changeLoading, changeOkLoading, closeModal }] = useModalInner(async (data) => {
    const { record, type, isEdit } = data;
    if (record) {
      // 如果是单纯的编辑，就只能编辑部分，棒三，二，上若 可以部分编辑
      isEditCard.value = isEdit === true;

      let newRecord = record;
      // 重新获取数据
      const res = await list({
        id: record.id,
      });
      if (res.records && res.records.length > 0) {
        newRecord = res.records[0];
      }

      headDtl.value = [];
      info.value = {
        ...newRecord,
        arrivalTimeDay: dayjs(record.arrivalTime),
        number: record.carAllNum || record.number,
        classes:
          isEdit === true
            ? record.classes
            : // dayjs(record.arrivalTime).format('YYYYMMDDHHmmss') +
              // '/' +
              // record.carNum +
              // '/' +
              // record.carAllNum +
              // '/' +
              record.shift_dictText + '/' + record.shiftGroup_dictText,
      };

      // 如果只是纯纯的编辑
      // if (isEdit === true) {
      // } else {
      //   await getTableList();
      // }

      if (type === 'offline') {
        getOfflineBill();
      }
      editDtl.value = {};
    } else {
      info.value = {};
    }
  });

  // 是否可编辑 轧钢确认后，除了gp账号其他的都不能编辑
  const isCanEdit = computed(() => {
    return !info.value.confirmTime || (info.value.confirmTime && userStore.userInfo && userStore.userInfo.username === 'gp');
  });

  // 渲染字典标签
  // const renderDictTag = (value: string, dictCode: string) => {
  //   return render.renderDict(value, dictCode);
  // };
  const getAllAmount = computed(() => {
    const allNum = headDtl.value.reduce((acc, cur) => {
      return acc + Number(cur.heatNum ? cur.heatNum : cur.billetNos.length);
    }, 0);
    info.value.amountTotal = allNum;
    return allNum;
  });

  const getTableList = async () => {
    try {
      changeLoading(true);
      changeOkLoading(true);
      const { id, ccmNo, heatNo, typeConfigId } = info.value;
      const data = await props.api({
        id,
        ccmNo,
        heatNo,
        typeConfigId: !typeConfigId ? '1024' : typeConfigId,
      });

      let newArr: any[] = [];
      if (Array.isArray(data)) {
        newArr = data;
      } else {
        for (let item in data) {
          if (data[item] && data[item].length > 0) {
            newArr = newArr.concat(data[item]);
          }
        }
      }
      let allWeight = 0;

      let sizeArr: string[] = [];
      // 数据结果按组批号分组
      newArr = newArr.reduce((acc, cur) => {
        const index = acc.findIndex((item) => cur.heatNo && item.heatNo === cur.heatNo);
        if (index === -1) {
          acc.push({
            ...cur,
            billetNos: [...cur.billetNo.split(',')],
          });
        } else {
          acc[index].billetNos = acc[index].billetNos.concat(cur.billetNo.split(','));
        }

        if (cur.blankOutput) {
          allWeight += Number(cur.blankOutput);
        }
        if (sizeArr.indexOf(cur.size) === -1) {
          sizeArr.push(cur.size);
        }
        return acc;
      }, []);

      headDtl.value = newArr;
      weight.value = allWeight;
      sizeInfo.value = sizeArr;
      info.value.weight = allWeight;
    } catch (error) {
      console.log(error);
    } finally {
      changeLoading(false);
      changeOkLoading(false);
    }
  };

  // 获取线下票据数据
  const getOfflineBill = async () => {
    try {
      changeLoading(true);
      changeOkLoading(true);
      getByStorageBillId({ storageBillId: info.value.id }).then((res) => {
        if (res) {
          const shiftObj = res.classes.split('/');
          let shift = '';
          let shiftGroup = '';
          if (shiftObj.length === 2) {
            shift = shiftObj[0];
            shiftGroup = shiftObj[1];
          } else {
            shift = info.value.shift;
            shiftGroup = info.value.shiftGroup;
          }
          const destinationInfo = (destinationOptions[info.value.ccmNo] || []).find((item) => item.label === res.destination);
          info.value = {
            ...info.value,
            ...res,
            shift,
            shiftGroup,
            arrivalTimeDay: dayjs(res.arrivalTime),
            destination: res.destination,
            typeConfigId: destinationInfo ? destinationInfo.value : '',
          };

          headDtl.value = Object.keys(res.heatNo).map((item) => ({
            heatNo: item,
            heatNum: res.heatNo[item],
          }));
        }
      });
    } catch (error) {
      console.log(error);
    } finally {
      changeLoading(false);
      changeOkLoading(false);
    }
  };
  const deleteHeatDtl = (index: number) => {
    headDtl.value.splice(index, 1);
  };

  const editHeatDtl = (index: number) => {
    const { heatNo, heatNum: orgHeatNum, billetNos } = headDtl.value[index];
    headValue.value = heatNo;
    heatNum.value = orgHeatNum ? orgHeatNum : billetNos.length;
    showAddHeat.value = true;
    editDtl.value = headDtl.value[index];
  };

  const headValue = ref<number | null>();
  const heatNum = ref<number | null>();
  const showAddHeat = ref(false);
  const editDtl = ref();
  const addHeatDtl = () => {
    headValue.value = null;
    heatNum.value = null;
    showAddHeat.value = true;
  };
  const confirmAddHeatDtl = () => {
    if (headValue.value && heatNum.value) {
      if (editDtl.value && editDtl.value.heatNo) {
        const index = headDtl.value.findIndex((item) => item.heatNo === editDtl.value.heatNo);
        headDtl.value[index] = {
          ...headDtl.value[index],
          heatNo: headValue.value,
          heatNum: heatNum.value,
        };

        editDtl.value = {};
      } else {
        headDtl.value.push({
          id: headValue.value + '-' + heatNum.value,
          heatNo: headValue.value,
          heatNum: heatNum.value,
        });
      }
      showAddHeat.value = false;
    } else {
      createMessage.warning('请填写炉号和支数');
    }
  };

  const changeBtype = () => {
    info.value.btype = info.value.btype == '1' ? '0' : '1';
  };

  // 修改目的地
  function handleDestinationIdChange(v) {
    if (v) {
      const cur = destinationOptions[info.value.ccmNo].find((item) => item.value === v);
      info.value.destination = cur.label;
    } else {
      info.value.destination = '';
    }
  }

  function onPrint() {
    changeOkLoading(true);

    if (!info.value.destination || !info.value.typeConfigId || info.value.typeConfigId === '1024') {
      createMessage.error('请选择目的地！');
      return;
    }

    let headDtlObj = {};
    headDtl.value.forEach((item) => {
      headDtlObj[item.heatNo] = item.heatNum ? item.heatNum : item.billetNos.length;
    });
    if (isCanEdit) {
      saveBeforePrint({
        amountTotal: info.value.amountTotal,
        arrivalTime: info.value.arrivalTimeDay.format('YYYY-MM-DD HH:mm:ss'),
        brandNum: info.value.brandNum,
        destination: info.value.destination,
        heatNo: headDtlObj,
        licensePlate: info.value.licensePlate,
        name: '方坯',
        size: info.value.size,
        storageBillId: info.value.id,
        weight: info.value.weight,
        number: info.value.number,
        classes: info.value.shift + '/' + info.value.shiftGroup,
        btype: info.value.btype,
        ccmNo: info.value.ccmNo,
      }).then((res) => {
        emits('success', res);
        closeModal();
      });
    }

    if (isEditCard.value !== true) {
      printJS({
        printable: '#printContent',
        type: 'html',
      });
    }
    setTimeout(() => {
      changeOkLoading(false);
    }, 1000);
  }
</script>

<style lang="less">
  #printContent {
    .lgprint-date-picker {
      font-size: 14px;
      padding: 0;

      .ant-picker-input > input {
        font-size: 14px;
        text-align: center;
      }

      .ant-picker-suffix {
        display: none;
      }
    }

    .ant-select {
      &.ant-select-single .ant-select-selector {
        font-size: 14px;
        padding: 0;
      }

      .ant-select-selection-item {
        padding-inline-end: 0;
      }

      .ant-select-arrow {
        display: none;
      }
    }

    .heatNo-item {
      position: relative;
      min-width: 100px;

      .op {
        position: absolute;
        right: 0;
        top: 0;
        font-size: 18px;
        cursor: pointer;
        width: 18px;
        height: 18px;
        line-height: 12px;
        border-radius: 18px;
        text-align: center;
        background: #f5f5f5;
        border: 1px solid #625dfa;
        display: none;
      }

      .jian {
        right: 25px;
        background-color: rgb(255, 205, 205);
        border: 1 solid #fa5d5d;
      }

      &:hover {
        .op {
          display: block;
        }
      }
    }

    .add-heatNo {
      position: absolute;
      right: 0;
      top: 0;
      font-size: 18px;
      cursor: pointer;
      width: 18px;
      height: 18px;
      line-height: 12px;
      border-radius: 18px;
      text-align: center;
      background: #f5f5f5;
      border: 1px solid #625dfa;
      display: none;
    }

    .heat-wrapper {
      &:hover {
        .add-heatNo {
          display: block;
        }
      }
    }
  }

  .mask-disabled-edit {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 10;
  }
  @media print {
    header,
    footer,
    .noprint {
      display: none;
    }

    @page :first {
      margin-top: 10px; /* 第一页的页眉距离顶部为0 */
      margin-bottom: 0; /* 第一页的页脚距离底部为0 */
    }
  }
</style>
