<template>
  <div class="storageAndTransportation flex flex-col">
    <div class="search-wrapper">
      <BasicForm class="search-form" @register="registerForm" @submit="handleSubmit" @reset="handleSubmit">
        <template #ccmNo="{ model, field }">
          <segmented-select
            v-model:value="model[field]"
            @change="
              () => {
                handleSubmit();
              }
            "
            dict="lg_zj"
          />
        </template>
        <template #advanceBefore>
          <a-button type="primary" preIcon="ant-design:export-outlined" style="margin-right: 10px" @click="onExportXls"> 导出</a-button>
          <a-button type="primary" preIcon="ant-design:export-outlined" style="margin-right: 10px" @click="onExportTicketsXls"> 导出票据</a-button>
        </template>
      </BasicForm>
    </div>
    <a-list item-layout="vertical" size="large" :loading="loading" :data-source="listData">
      <template #renderItem="{ item, index }">
        <a-list-item key="item.heatNo">
          <a-list-item-meta>
            <template #title>
              <span>炉号：{{ item.heatNo }}</span>
              <span style="padding: 0 20px"> 总支数：{{ item.heatNoAmount }} </span>
              <span> 总重量：{{ item.heatNoWeight }} t </span>
              <span style="padding: 0 20px"> 开始时间：{{ item.createTime }} </span>
            </template>
            <template #avatar>
              <a-tag color="#108ee9">{{ index + 1 }}</a-tag>
            </template>
          </a-list-item-meta>
          <div class="flex heat-wrapper">
            <div class="items-content flex-1" :style="{ width: 100 / item.content.length + '%' }" v-for="pval in item.content">
              <a-card>
                <template #title>
                  <div class="customer-title flex">
                    <img src="/@/assets/images/send.png" v-if="pval.type === 'line'" alt="" class="heat-img" />
                    <img src="/@/assets/images/charge.png" v-if="pval.type === 'car'" alt="" class="heat-img" />
                    <div class="heat-title">
                      {{ pval.title }} 【{{ pval.type == 'car' ? pval.content['rollChargeDetails'].length : pval.content['rollSendDetails'].length }}
                      条记录】
                    </div>
                  </div>
                </template>
                <template v-if="pval.type == 'car'">
                  <div class="ticket next-ticket" v-for="(sval, i) in pval.content['rollChargeDetails']">
                    <a-descriptions size="small">
                      <a-descriptions-item label="库名"> {{ pval.title }} </a-descriptions-item>
                      <a-descriptions-item> {{ dayjs(sval.createTime).format('YYYY 年 MM 月 DD 日 HH 时 mm 分') }} </a-descriptions-item>
                      <a-descriptions-item>
                        <div style="width: 100%; text-align: right">
                          <a-tag v-if="sval.btype == 1">冷装</a-tag>
                          <a-tag color="#f50" v-else>热装</a-tag>
                        </div>
                      </a-descriptions-item>
                    </a-descriptions>
                    <a-descriptions class="ticket-content" layout="vertical" bordered :column="8" size="small">
                      <a-descriptions-item label="序号">{{ sval.carNum }}</a-descriptions-item>
                      <a-descriptions-item label="炉号">{{ sval.heatNo }}</a-descriptions-item>
                      <a-descriptions-item label="车号">{{ sval.licensePlate }}</a-descriptions-item>
                      <a-descriptions-item label="类型"><component :is="renderDictTag(sval.btype, 'lg_btype')" /></a-descriptions-item>
                      <a-descriptions-item label="定尺">{{ sval.size }}</a-descriptions-item>
                      <a-descriptions-item label="牌号"><component :is="renderDictTag(sval.brandNum, 'billet_spec')" /></a-descriptions-item>
                      <a-descriptions-item label="支数">{{ sval.amount }}</a-descriptions-item>
                      <a-descriptions-item label="重量">{{ sval.weight }}</a-descriptions-item>
                    </a-descriptions>
                  </div>
                </template>
                <a-table
                  v-else
                  class="heat-s-table"
                  size="small"
                  :scroll="{ y: 300 }"
                  :columns="columnLine"
                  :pagination="false"
                  :data-source="pval.content['rollSendDetails']"
                />
              </a-card>
            </div>
          </div>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>

