<template>
  <!-- 公共详情  -->
  <el-card class="hl-card" style="position: relative">
    <template #header>
      <span><span v-html="dialogTitle"></span>页</span>
    </template>
    <div class="abstatus">
      <div v-if="formData.deliverStatus == 2">
        <img src="/src/assets/imgs/status/deliver.png" alt="" />
      </div>

    </div>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="140px" v-loading="formLoading">
      <!-- 基础信息 横向布局 -->
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">基础信息</span>
        </template>
        <el-row>
          <el-col :span="6">
            <el-form-item label="发货单号" prop="code">
              <el-input disabled v-model="formData.code" placeholder="系统自动生成" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目编号" prop="saleOrderIds">
              <!-- <el-input disabled v-model="formData.saleOrderCode" placeholder="请输入项目编号" class="!w-250px">
                <template #append><el-button :disabled="active != 'create'" @click="openProjectOrderDialog" :icon="Search" /> -->
              <el-input class="!w-250px" :disabled="active != 'create'" v-model="formData.saleOrderCode" @click.prevent="handleClick" :readonly="!isEditing" placeholder="请输入项目编号">
                <template #append><el-button :disabled="active != 'create'" :icon="Search" @click="openProjectOrderDialog" /></template>
              </el-input>

            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="contractNo" label="合同号">
              <el-input v-model="formData.contractNo" disabled class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="property" label="性质">
              <el-input v-model="formData.property" disabled class="!w-250px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="发货日期" prop="deliverDate">
              <el-date-picker :disabled="detailDisabled" v-model="formData.deliverDate" type="date" value-format="x" placeholder="选择发货日期" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="customerId" label="客户名称">
              <el-input v-model="formData.customerName" disabled class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item prop="projectName" label="项目名称">
              <el-input disabled v-model="formData.projectName" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货单状态" prop="deliverStatus">
              {{getDictLabel(DICT_TYPE.HELI_DELIVER_ORDER_STATUS, formData.deliverStatus)}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发货备注" prop="remark">
              <el-input :disabled="detailDisabled" type="textarea" v-model="formData.remark" show-word-limit maxlength="200" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">发货信息</span>
        </template>
        <el-row>
          <el-col :span="6">
            <el-form-item label="发货人姓名" prop="deliverPerson">
              <UserSelect :disabled="detailDisabled" v-model="formData.deliverPerson" @update:new-value="handleSelectedUser" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货人电话" prop="deliverPersonMobile">
              <el-input :disabled="detailDisabled" v-model="formData.deliverPersonMobile" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货方式" prop="deliverMode">
              <el-select clearable :disabled="detailDisabled" v-model="formData.deliverMode" placeholder="请选择发货方式" class="!w-250px">
                <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HELI_DELIVER_MODE)" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货单位" prop="deliverCompany">
              <el-input v-model="formData.deliverCompany" disabled class="!w-250px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info" v-if="active != 'create'">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">收货信息</span>
        </template>
        <el-row>
          <el-col :span="6">
            <el-form-item label="收货人姓名" prop="receivePersonName">
              <el-select :disabled="detailDisabled" v-model="formData.receivePersonName" filterable allow-create clearable @change="receiveOnChange" @blur="e => { if(e.target.value) formData.receivePersonName = e.target.value;}">
                <el-option v-for="dict in receivePersonOptions" :key="dict.name" :label="dict.name" :value="dict.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收货人电话" prop="receivePersonMobile">
              <el-input :disabled="detailDisabled" v-model="formData.receivePersonMobile" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货详细地址" prop="receiveAddress">
              <el-select v-model="formData.receiveAddress" filterable allow-create :disabled="detailDisabled" @blur="e => { if(e.target.value) formData.receiveAddress = e.target.value;}" clearable style="width: 100%;margin-right: 1.5%">
                <el-option v-for="dict in receivePersonAddressOptions" :key="dict.address" :label="dict.address" :value="dict.address" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">物流信息</span>
        </template>
        <el-row>
          <el-col :span="6">
            <el-form-item label="司机姓名" prop="transportDriverName">
              <el-input :disabled="detailDisabled" v-model="formData.transportDriverName" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="司机电话" prop="transportDriverMobile">
              <el-input :disabled="detailDisabled" v-model="formData.transportDriverMobile" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车牌号" prop="transportBusNumber">
              <el-input :disabled="detailDisabled" v-model="formData.transportBusNumber" class="!w-250px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="重量(T)" prop="transportWeight" >
              <el-input :disabled="detailDisabled" v-model="formData.transportWeight" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="位置(米)" prop="transportSize">
              <el-input :disabled="detailDisabled" v-model="formData.transportSize" class="!w-250px" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="运费成本(元)" prop="transportFreightCost">
              <el-input :disabled="detailDisabled" v-model="formData.transportFreightCost" @blur="yunFei()" class="!w-250px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info" v-if="active != 'create'">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">发货清单</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-form ref="subFormRef" :model="formData.deliverOrderSubs" :rules="subFormRules" v-loading="subFormLoading" label-width="0">
                <el-table :data="formData.deliverOrderSubs" class="hl-table">
                  <el-table-column label="序号" type="index" width="100" />
                  <el-table-column min-width="150" align="center">
                    <template #header> <span class="hl-table_header">*</span>子项目名称 </template>
                    <template #default="scope">
                      {{scope.row.name}}
                    </template>
                  </el-table-column>
                  <el-table-column label="项目编号" min-width="220" align="center">
                    <template #default="scope">
                      {{scope.row.saleOrderCode}}
                    </template>
                  </el-table-column>
                  <el-table-column label="子项目图号" min-width="200" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.blueprintNo`" :rules="subFormRules.blueprintNo" class="mb-0px!">
                        <el-input :disabled="detailDisabled" v-model="row.blueprintNo" placeholder="请输入子项目图号" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="本次发货数量" min-width="150">
                    <template #header> <span class="hl-table_header">*</span>本次发货数量 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.amount`" :rules="subFormRules.amount" class="mb-0px!">
                        <el-input-number :disabled="detailDisabled" v-model="row.amount" placeholder="请输入本次发货数量" style="width: 100%" :min="1" :max="row.amount"  /><!-- :precision="0" -->
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="单位" width="80">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.unit`" :rules="subFormRules.unit" class="ml-10px mb-0px!">
                        {{getDictLabel(DICT_TYPE.HELI_MATERIAL_UNIT, row.unit)}}
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="重量(T)" min-width="150" align="center">
                    <template #header> <span class="hl-table_header">*</span>重量(T)</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.weight`" :rules="subFormRules.weight" class="mb-0px!">
                        <el-input :disabled="detailDisabled" v-model="row.weight" @blur="yunFei()" placeholder="请输入重量(T)" />
                      </el-form-item>
                    </template>
                  </el-table-column>
					<el-table-column label="运费" min-width="100" align="center">
					  <template #default="scope">
					    {{scope.row.yunFei}}
					  </template>
					</el-table-column>
                  <el-table-column label="尺寸(米)" min-width="150" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.size`" class="mb-0px!">
                        <el-input :disabled="detailDisabled" v-model="row.size" placeholder="请输入尺寸(米)" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" min-width="180" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
                        <el-input :disabled="detailDisabled" v-model="row.remark" placeholder="请输入备注" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" min-width="100">
                    <template #default="scope">
                      <el-button v-if="'update,create,deliver'.indexOf(active) > -1" link type="danger" size="small" @click.prevent="onDeleteItem(scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info" v-if="active != 'create'">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">其他物料清单</span>
        </template>
        <el-row>
          <el-col v-if="active != 'detail'">
            <el-button class="hl-addbutton" type="primary" size="large" @click="onAddItem2">新增</el-button>
          </el-col>
          <el-col>
            <el-card class="hl-incard">
              <el-form ref="otherSubFormRef" :model="formData.deliverOrderOtherSubs" :rules="subFormRules" v-loading="subFormLoading" label-width="0">
                <el-table :data="formData.deliverOrderOtherSubs" class="hl-table">
                  <el-table-column label="序号" type="index" width="100" />
                  <el-table-column min-width="150" align="center">
                    <template #header> <span class="hl-table_header">*</span>名称 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.name`" :rules="subFormRules.name" class="mb-0px!">
                        <el-input :disabled="detailDisabled" v-model="row.name" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="所属类型" min-width="150" align="center">
                    <template #header> <span class="hl-table_header">*</span>所属类型 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.subType`" :rules="subFormRules.subType" class="mb-0px!">
                        <el-select :disabled="detailDisabled" v-model="row.subType" placeholder="请选择子项类型">
                          <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HELI_DELIVER_MATERIAL_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="本次发货数量" min-width="150">
                    <template #header> <span class="hl-table_header">*</span>本次发货数量 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.amount`" :rules="subFormRules.amount" class="mb-0px!">
                        <el-input-number :disabled="detailDisabled" v-model="row.amount" placeholder="请输入本次发货数量" style="width: 100%" :min="1" :precision="0"/><!-- :precision="0" -->
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="单位" min-width="150" align="center">
                    <template #header> <span class="hl-table_header">*</span>单位 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.unit`" :rules="subFormRules.unit" class="mb-0px!">
                        <el-select :disabled="detailDisabled" v-model="row.unit" placeholder="请选择单位">
                          <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_UNIT)" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" min-width="150" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
                        <el-input :disabled="detailDisabled" v-model="row.remark" placeholder="请输入备注" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="240">
                    <template #default="scope">
                      <el-button v-if="'update,create,deliver'.indexOf(active) > -1" link type="danger" size="small" @click.prevent="onDeleteItem2(scope.$index)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info" v-if="active != 'create'">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">附件信息</span>
        </template>
        <el-row>
          <el-col v-if="active != 'detail'">
            <el-upload ref="attachmentUploadRef" multiple :action="uploadUrl" :headers="uploadHeaders" name="files" :show-file-list="false" :auto-upload="false" :data="uploadData" :on-change="attachmentUploadChange" :on-error="handleError" :on-success="handleSuccess" :before-upload="before" class="upload-file-uploader">
              <el-button type="primary">
                <Icon icon="ep:upload-filled" />上传
              </el-button>
            </el-upload>
          </el-col>
          <el-col>
            <el-card class="hl-incard">
              <el-table :data="formData.attachments" class="hl-table" v-loading.fullscreen.lock="uploading" element-loading-text="附件上传中..." element-loading-background="rgba(122, 122, 122, 0.6)">
                <el-table-column prop="name" label="文件名称" align="center" />
                <el-table-column prop="createTime" align="center" label="上传时间" :formatter="dateFormatter" />
                <el-table-column label="操作" align="center">
                  <template #default="scope">
                    <el-button v-if="'update,create,deliver'.indexOf(active) > -1" link type="danger" size="small" @click="handleDeleteAttachment(scope.$index, scope.row.businessFileType)">
                      删除
                    </el-button>
                    <el-button v-if="!!scope.row.id" link type="primary" size="small" @click="downloadAttachment(scope.row.name, scope.row.url)">
                      下载
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info" v-if="active != 'create'">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">操作日志</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-table v-if="formData && formData.operateLogs" :data="formData.operateLogs" class="hl-table" :style="{ height: formData.operateLogs.length > 10 ? '450px' : '' }">
                <el-table-column prop="type" label="操作" align="center">
                  <template #default="scope">
                    {{ getDictLabel(DICT_TYPE.SYSTEM_OPERATE_TYPE, scope.row.type) }}
                  </template>
                </el-table-column>
                <el-table-column prop="userNickname" label="操作人" align="center" />
                <el-table-column label="操作时间" align="center" prop="startTime" :formatter="dateFormatter" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <div class="hl-footer text-center">
      <el-button @click="goback" size="large">取 消</el-button>
      <el-button v-if="active != 'detail' && formData.deliverStatus == 1" @click="submitForm('SAVE')" type="success" :disabled="formLoading" size="large">保 存</el-button>
      <el-button v-if="(((active != 'detail' && formData.id) || active == 'deliver') && formData.deliverStatus == 1)" @click="submitForm('DELIVER')" type="primary" :disabled="formLoading" size="large">发 货</el-button>
      <el-button v-if="active == 'detail' && formData.deliverStatus == 2 && formData.id" type="primary" @click="printHandle" :disabled="formLoading" size="large">打印发货单</el-button>
    </div>
  </el-card>
  <ProjectOrderDialog ref="projectOrderDialog" @success="handleSelectedProjectOrder" />
  <!-- 【打印发货单】 - 弹框-->
  <ShipmentsPrint ref="shipmentsPrintRef" />
  <PriceDigind :title="dialogTitles" width="80%" v-model="dialogVisibles" :parent-method="parentMethod" :projectOrderSubs="dataList"   @update="handleUpdate" center />

