<template>
  <section class="printContent">
    <div class="ticket next-ticket">
      <div class="flex" style="line-height: 32px">
        <div class="flex-1">
          库名：
          <JSearchSelect
            v-if="!info.destination && info.id"
            type="list"
            style="width: 160px"
            v-model:value="info.typeConfigId"
            :options="destinationOptions[ccmNo]"
            placeholder="请选择"
            allowClear
            @change="(v) => handleSelectChange(v, 'destination')"
            ref="destinationRef"
          />
          <span v-else>{{ info.destination }}</span>
          <a-button
            style="margin-left: 10px"
            v-if="!info.outTime && info.id && info.destination"
            type="primary"
            :loading="btnLoading"
            @click="sendCar"
          >
            发车
          </a-button>
          <a-button
            style="margin-left: 10px"
            v-if="commonPositon.includes(String(carPositon)) && !info.outTime && info.id"
            type="primary"
            :loading="btnLoading"
            @click="updateCcmNo"
          >
            变更#{{ info.ccmNo == '5' ? '6' : '5' }}
          </a-button>
        </div>
        <div class="flex-1" style="text-align: center; font-size: 16px">{{ dayjs(info.arrivalTime).format('YYYY 年 MM 月 DD 日 HH 时 mm 分') }}</div>
        <div class="flex-1" style="text-align: right; font-size: 16px"></div>
      </div>
      <a-descriptions layout="vertical" bordered :column="8" size="small">
        <a-descriptions-item label="序号">
          <div style="min-height: 80px; display: flex; align-items: center; justify-content: center">
            <span>{{ info.carAllNum }}</span>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="车号">
          <!-- {{ info.licensePlate }} -->
          <JSearchSelect
            type="list"
            v-if="!info.outTime && info.id"
            style="width: 117px"
            v-model:value="info.licensePlate"
            dict="lg_car"
            @change="(v) => handleSelectChange(v, 'licensePlate')"
            placeholder="请选择"
            allowClear
          />
          <span v-else>{{ info.licensePlate }}</span>
        </a-descriptions-item>
        <a-descriptions-item label="牌号">
          <JSearchSelect
            type="list"
            v-if="!info.outTime && info.id"
            style="width: 117px"
            v-model:value="info.brandNum"
            dict="billet_spec"
            @change="(v) => handleSelectChange(v, 'brandNum')"
            placeholder="请选择"
            allowClear
          />
          <span v-else>
            <component :is="renderDictTag(info.brandNum, 'billet_spec')" />
          </span>
        </a-descriptions-item>
        <a-descriptions-item style="position: relative; text-align: left" label="炉号">
          <div v-for="item in headDtl" :key="item.heatNo">{{ item.heatNo }} - {{ item.nums }}</div>
          <div class="correct" v-if="!info.outTime && info.id && headDtl.length > 0">
            <a-button
              size="small"
              type="primary"
              @click="
                () => openDetailModal(true, { record: { ...info, typeConfigId: !info.typeConfigId ? '1024' : info.typeConfigId }, isUpdate: true })
              "
            >
              修正
            </a-button>
          </div>
        </a-descriptions-item>
        <a-descriptions-item label="规格">
          170 /
          <JSearchSelect
            class="size-input"
            type="list"
            v-if="!info.outTime && info.id"
            style="width: 80px; text-align: left"
            v-model:value="info.size"
            dict="lg_dcgg"
            @change="(v) => handleSelectChange(v, 'size')"
            placeholder="请选择"
            allowClear
          />
          <span v-else>
            {{ info.size }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="名称"> 方坯 </a-descriptions-item>
        <a-descriptions-item label="支数">
          {{ info.amountTotal }}
        </a-descriptions-item>
        <!-- <a-descriptions-item label="重量（t）">
          {{ weight > 0 ? weight.toFixed(3) : 0 }}
        </a-descriptions-item> -->
      </a-descriptions>
    </div>
  </section>
  <!-- 详情  -->
  <correct @register="registerDetailModal" showActionColumn @success="() => getTableList()" />
</template>

<script lang="ts" setup>
  import { ref, h, computed } from 'vue';
  import dayjs from 'dayjs';
  import { listShippingBill, startCar, edit } from '../../shippingBill/shippingBill.api';
  import { destinationOptions } from '../../hotDelivery/common.data';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { render } from '/@/utils/common/renderUtils';
  import correct from './correct.vue';
  import { useModal } from '/@/components/Modal';

  const { createConfirm, createMessage } = useMessage();

  // 棒线堆垛明细
  const [registerDetailModal, { openModal: openDetailModal }] = useModal();

  const emits = defineEmits(['change', 'refresh']);

  const props = defineProps({
    ccmNo: {
      type: [String, Number],
      default: '5',
    },
    api: {
      type: Function as PropType<(params: any) => Promise<any>>,
      default: listShippingBill,
    },
    info: {
      type: Object,
      default: () => {},
    },
    carPositon: {
      type: [Number, String],
      default: 1,
    },
  });

  const destinationRef = ref<any>(null);
  // const headDtl = ref<any[]>([]);
  const weight = ref<number>(0);
  const sizeInfo = ref<string[]>([]);
  // 共用的车位
  const commonPositon = ['2', '4'];
  // 渲染字典标签
  const renderDictTag = (value: string, dictCode: string) => {
    return render.renderDict(value, dictCode);
  };

  // 获取炉号
  //  headDtl.value = newArr;
  //     weight.value = allWeight;
  //     sizeInfo.value = sizeArr;
  const headDtl = computed(() => {
    if (!props.info || !props.info.heatNoCountMap) return [];

    return Object.keys(props.info.heatNoCountMap).map((item) => {
      return { heatNo: item, nums: props.info.heatNoCountMap[item] };
    });
  });

  const getTableList = async () => {
    return;
    try {
      const { id, ccmNo, heatNo, typeConfigId } = props.info;
      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;
    } catch (error) {
      console.log(error);
    } finally {
    }
  };

  const handleSelectChange = (v: any, type: string) => {
    emits('change', { value: v, type, carPositon: props.carPositon });
  };

  // 发车
  const btnLoading = ref(false);
  const sendCar = async () => {
    try {
      if (!props.info.destination) {
        createMessage.error('请选择库名');
        return;
      }

      if (!props.info.licensePlate) {
        createMessage.error('请选择车牌号');
        return;
      }

      createConfirm({
        iconType: 'warning',
        title: '请确认是否发车?',
        onOk: () => {
          return startCar({ ...props.info }).then(() => {
            emits('refresh');
          });
        },
      });
    } catch (error) {
      console.log(error);
    }
  };

  // 修改铸机号
  const updateCcmNo = async () => {
    try {
      if (!props.info.id) {
        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' } }, `${props.info.ccmNo}#机 `),
            h('span', null, ` 改为 `),
            h('span', { style: { fontSize: '18px', color: '#3b5999' } }, ` ${props.info.ccmNo == '5' ? ' 6 ' : ' 5 '}#机`),
            h('span', null, `?`),
          ]);
        },
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          return edit({ ...props.info, ccmNo: props.info.ccmNo == '5' ? '6' : '5' }).then(() => {
            emits('refresh');
          });
        },
      });
    } catch (error) {
      console.log(error);
    }
  };

  defineExpose({
    getTableList,
    focusDestination: () => {
      // destinationRef.value && destinationRef.value.handleAsyncFocus();
    },
  });
</script>
<style lang="less" scoped>
  .printContent {
    padding: 10px;
    position: relative;
    border: 1px solid #c5c5c5;
    background: #01396c;
    width: 100%;
    border-radius: 4px;
    color: #fff;

    .ant-descriptions {
      margin-top: 6px;
      margin-bottom: 4px;
    }

    .correct {
      position: absolute;
      right: 2px;
      top: -32px;
    }

    :deep(.ant-descriptions-view) {
      .ant-descriptions-item-label,
      .ant-descriptions-item-content {
        border: 1px solid #bfbfbf;
        font-size: 16px;
        padding: 4px;
        text-align: center;
        height: 36px;
        color: #fff;
      }
    }

    .size-input {
      :deep(.ant-select-selector) {
        padding: 0 4px;
      }
    }
  }
</style>