<script lang="ts" name="storageAndTransportation" setup>
  import { onMounted, ref } from 'vue';
  //引入依赖
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  import { getStorageCenterInvoicingInfo, exportExcel, exportInvoice } from './storageAndTransportation.api';
  import SegmentedSelect from '/@/components/SegmentedSelect/index.vue';
  import { isArray } from '/@/utils/is';
  import dayjs from 'dayjs';
  import { render } from '/@/utils/common/renderUtils';
  import { useMethods } from '/@/hooks/system/useMethods';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  //导入导出方法
  const { handleExportXlsx } = useMethods();

  // 渲染字典标签
  const renderDictTag = (value: string, dictCode: string) => {
    return render.renderDict(value, dictCode);
  };

  //自定义表单字段
  const formSchemas: FormSchema[] = [
    {
      field: 'ccmNo',
      label: '铸机',
      component: 'Input',
      defaultValue: '5',
      componentProps: {
        dictCode: 'lg_zj',
      },
      colProps: { span: 6 },
      slot: 'ccmNo',
    },
    {
      label: '炉号',
      field: 'heatsCode',
      component: 'Input',
    },
    {
      label: '班组',
      field: 'shiftGroup',
      component: 'JDictSelectTag',
      componentProps: {
        dictCode: 'lg_bz',
      },
    },
    {
      label: '班别',
      field: 'shift',
      component: 'JDictSelectTag',
      componentProps: {
        dictCode: 'lg_bb',
      },
    },
    // {
    //   label: '炉次日期',
    //   field: 'createTime',
    //   component: 'RangePicker',
    //   componentProps: {
    //     valueFormat: 'YYYY-MM-DD',
    //   },
    // },
    {
      label: '装运日期',
      field: 'storageTime',
      component: 'RangePicker',
      componentProps: {
        showTime: true,
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
      },
    },
    {
      label: '票据打印时间',
      field: 'receipt',
      component: 'DatePicker',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
    },
  ];
  /**
   * BasicForm绑定注册;
   */
  const [registerForm, { getFieldsValue }] = useForm({
    //注册表单列
    schemas: formSchemas,
    //是否显示展开收起按钮，默认false
    showAdvancedButton: true,
    //超过指定行数折叠，默认3行
    autoAdvancedCol: 3,
    //折叠时默认显示行数，默认1行
    alwaysShowLines: 3,
    //将表单内时间区域的值映射成 2个字段, 'YYYY-MM-DD'日期格式化
    fieldMapToTime: [
      ['createTime', ['createTime_begin', 'createTime_end'], 'YYYY-MM-DD HH:mm:ss'],
      ['storageTime', ['storageTime_begin', 'storageTime_end'], 'YYYY-MM-DD HH:mm:ss'],
    ],
    //每列占比，默认一行为24
    baseColProps: { span: 6 },
  });

  /**
   * 点击提交按钮的value值
   * @param values
   */
  function handleSubmit() {
    getList();
  }

  const listData = ref<Record<string, any>>([]);
  const loading = ref(false);
  const columnLine = [
    { title: '日期', dataIndex: 'createTime' },
    { title: '定尺', dataIndex: 'size' },
    { title: '规格', dataIndex: 'spec' },
    { title: '支数', dataIndex: 'amount' },
    { title: '重量/t', dataIndex: 'weight' },
  ];

  const getList = async () => {
    try {
      loading.value = true;
      const values = getFieldsValue();

      if (!values.ccmNo) {
        values.ccmNo = '5';
      }
      console.log('values', values);

      const params = Object.assign({}, values, {
        createTimeBegin: values.createTime_begin,
        createTimeEnd: values.createTime_end,
        storageTimeBegin: values.storageTime_begin,
        storageTimeEnd: values.storageTime_end,
      });

      const records = await getStorageCenterInvoicingInfo(params);
      if (records && isArray(records)) {
        const list = records.map((item: any) => {
          let content: any[] = [];
          const {
            heatNoDetails,
            storageCenterHeatNoInvoicing: {
              rollClubOneDetails,
              rollClubTwoDetails,
              rollClubThreeDetails,
              rollHeightDetails,
              rollOutShippDetails,
              rollDeputyDetails,
            },
          } = item;

          if (rollClubOneDetails) {
            content.push({
              title: '棒一',
              type: 'line',
              content: rollClubOneDetails,
            });
          }

          if (rollClubTwoDetails) {
            content.push({
              title: '棒二',
              type: 'car',
              content: rollClubTwoDetails,
            });
          }

          if (rollClubThreeDetails) {
            content.push({
              title: '棒三',
              type: 'car',
              content: rollClubThreeDetails,
            });
          }

          if (rollDeputyDetails) {
            content.push({
              title: '付跨',
              type: 'car',
              content: rollDeputyDetails,
            });
          }

          if (rollOutShippDetails) {
            content.push({
              title: '上若',
              type: 'car',
              content: rollOutShippDetails,
            });
          }

          if (rollHeightDetails) {
            content.push({
              title: '高线',
              type: 'line',
              content: rollHeightDetails,
            });
          }

          return {
            ...heatNoDetails[0],
            content,
          };
        });

        listData.value = list;
      }

      loading.value = false;
    } catch (error) {
      console.error(error);
      loading.value = false;
    }
  };

  // 导出
  const onExportXls = () => {
    const values = getFieldsValue();

    if (!values.storageTime_begin) {
      createMessage.error('请选择装运日期');
      return;
    }

    if (!values.ccmNo) {
      values.ccmNo = '5';
    }

    const params = Object.assign({}, values);

    let queryParams = Object.keys(params)
      .filter((v) => params[v])
      .map((key) => {
        if (key === 'createTime_begin') {
          return `createTimeBegin=${params[key]}`;
        }
        if (key === 'createTime_end') {
          return `createTimeEnd=${params[key]}`;
        }
        if (key === 'storageTime_begin') {
          return `storageTimeBegin=${params[key]}`;
        }
        if (key === 'storageTime_end') {
          return `storageTimeEnd=${params[key]}`;
        }
        return `${key}=${params[key]}`;
      });

    return handleExportXlsx('储运中心', exportExcel() + (queryParams.length > 0 ? '?' + queryParams.join('&') : ''));
  };

  const onExportTicketsXls = () => {
    const values = getFieldsValue();
    console.log('values', values);
    let queryParams = Object.keys(values)
      .filter((v) => values[v])
      .map((key) => {
        return `${key}=${values[key]}`;
      });

    if (!values['receipt']) {
      queryParams.push(`arrivalTime=${dayjs().format('YYYY-MM-DD 00:00:00')}`);
      queryParams.push(`createTime=${dayjs().format('YYYY-MM-DD 23:59:59')}`);
    } else {
      queryParams.push(`arrivalTime=${values['receipt']} 00:00:00`);
      queryParams.push(`createTime=${values['receipt']} 23:59:59`);
    }
    return handleExportXlsx('储运票据', exportInvoice() + (queryParams.length > 0 ? '?' + queryParams.join('&') : ''));
  };

  onMounted(() => {
    getList();
  });