</template>
<script setup lang="ts">
import { ref , computed} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import type { UploadProps, UploadUserFile } from 'element-plus'
import {
  getStrDictOptions,
  DICT_TYPE,
  getIntDictOptions,
  getDictLabel
} from '@/utils/dict'
import * as DeliverOrderApi from '@/api/heli/deliverorder'
import { getOperateLogPage } from '@/api/system/operatelog'
import { deleteFileLogic, downloadFile, getFilePage } from '@/api/infra/file'
import { Search, Plus } from '@element-plus/icons-vue'
import UserSelect from '@/views/heli/hlvuestyle/userSelect.vue'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { inject } from 'vue'
import * as UserApi from '@/api/system/user'
import Big from 'big-js';

import PriceDigind from '@/views/heli/PriceQuoteRecord/priceDigind.vue'


import {
  getProjectOrder,
  getProjectOrderSubListByProjectOrderId,
  ProjectOrderVO
} from '@/api/heli/projectorder'
import { getCustomer } from '@/api/heli/customer'
import ProjectOrderDialog from '@/views/heli/deliverorder/projectOrderDialog.vue'
import ShipmentsPrint from './shipmentsPrint.vue' // 引入打印弹框
import Decimal from 'decimal.js';

defineOptions({ name: 'DeliverOrderDetail' })

