<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      title="批量调拨单明细"
      width="90%"
      :destroy-on-close="true"
      @close="close"
    >
      <el-row style="margin-bottom: 20px">
        <template v-if="props.isApply">
          <el-button
            plain
            type="primary"
            icon="Edit"
            @click="handelApply"
          >
            审批通过
          </el-button>
          <el-button
            type="primary"
            plain
            icon="Edit"
            @click="handleReject"
          >
            驳回
          </el-button>
        </template>
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="handleExport"
        >
          导出
        </el-button>
        <el-button
          type="warning"
          plain
          icon="Printer"
          @click="handlePrint"
        >
          打印单据
        </el-button>
      </el-row>
      <el-descriptions
        :column="5"
        style="margin-bottom: 10px"
      >
        <el-descriptions-item label="单据号:">
          {{ detailsList[0]?.busNo || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="源仓库:">
          {{ detailsList[0]?.sourceLocationName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="目的仓库:">
          {{ detailsList[0]?.purposeLocationName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="项目类型:">
          {{ detailsList[0]?.itemType_dictText || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="制单日期:">
          {{ proxy.formatDateStr(detailsList[0]?.occurrenceTime, 'YYYY-MM-DD HH:mm:ss') || '-' }}
        </el-descriptions-item>
      </el-descriptions>
      <el-table
        v-loading="loading"
        :data="detailsList"
        border
        max-height="650"
      >
        <el-table-column
          label="序号"
          width="60"
          type="index"
          align="center"
        />
        <el-table-column
          label="项目名称"
          align="center"
          prop="name"
        />
        <el-table-column
          label="规格"
          align="center"
          prop="totalVolume"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="厂家/产地"
          align="center"
          prop="manufacturerText"
          width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="产品批号"
          align="center"
          prop="lotNumber"
        />
        <el-table-column
          label="单价"
          align="right"
          header-align="center"
          prop="price"
          width="120"
        >
          <template #default="scope">
            {{ scope.row.price?.toFixed(2) + ' 元' }}
          </template>
        </el-table-column>
        <el-table-column
          label="调拨单位"
          align="center"
          prop="measurementUnitCode_dictText"
          width="80"
        />
        <el-table-column
          label="源库存数"
          align="right"
          header-align="center"
          prop="itemName"
          width="100"
        >
          <template #default="scope">
            {{ formatQuantity(Number(scope.row.totalSourceQuantity), scope.row) }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="目的库存数"
          align="right"
          header-align="center"
          prop="itemName"
          width="100"
        >
          <template #default="scope">
            {{
              formatQuantity(
                Number(scope.row.itemQuantity) - Number(scope.row.totalSourceQuantity),
                scope.row
              )
            }}
          </template>
        </el-table-column> -->
        <el-table-column
          label="调拨数量"
          align="right"
          header-align="center"
          prop="totalQuitemQuantityantity"
          width="100"
        >
          <template #default="scope">
            {{ formatQuantity(scope.row.itemQuantity, scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          label="合计金额"
          align="right"
          header-align="center"
          prop="totalPrice"
          width="120"
        >
          <template #default="scope">
            {{ scope.row.totalPrice?.toFixed(2) + ' 元' }}
          </template>
        </el-table-column>
        <el-table-column
          label="生产日期"
          align="center"
          prop="startTime"
          width="120"
        >
          <template #default="scope">
            {{ proxy.formatDateStr(scope.row.startTime, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column
          label="有效期至"
          align="center"
          prop="endTime"
          width="120"
        >
          <template #default="scope">
            {{ proxy.formatDateStr(scope.row.endTime, 'YYYY-MM-DD') }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            关 闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {getCurrentInstance} from 'vue';
import {getTransferProductDetail, productTransferApproved, reject} from './transferManagement';
import templateJson from './template.json';
import {hiprint} from 'vue-plugin-hiprint';
import useUserStore from '@/store/modules/user';

const detailsList = ref([]);
const dialogVisible = ref(false);
const loading = ref(false);
const supplyBusNo = ref('');
const userStore = useUserStore();
const { proxy } = getCurrentInstance();

const props = defineProps({
  isApply: {
    type: Boolean,
    default: false,
  },
});

function open(busNo) {
  dialogVisible.value = true;
  supplyBusNo.value = busNo;
  loading.value = true;
  getTransferProductDetail({ busNo: busNo, pageSize: 1000, pageNo: 1 }).then((res) => {
    detailsList.value = res.data.records;
    loading.value = false;
  });
}

function formatQuantity(quantity, row) {
  if (row.measurementUnitCode == row.unitCode) {
    return formatInventory(
      quantity,
      row.partPercent,
      row.unitCode_dictText,
      row.minUnitCode_dictText
    );
  } else {
    return quantity + row.minUnitCode_dictText;
  }
}

function handelApply() {
  loading.value = true;
  productTransferApproved(supplyBusNo.value).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('操作成功');
      loading.value = false;
    }
  });
}

function handleReject() {
  reject(supplyBusNo.value).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('操作成功');
    }
  });
}

/**
 * 格式化库存数量显示(大单位情况)
 * @param quantity 小单位库存数量
 * @param partPercent 拆零比
 * @param unitCode 大单位
 * @param minUnitCode 小单位
 */
function formatInventory(quantity, partPercent, unitCode, minUnitCode) {
  // 处理负数情况
  const isNegative = quantity < 0;
  const absQuantity = Math.abs(quantity);

  if (absQuantity % partPercent !== 0) {
    const integerPart = Math.floor(absQuantity / partPercent);
    const decimalPart = absQuantity % partPercent;

    let result = integerPart.toString() + ' ' + unitCode;
    if (decimalPart > 0) {
      result += decimalPart.toString() + ' ' + minUnitCode;
    }

    return isNegative ? '-' + result : result;
  }

  // 整除情况
  const result = absQuantity / partPercent + ' ' + unitCode;
  return isNegative ? '-' + result : result;
}

// 打印盘点单
function handlePrint() {
  const result = [];
  const printList = detailsList.value.map((item) => {
    return {
      ...item,
      volume: item.totalVolume,
      price: Number(item.price).toFixed(2) + ' 元',
      totalPrice: Number(item.totalPrice).toFixed(2) + ' 元',
      totalSourceQuantity: formatQuantity(Number(item.totalSourceQuantity), item),
      itemQuantity: formatQuantity(Number(item.itemQuantity), item),
      profitAmount: ((item.itemQuantity * item.price) / item.partPercent).toFixed(2),
    };
  });
  result.push({
    purposeLocationName: printList[0].purposeLocationName,
    sourceLocationName: printList[0].sourceLocationName,
    itemType_dictText: printList[0].itemType_dictText,
    name: userStore.name,
    occurrenceTime: proxy.formatDateStr(printList[0].occurrenceTime, 'YYYY-MM-DD HH:mm:ss'),
    busNo: printList[0].busNo,
    detailsList: printList,
  });
  const printElements = JSON.parse(
    JSON.stringify(templateJson).replace(/{{HOSPITAL_NAME}}/g, userStore.hospitalName)
  );
  var hiprintTemplate = new hiprint.PrintTemplate({ template: printElements }); // 定义模板
  hiprintTemplate.print2(result, {
    title: '打印标题',
  }); //开始打印
}
function handleExport() {
  proxy.downloadGet(
    '/inventory-manage/transfer/excel-out',
    {
      busNo: supplyBusNo.value,
    },
    `批量调拨单据明细记录_${proxy.formatDateStr(new Date(), 'YYYY-MM-DD')}.xlsx`
  );
}
defineExpose({
  open,
});
</script>