</script>

<style lang="less" scoped>
  .storageAndTransportation {
    margin: 10px;

    .search-wrapper {
      margin-bottom: 10px;
      background-color: #fff;
      padding-top: 30px;

      .search-form {
        :deep(.btnArea) {
          .ant-form-item-row {
            width: 100%;
            justify-content: flex-end;
          }
        }
      }
    }

    .ant-list {
      background-color: #fff;
      padding: 10px;
    }

    .heat-wrapper {
      gap: 10px;
    }

    .items-content {
      flex-shrink: 0;
    }

    .customer-title {
      line-height: 32px;
    }

    .heat-img {
      width: 32px;
      height: 32px;
    }

    .heat-title {
      margin-left: 8px;
      margin-right: 60px;
      font-weight: 400;
      font-size: 14px;
      color: #000000;
    }

    .ant-card {
      width: 100%;
      height: 100%;
      overflow: hidden;

      :deep(.ant-card-body) {
        padding: 10px;
        display: flex;
        overflow: auto;

        &::after,
        &::before {
          display: none;
        }
      }
    }

    /* 基础票据样式 */
    .ticket {
      width: 672px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 5px 0px 6px 2px rgba(0, 0, 0, 0.25);
      padding: 10px;
      position: relative;
      border-left: 4px solid #ddd;
      transition: transform 0.2s;
      margin-right: 10px;
      flex-shrink: 0;

      &:last-child {
        margin-right: 0;
      }
    }

    /* 下一个票据的特殊样式 */
    .next-ticket {
      border-left-color: #0958d9; /* 左侧高亮蓝色边框 */
      background: #f8f9fa; /* 浅灰色背景 */
    }
  }
</style>