const reload: any = inject('reload')

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter()
const { query } = useRoute()
const active = toRef(query, 'active')
const activeId = toRef(query, 'id')

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogVisibles = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const dialogTitles = ref('剩余BOM零件弹窗'); // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const userParams = {
  pageNo: 1,
  pageSize: 10,
  status: 0, // 根据实际情况调整参数
  username: undefined,
  nickname: undefined,
  userNickName: undefined
}
const formData = ref({
  id: undefined,
  code: undefined,
  saleOrderIds: undefined,
  saleOrderCode: undefined,
  contractNo: undefined,
  property: undefined,
  customerId: undefined,
  customerName: undefined,
  projectName: undefined,
  deliverDate: undefined,
  deliverStatus: 1,
  deliverPerson: undefined,
  deliverPersonMobile: undefined,
  deliverMode: '2',
  receivePersonMobile: undefined,
  transportDriverName: undefined,
  transportDriverMobile: undefined,
  transportBusNumber: undefined,
  transportWeight: undefined,
  transportSize: undefined,
  transportFreightCost: undefined,
  remark: undefined,
  status: 1,
  receivePersonName: undefined,
  receiveAddress: undefined,
  deliverOrderSubs: [],
  deliverOrderOtherSubs: [],
  attachments: [],
  operateLogs: [],
  active: undefined,
  deliverCompany: '杭州合立机械有限公司'
})
const dataList = ref({
	projectOrderSubs: []
})



const handleUpdate = () => {
  // 处理子组件的更新通知
  console.log("子组件已更新");
};

const parentMethod = () => {

 dialogVisibles.value = false
 reload()

};

const formRules = reactive({
  saleOrderIds: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
  property: [{ required: true, message: '性质不能为空', trigger: 'blur' }],
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户id不能为空', trigger: 'blur' }],
  deliverCompany: [{ required: true, message: '发货单位不能为空', trigger: 'blur' }],
  deliverDate: [{ required: true, message: '发货日期不能为空', trigger: 'blur' }],
  deliverStatus: [{ required: true, message: '发货单状态不能为空', trigger: 'blur' }],
  deliverPerson: [{ required: true, message: '发货人不能为空', trigger: 'blur' }],
  deliverPersonMobile: [{ required: true, message: '发货人电话不能为空', trigger: 'blur' }],
  receivePersonMobile: [{ required: true, message: '收货人电话不能为空', trigger: 'blur' }],
  receivePersonName: [{ required: true, message: '收货人姓名不能为空', trigger: 'blur' }],
  receiveAddress: [{ required: true, message: '收货详细地址不能为空', trigger: 'blur' }]
})
const subFormLoading = ref(false) // 子表单的加载中
const subFormRules = reactive({
  deliveryOrderId: [{ required: true, message: '订单不能为空', trigger: 'blur' }],
  subType: [{ required: true, message: '所属类型不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '名称，唯一不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '本次发货数量不能为空', trigger: 'blur' }],
  unit: [{ required: true, message: '单位不能为空', trigger: 'blur' }],
  weight: [{ required: true, message: '重量不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
/** 子表的表单 */
const subFormRef = ref()
const otherSubFormRef = ref()
//计算运费
 const yunFei = (event) => {

   const totalWeight = formData.value.deliverOrderSubs.reduce((sum, item) => {
     const weight = item.weight !== null && item.weight !== undefined ? Number(item.weight) : 0;
     return sum + weight;
   }, 0);
   formData.value.transportWeight=totalWeight

		if (formData.value.transportFreightCost && formData.value.transportFreightCost > 0) {
			//先将有重量和无重量的进行拆分
			let numOne = 0
			let numWeight = 0;
			let numTwo = 0
			for(var a=0;a<formData.value.deliverOrderSubs.length;a++){
				if(formData.value.deliverOrderSubs[a].weight>0&&formData.value.deliverOrderSubs[a].weight){
					numOne = numOne+1
					numWeight = numWeight+Number(formData.value.deliverOrderSubs[a].weight)
				}else{
					numTwo = numTwo+1
				}
			}
			if(numTwo>0){
				//大于0的情况下平摊运费
				 pingt();
			}else{
				//否则按照重量平摊
				weight(numWeight);
			}

		}else{
			for(var a=0;a<formData.value.deliverOrderSubs.length;a++){

				formData.value.deliverOrderSubs[a].yunFei = undefined


			}
		}

	}
//平摊运费
const pingt = () => {
    let sumMoney = new Big(0);
    for (var a = 0; a < formData.value.deliverOrderSubs.length; a++) {
        if (formData.value.deliverOrderSubs.length === a + 1) {
            let remainingCost = new Big(formData.value.transportFreightCost).minus(sumMoney);
            formData.value.deliverOrderSubs[a].yunFei = remainingCost;
        } else {
            let subYunFei = new Big(formData.value.transportFreightCost)
               .div(formData.value.deliverOrderSubs.length)
               .toFixed(2);
            formData.value.deliverOrderSubs[a].yunFei = subYunFei;
            sumMoney = sumMoney.plus(new Big(formData.value.deliverOrderSubs[a].yunFei));
        }
    }
}
/* const pingt = () =>{
	let sumMoney = 0;
	for(var a=0;a<formData.value.deliverOrderSubs.length;a++){
		if(formData.value.deliverOrderSubs.length == a+1){
			formData.value.deliverOrderSubs[a].yunFei = Number(formData.value.transportFreightCost)-Number(sumMoney)
		}else{
			formData.value.deliverOrderSubs[a].yunFei = (Number(formData.value.transportFreightCost)/Number(formData.value.deliverOrderSubs.length)).toFixed(2)
			sumMoney = sumMoney +Number(formData.value.deliverOrderSubs[a].yunFei)
		}

	}
} */
//平摊运费
const weight = (numWeight: number) => {
    let sumMoney = new Big(0);
    for (var a = 0; a < formData.value.deliverOrderSubs.length; a++) {
        if (formData.value.deliverOrderSubs.length === a + 1) {
            let remainingCost = new Big(formData.value.transportFreightCost).minus(sumMoney);
            formData.value.deliverOrderSubs[a].yunFei = remainingCost;
        } else {
            let subYunFei = new Big(formData.value.transportFreightCost)
              .times(new Big(formData.value.deliverOrderSubs[a].weight).div(numWeight))
              .toFixed(2);
            formData.value.deliverOrderSubs[a].yunFei = subYunFei;
            sumMoney = sumMoney.plus(new Big(formData.value.deliverOrderSubs[a].yunFei));
        }
    }
}
/* const weight = (numWeight: number) =>{
	let sumMoney = 0;
	for(var a=0;a<formData.value.deliverOrderSubs.length;a++){
		if(formData.value.deliverOrderSubs.length == a+1){
			formData.value.deliverOrderSubs[a].yunFei = Number(formData.value.transportFreightCost)-Number(sumMoney)
		}else{
			formData.value.deliverOrderSubs[a].yunFei = (Number(formData.value.transportFreightCost)*(Number(formData.value.deliverOrderSubs[a].weight)/Number(numWeight))).toFixed(2)
			sumMoney = sumMoney +Number(formData.value.deliverOrderSubs[a].yunFei)
		}

	}
} */


const submitForm = async (operate) => {
  // 校验表单
  formData.value.active = operate
  await formRef.value.validate()
  // 校验子表单
  if (active.value != 'create') {
    await subFormRef.value.validate()
    await otherSubFormRef.value.validate()
  }
  // 提交请求
  formLoading.value = true
  try {
    // 设置类型
    formData.value.deliverOrderSubs?.forEach((item) => {
      item.category = 'DELIVER_LIST'
      item.status = 1
    })
    formData.value.deliverOrderOtherSubs?.forEach((item) => {
      item.category = 'OTHER_LIST'
      item.status = 1
    })
    var data = formData.value as unknown as DeliverOrderApi.DeliverOrderVO
    // if(data.deliverOrderSubs.length >1){
    //   data.deliverOrderSubs.forEach(element => {
    //     element.saleOrderSubId = element.projectOrderId;
    //   });

    // }
    const orderId = await DeliverOrderApi.operateDeliverOrder(data)
    message.success(t('common.operationSuccess'))
    // 上传附件
    if (attachmentUploadFiles.value.length > 0) {
      uploadData.value.businessId = orderId
      await attachmentUploadRef.value!.submit()
    }

    if (operate == 'SAVE') {
      if (active.value != 'deliver') {
        active.value = 'update'
      }
    } else if (operate == 'DELIVER') {
      active.value = 'detail'
	  //在这个地方判断发货后是否此子项目下是否还有剩余物料
	  const data = formData.value as unknown as DeliverOrderApi.DeliverOrderVO;
    dataList.value.projectOrderSubs = await DeliverOrderApi.operateDeliverOrders(data);
      if(dataList.value.projectOrderSubs.length>0){
        dialogVisibles.value = true;
      }
    }
    activeId.value = orderId
     if (sumbefore.value == 0) {
		 if(!dialogVisibles.value){
			 reload()
		 }

    }

  } finally {
    formLoading.value = false
  }
}
const goback = () => {
  router.back()
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    saleOrderIds: undefined,
    saleOrderCode: undefined,
    contractNo: undefined,
    property: undefined,
    customerId: undefined,
    customerName: undefined,
    projectName: undefined,
    deliverDate: undefined,
    deliverStatus: 1,
    deliverPerson: undefined,
    deliverPersonMobile: undefined,
    deliverMode: '2',
    receivePersonMobile: undefined,
    transportDriverName: undefined,
    transportDriverMobile: undefined,
    transportBusNumber: undefined,
    transportWeight: undefined,
    transportSize: undefined,
    remark: undefined,
    status: 1,
    receivePersonName: undefined,
    receiveAddress: undefined,
    deliverOrderSubs: [],
    deliverOrderOtherSubs: [],
    attachments: [],
    operateLogs: [],
    active: undefined,
    deliverCompany: '杭州合立机械有限公司'
  }
  formRef.value?.resetFields()
}

const onAddItem2 = () => {
  const row = {
    id: undefined,
    deliveryOrderId: undefined,
    category: 'OTHER_LIST',
    name: undefined,
    blueprintNo: undefined,
    amount: undefined,
    unit: undefined,
    weight: undefined,
    size: undefined,
    subType: '1',
    remark: undefined,
    status: undefined
  }
  row.deliveryOrderId = formData.value.id
  if (!formData.value.deliverOrderOtherSubs) {
    formData.value.deliverOrderOtherSubs = []
  }
  formData.value.deliverOrderOtherSubs.push(row)
}

//接收职工传递的数据
const handleSelectedUser = (newValue: any) => {
  formData.value.deliverPerson = newValue?.id
  formData.value.deliverPersonMobile = newValue?.mobile
}

const attachmentUploadRef = ref()
const attachmentUploadFiles = ref<UploadUserFile[]>([])
const uploading = ref(false)
const businessType = ref('DELIVER_ORDER')
const uploadUrl = ref(import.meta.env.VITE_UPLOAD_BATCH_URL)
const uploadData = ref({
  businessType: businessType.value,
  businessId: formData.value.id,
  businessFileType: 'MATERIAL'
})
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})

const attachmentUploadChange = (file, files) => {
  attachmentUploadFiles.value = files
  refreshAttachments(files, 'MATERIAL')
}

// 记录待上传、成功上传及失败上传的文件数量
const sumbefore = ref(0)
const successfulUploadsCount = ref(0)
const failedUploadsCount = ref(0)
const failedAttachments = ref<UploadUserFile[]>([])
const failedAttachmentsName = ref()

// 处理单个文件上传成功的情况
const handleSuccess = (response: any, file: UploadUserFile) => {
  successfulUploadsCount.value++
  // 更新附件信息等其他逻辑...
  // console.log('上传成功数量', successfulUploadsCount.value)
}

// 处理单个文件上传失败的情况
const handleError = (error: Error, file: UploadUserFile) => {
  failedUploadsCount.value++
  if (failedUploadsCount.value > 0) {
    // 当有上传错误时
    // 将失败的附件添加到failedAttachments.value数组中
    failedAttachments.value.push(file)
    failedAttachmentsName.value = failedAttachments.value.map((value) => value.name)
  }
  // console.log('上传失败数量', failedUploadsCount.value)
}

// 文件上传前的钩子
const before = (rawFile) => {
  sumbefore.value++
}

const refreshAttachments = (files, type) => {
  formData.value.attachments = formData.value.attachments.filter((value) => value.id)

  // 避免重复添加
  const newFiles = files.filter(
    (file) => !formData.value.attachments.some((att) => att.name === file.name)
  )

  for (let i = 0; i < newFiles.length; i++) {
    let file = newFiles[i]
    file.businessFileType = type
    file.createTime = new Date()
    formData.value.attachments.push(file)
  }

  // 排序
  formData.value.attachments.sort((v1, v2) => v1.createTime - v2.createTime)
  // 文件上传一遍 上传总数等于要上传文件时 刷新页面
  const sum = successfulUploadsCount.value + failedUploadsCount.value
  // console.log('上传总数', sum)
  // console.log('要上传文件数量', sumbefore.value)
  if (sumbefore.value !== sum && sumbefore.value !== 0 && sum !== 0) {
    // console.log('要上传文件数量不等于上传总数时等待',uploading.value)
    uploading.value = true
  } else if (sum == sumbefore.value && sumbefore.value > 0 && sum > 0) {
    // console.log('要上传文件数量等于上传总数 刷新页面并给出提示')
    if (failedUploadsCount.value > 0) {
      ElMessageBox.alert(
        // 使用错误信息作为提示内容
        `文件名为：${failedAttachmentsName.value.join(' / ')}上传失败`,
        `文件格式不正确或网络问题 请您稍后再试`,
        {
          dangerouslyUseHTMLString: false,
          confirmButtonText: '知道了',
          center: true
        }
      )
    }
    reload()
    uploading.value = false
  }
}

/** 删除子项操作 */
const onDeleteItem = (index) => {
  if (formData.value.deliverOrderSubs.length == 1) {
    message.warning('发货清单至少存在一条数据')
    return
  }
  formData.value.deliverOrderSubs.splice(index, 1)
}

const onDeleteItem2 = (index) => {
  formData.value.deliverOrderOtherSubs.splice(index, 1)
}

// 删除附件
const handleDeleteAttachment = async (index, type) => {
  const deletedAttachments = formData.value.attachments.splice(index, 1)
  for (let i = 0; i < deletedAttachments.length; i++) {
    const attachment = deletedAttachments[i]
    if (attachment.id) {
      // 清理已上传文件
      await deleteFileLogic(attachment.id)
    }
    // 清理待上传文件
    attachmentUploadFiles.value = attachmentUploadFiles.value.filter((file1) => {
      return file1.name != attachment.name
    })
  }
}

// 下载文件
const downloadAttachment = async (name, url) => {
         const baseUrl = import.meta.env.VITE_BASE_URL;
    url =baseUrl+'/admin-api/'+ url.split('/admin-api/')[1];    const data = await downloadFile(url)
  download.any(data, name)
}

/** 打开弹窗 */
const queryData = async (type: string, id?: number) => {
  if (type == 'create') {
    // console.log('-------', getStrDictOptions(DICT_TYPE.HELI_DEFAULT_DELIVER)[0].value)
    userParams.userNickName = getStrDictOptions(DICT_TYPE.HELI_DEFAULT_DELIVER)[0].value
    const data = await UserApi.getUserPage(userParams)
    formData.value.deliverPerson = data.list[0].id
    const initialUser = await UserApi.getUser(formData.value.deliverPerson)
    formData.value.deliverPersonMobile = initialUser?.mobile
  }

  dialogTitle.value = t('action.' + type)
  // 修改时，设置数据
  formLoading.value = true
  formData.value.deliverDate = new Date().getTime()
  try {
    if (id) {
      formData.value = await DeliverOrderApi.getDeliverOrder(id)
      formData.value.deliverCompany = '杭州合立机械有限公司'

      // 性质
      let properties = formData.value.property.split(',')
      let property = ''
      for (let i = 0; i < properties.length; i++) {
        property += getDictLabel(DICT_TYPE.HELI_PROJECT_PROPERTY, properties[i]) + ','
      }
      formData.value.property = property.substring(0, property.length - 1)

      // 子项列表
      const subArr = await DeliverOrderApi.getDeliverOrderSubListByDeliveryOrderId(id)
      // 如未保存过 即子项为空 从关联项目带出
      if (!subArr || subArr.length == 0) {
        formData.value.deliverOrderSubs = []
        let saleOrderIdArr = formData.value.saleOrderIds.split(',')
        for (let i = 0; i < saleOrderIdArr.length; i++) {
           var subList = await getProjectOrderSubListByProjectOrderId(saleOrderIdArr[i]);
           subList.forEach((sub)=>{
            sub.saleOrderId = saleOrderIdArr[i];
            sub.remark = ''
            sub.saleOrderSubId = sub.id
            sub.id = ''
            sub.saleOrderCode = sub.projectOrderCode
            sub.amount = sub.amount - sub.deliverAmount
           })
          formData.value.deliverOrderSubs = formData.value.deliverOrderSubs.concat(
            subList
          )
          // formData.value.deliverOrderSubs.forEach((sub) => {
          //   sub.saleOrderId = saleOrderIdArr[i];
          //   sub.remark = ''
          //   sub.saleOrderSubId = sub.id
          //   sub.id = ''
          //   sub.saleOrderCode = sub.projectOrderCode
          //   sub.amounts = sub.amount - sub.deliverAmount
          // })
        }
     //   console.log(formData.value.deliverOrderSubs )
      } else {
        // 分类发货清单与其他物料清单
        formData.value.deliverOrderSubs = subArr.filter((sub) => sub.category == 'DELIVER_LIST')
        formData.value.deliverOrderOtherSubs = subArr.filter((sub) => sub.category == 'OTHER_LIST')
      }
	//console.log("打印发货信息");
	//
  // console.log(formData.value.deliverOrderSubs);
      // 操作日志
      let logParams = {
        pageNo: 1,
        pageSize: 99,
        businessId: id,
        businessType: businessType.value
      }
      formData.value.operateLogs = (await getOperateLogPage(logParams)).list

      // 附件信息
      let attParams = {
        pageNo: 1,
        pageSize: 99,
        businessId: id,
        businessType: businessType.value
      }
      formData.value.attachments = (await getFilePage(attParams)).list

      await initCustomerInfo()
    }
  } finally {
    formLoading.value = false
  }
}

const initCustomerInfo = async () => {
  // 收货人信息
  const customer = await getCustomer(formData.value.customerId)
  if (customer.contact1Name) {
    receivePersonOptions.value.push({
      name: customer.contact1Name,
      mobile: customer.contact1Method
    })
    receivePersonAddressOptions.value.push({
      address: customer.contact1Addr
    })
  }
  if (customer.contact2Name) {
    receivePersonOptions.value.push({
      name: customer.contact2Name,
      mobile: customer.contact2Method
    })
    receivePersonAddressOptions.value.push({
      address: customer.contact2Addr
    })
  }
  if (customer.contact3Name) {
    receivePersonOptions.value.push({
      name: customer.contact3Name,
      mobile: customer.contact3Method
    })
    receivePersonAddressOptions.value.push({
      address: customer.contact3Addr
    })
  }
}

const isEditing = ref(false)
const handleClick = (event) => {
  openProjectOrderDialog()
}
const projectOrderDialog = ref()
const openProjectOrderDialog = () => {
  projectOrderDialog.value?.open()
}
const handleSucessPriceDigind = (msg:string) =>{
  if(msg == 'error'){

  }
}
const handleSelectedProjectOrder = (arr: ProjectOrderVO[]) => {
  if (arr && arr.length > 0) {
    let saleOrderIds = ''
    let saleOrderCode = ''
    let contractNo = ''
    let property = ''
    let projectName = ''
    for (let i = 0; i < arr.length; i++) {
      let order = arr[i]
      saleOrderIds += order.id + ','
      saleOrderCode += order.code + ','
      contractNo += (!order.contractNo ? '' : order.contractNo) + ','
      property += getDictLabel(DICT_TYPE.HELI_PROJECT_PROPERTY, order.property) + ','
      projectName += order.projectName + ','
    }
    formData.value.saleOrderIds = saleOrderIds.substring(0, saleOrderIds.length - 1)
    formData.value.saleOrderCode = saleOrderCode.substring(0, saleOrderCode.length - 1)
    formData.value.contractNo = contractNo.substring(0, contractNo.length - 1)
    formData.value.property = property.substring(0, property.length - 1)
    formData.value.projectName = projectName.substring(0, projectName.length - 1)
    formData.value.customerId = arr[0].customerId
    formData.value.customerName = arr[0].customerName
  }
}

// 收货人信息
const receivePersonOptions = ref([])
// 详细地址
const receivePersonAddressOptions = ref([])

const receiveOnChange = (val) => {
  let matchedPerson = receivePersonOptions.value.find((p) => p.name == val)
  if (matchedPerson) {
    formData.value.receivePersonMobile = matchedPerson.mobile
  }
}

//打印发货单
const shipmentsPrintRef = ref() // 打印弹框

const printHandle = () => {
  shipmentsPrintRef.value.open(formData.value.id)
}

const initDeliverData = async (projectOrderId) => {
  let projectOrder = await getProjectOrder(projectOrderId)
  handleSelectedProjectOrder([projectOrder])

  formData.value.deliverOrderSubs = []
  formData.value.deliverOrderSubs = formData.value.deliverOrderSubs.concat(
    await getProjectOrderSubListByProjectOrderId(projectOrderId)
  )
  formData.value.deliverOrderSubs.forEach((sub) => {
    sub.remark = ''
    sub.saleOrderSubId = sub.id
    sub.id = ''
    sub.saleOrderCode = sub.projectOrderCode
    sub.amounts = sub.amount - sub.deliverAmount
  })

  await initCustomerInfo()
}

const initData = async () => {
  resetForm()
  if ('detail' == active.value) {
    detailDisabled.value = true
  }
  if ('deliver' == active.value && query.projectOrderId) {
    await initDeliverData(query.projectOrderId)
  }
  await queryData(active.value, activeId.value)
}

const detailDisabled = ref(false)

onMounted(() => {
  initData()
})
</script>
<style>
a {
  color: #409eff;
  text-decoration: none;
}
</style>
