<template>
  <el-card class="hl-card" style="position: relative">
    <template #header>
      <span>编辑页</span>
    </template>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="160px" 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="24">
            <el-row>
              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label=" 委外验收单号" prop="outsourceNo">
                      <el-input class="!w-265px" placeholder="系统自动生成" v-model="formData.outsourceNo" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="采购物料类型" prop="goodsType" :rules="formRules.goodsType">
                      <el-select disabled v-model="formData.goodsType" placeholder="下拉选择" clearable class="!w-240px">
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PURCHASE_GOODS_TYPE)"
                          :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="送检人" prop="deliver">
                      <el-input class="!w-265px" v-model="formData.deliver" placeholder="请输入送检人" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="80">
                    <el-form-item label="到货日期" prop="arrivalDate">
                      <el-date-picker
v-model="formData.arrivalDate" type="date" value-format="x"
                        placeholder="选择到货日期" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="单据日期" prop="createTime">
                      <el-date-picker
class="!w-265px" v-model="formData.createTime" value-format="x" placeholder="单据日期"
                        disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label=" 是否自动入库" prop="autoStockIn">
                      <el-input class="!w-265px" :value="formData.autoStockIn === 1 ? '是' : '否'" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="收检人" prop="receiver">
                      <el-input v-model="formData.receiver" placeholder="请输入收检人" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="检验日期" prop="inspectionDate">
                      <el-date-picker
v-model="formData.inspectionDate" type="date" value-format="x"
                        placeholder="选择检验日期" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="采购单号" prop="purchaseNo" :rules="formRules.purchaseNo">
                      <el-input class="!w-265px" v-model="formData.purchaseNo" disabled />
                    </el-form-item>
                    <!-- <el-form-item label="采购单号" prop="purchaseId">
                      <el-input v-model="formData.purchaseId" placeholder="请输入采购id" />
                    </el-form-item> -->
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label=" 是否自动出库" prop="autoStockOut">
                      <el-input class="!w-265px" :value="formData.autoStockIn === 1 ? '是' : '否'" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input
class="!w-713px" type="textarea" v-model="formData.remark" show-word-limit
                        maxlength="100" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="供应商" prop="supplierName">
                      <el-input v-model="formData.supplierName" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

            </el-row>
          </el-col>
        </el-row>
      </el-card>

      <!--  物料信息-计划   -->
      <el-card class="hl-card-info" v-if="formData.goodsType == 1">

        <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="subOutSourceMatFormRef" :model="formData.matItemDOList" :rules="subOutSourceMatFormRules"
                label-width="0">
                <el-table :data="formData.matItemDOList" class="hl-table">
                  <el-table-column type="index" label="序号" fixed align="center" min-width="60" />
                  <el-table-column prop="materialId" fixed min-width="200" align="center">
                    <template #header> <span class="hl-table_header">*</span>物料编码/名称 </template>

                    <template #default="scope">
                      <el-form-item
:prop="`${scope.$index}.materialId`" :rules="subOutSourceMatFormRules.materialId"
                        class="mb-0px!">
                        <MaterialSelect
:key="scope.row.materialId" v-model="scope.row.materialId" disabled
                          @update:new-value="handleSelectedMaterial(scope.$index, $event)" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="purchaseAmount" label="采购数量" min-width="180" align="center" />
                  <el-table-column prop="matType" label="物料类型" min-width="120" align="center">
                    <template #default="scope">
                      <dict-tag :type="DICT_TYPE.HELI_MATERIAL_TYPE" :value="scope.row.matType" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="matSpec" label="规格/型号" min-width="120" align="center" />



                  <!-- <el-table-column prop="matRest" label="库存数量" min-width="180" align="center" /> -->
                  <el-table-column prop="currentCount" min-width="180" align="center">
                    <template #header><span class="hl-table_header">*</span>本次到货数量</template>
                    <template #default="scope">
                      <el-form-item
:prop="`${scope.$index}.currentCount`"
                        :rules="subOutSourceMatFormRules.currentCount" class="mb-0px!">
                        <el-input-number
style="width: 100%" v-model="scope.row.currentCount" placeholder="本次到货数量"
                          @change="handleEstimatedPrice" :min="0" :precision="2" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unqualifiedCount" min-width="200" align="center">

                    <template #header><span class="hl-table_header">*</span>不合格数量</template>

                    <template #default="scope">
                      <el-form-item
:prop="`${scope.$index}.unqualifiedCount`"
                        :rules="subOutSourceMatFormRules.unqualifiedCount" class="mb-0px!">
                        <el-input-number
style="width: 100%" v-model="scope.row.unqualifiedCount" placeholder="不合格数量"
                          @change="handleEstimatedPrice" :min="0" :precision="2" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="qualifiedCount" min-width="200" align="center">

                    <template #header>合格数量</template>

                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.qualifiedCount`" class="mb-0px!">
                        <el-input-number
disabled style="width: 100%" v-model="scope.row.qualifiedCount"
                          placeholder="合格数量" @change="handleEstimatedPrice" :min="0" :precision="2" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="350" align="center">
                    <template #header><span class="hl-table_header">*</span>子项目编号</template>
                    <template #default="{ row, $index }">
                      <el-form-item
:prop="`${$index}.projectSubId`" class="mb-0px!"
                        :rules="subOutSourceMatFormRules.projectSubId">
                        <el-select
class="!w-365px" v-model="row.projectSubId" clearable
                          :disabled="formData.status == 2">
                          <el-option
v-for="dict in formData.projectPlanSubs" :key="dict.projectSubId"
                            :label="dict.projectSubCode" :value="dict.projectSubId" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="repairable" min-width="260" align="center" label="修复判断">
                    <template #header><span class="hl-table_header">*</span>修复判断</template>
                    <template #default="{ row, $index }">
                      <el-form-item
:prop="`${$index}.repairable`" class="mb-0px!"
                        :rules="subOutSourceMatFormRules.repairable">
                        <el-select v-model="row.repairable" clearable class="!w-240px">
                          <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_OUTSOURCE_STOCK_REPAIR)"
                            :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unqualifiedContent" label="不合格内容" min-width="180" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.unqualifiedContent" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="reason" min-width="180" label="原因分析" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.reason" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="remark" min-width="180" label="纠正/预防措施" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.remark" />
                    </template>
                  </el-table-column>
                  <el-table-column label="系统单位" align="center" prop="matUnit" width="100px">
                    <template #default="scope">
                      <dict-tag :type="DICT_TYPE.HELI_MATERIAL_UNIT" :value="scope.row.matUnit" min-width="100" />
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <!--  加工件信息-计划   -->
      <el-card class="hl-card-info" v-if="formData.goodsType == 2">
        <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-col>
                <el-button
class="hl-addbutton" type="primary" size="large" @click="onBoomAddItemOpen"
                  :disabled="formData.status == 2 || formData.status == 3">新增</el-button>
              </el-col> -->
              <el-form
ref="subBoomPlanFormRef" :model="formData.boomItemDOList" :rules="subBoomPlanFormRules"
                label-width="0">
                <el-table :data="formData.boomItemDOList" class="hl-table">
                  <el-table-column type="index" label="序号" fixed align="center" min-width="60" />
                  <el-table-column prop="materialName" fixed label="零件名称" min-width="120" align="center" />

                  <!-- <el-table-column prop="boomName" fixed min-width="200" align="center">
                    <template #header> <span class="hl-table_header">*</span>零件名称 </template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.boomDetailId`" :rules="subOutSourceMatFormRules.boomDetailId" class="mb-0px!">
                        <MaterialSelect :key="scope.row.boomDetailId" v-model="scope.row.boomDetailId" disabled @update:new-value="handleSelectedBoomMaterial(scope.$index, $event)" />
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <el-table-column prop="purchaseAmount" fixed label="采购数量" min-width="120" align="center" />
                  <el-table-column prop="boomSpec" label="规格/型号" min-width="120" align="center" />
                  <el-table-column prop="composition" min-width="180" label="材质" align="center">
                    <!-- <template #header>材质</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.composition`" class="mb-0px!">
                        <CompositionSelect v-model="row.composition" disabled @update:new-value="(val) => { row.composition = val.id; }" />
                      </el-form-item>
                    </template> -->
                  </el-table-column>


                  <el-table-column prop="currentCount" min-width="180" align="center">
                    <template #header><span class="hl-table_header">*</span>本次到货数量</template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.currentCount`" class="mb-0px!" :rules="subOutSourceMatFormRules.currentCount">
                        <el-input-number 
style="width: 100%" v-model="scope.row.currentCount" placeholder="本次到货数量"
                          @change="handleEstimatedPrice" :min="0" :precision="2" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unqualifiedCount" min-width="200" align="center">

                    <template #header><span class="hl-table_header">*</span>不合格数量</template>

                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.unqualifiedCount`" class="mb-0px!" :rules="subOutSourceMatFormRules.unqualifiedCount">
                        <el-input-number
style="width: 100%" v-model="scope.row.unqualifiedCount" placeholder="不合格数量"
                          @change="handleEstimatedPrice" :min="0" :precision="2" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="qualifiedCount" min-width="200" align="center">

                    <template #header>合格数量</template>

                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.qualifiedCount`" class="mb-0px!">
                        <el-input-number
disabled style="width: 100%" v-model="scope.row.qualifiedCount"
                          placeholder="合格数量" @change="handleEstimatedPrice" :min="0" :precision="2" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="350" align="center">
                    <template #header><span class="hl-table_header">*</span>子项目编码</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.projectSubId`" class="mb-0px!" :rules="subOutSourceMatFormRules.projectSubId" >
                        <el-select
class="!w-365px" v-model="row.projectSubId" clearable
                          :disabled="formData.status == 2">
                          <el-option
v-for="dict in formData.projectPlanSubs" :key="dict.projectSubId"
                            :label="dict.projectSubCode" :value="dict.projectSubId" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="repairable" min-width="260" align="center" label="修复判断">
                    <template #header><span class="hl-table_header">*</span>修复判断</template>
                    <template #default="{ row, $index }">
                      <el-form-item
                        :prop="`${$index}.repairable`" class="mb-0px!"
                        :rules="subOutSourceMatFormRules.repairable">
                        <el-select v-model="row.repairable" clearable class="!w-240px">
                          <el-option
                            v-for="dict in getIntDictOptions(DICT_TYPE.HELI_OUTSOURCE_STOCK_REPAIR)"
                            :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unqualifiedContent" label="不合格内容" min-width="180" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.unqualifiedContent" />
                    </template>
                  </el-table-column>

                  <!-- <el-table-column prop="repairable" min-width="260" align="center" label="修复判断">
                    <template #default="scope">
                      <el-select v-model="scope.row.repairable" clearable class="!w-240px">
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_OUTSOURCE_STOCK_REPAIR)"
                          :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                    </template>
                  </el-table-column> -->
                  <el-table-column prop="reason" min-width="180" label="原因分析" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.reason" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="remark" min-width="180" label="纠正/预防措施" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.remark" />
                    </template>
                  </el-table-column>
                  <el-table-column label="单位" align="center" prop="boomUnit" width="100px">
                    <template #default="scope">
                      <dict-tag :type="DICT_TYPE.HELI_MATERIAL_UNIT" :value="scope.row.boomUnit" min-width="100" />
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
          </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>
            <el-card class="hl-incard">
              <el-col>
                <el-upload
ref="matUploadRef" :file-list="matUploadFiles" multiple :action="uploadUrl" :headers="{
                  Authorization: 'Bearer ' + getAccessToken(),
                  'tenant-id': getTenantId()
                }" name="files" :show-file-list="false" :auto-upload="false" :data="matUploadData"
                  :on-change="matUploadChange" :on-error="handleError" :on-success="handleSuccess"
                  :before-upload="before" class="upload-file-uploader">
                  <el-button type="primary" :disabled="formData.status == 2">
                    <Icon icon="ep:upload-filled" />上传
                  </el-button>
                </el-upload>
              </el-col>
              <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">
                  <!-- <template #default="scope">
                    <a :href="scope.row.url" target="_blank" style="color: #409eff">{{ scope.row.name }} </a>
                  </template> -->
                </el-table-column>

                <el-table-column prop="createTime" align="center" label="上传日期" :formatter="dateFormatter" />

                <el-table-column label="操作" align="center">

                  <template #default="scope">
                    <el-button
link type="danger" size="small" :disabled="formData.status == 2"
                      @click="handleDeleteAttachment(scope.$index, scope.row.businessFileType)">
                      删除
                    </el-button>
                    <el-button
link type="primary" size="small" :disabled="formData.status == 2"
                      @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">

        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">系统信息</span>
        </template>

        <el-row justify="center">
          <el-col :span="8">
            <el-form-item prop="creator" label="创建人">
              {{ userList.find((user) => user.id == formData.creator)?.nickname }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="createTime" label="创建时间">
              {{ formatDate(formData.createTime, 'YYYY-MM-DD HH:mm') }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="center">
          <el-col :span="8">
            <el-form-item prop="submitter" label="提交人">
              {{ userList.find((user) => user.id == formData.submitter)?.nickname }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="submitTime" label="提交时间">
              {{ formatDate(formData.submitTime, 'YYYY-MM-DD HH:mm') }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

    </el-form>
    <div class="hl-footer text-center">

      <!-- <el-button @click="deleteForm" type="danger" size="large" v-if="formData.status == 1 || formData.status == 4">删
        除</el-button> -->
      <el-button @click="saveForm" v-if="formData.status !== 2 && formData.status !== 3" type="primary" size="large">保
        存</el-button>
      <el-button
@click="submitForm" type="success" size="large"
        v-if="formData.status !== 2 && formData.status !== 3">提交</el-button>
      <el-button @click="closeForm" v-if="formData.status == 2" size="large">取消提交</el-button>
    </div>
  </el-card>
  <!-- 表单弹窗：物料列表 -->
  <materials ref="matOpenFormRef" @success="getList" />
  <MaterialDialog ref="materialDialog" @success="handleSelectedMaterialPlanMat" />
  <BoomDialog ref="boomDialog" @success="handleSelectedMaterialPlanBoom" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as MaterialPlanApi from '@/api/heli/materialplan'
import * as PurchaseOrderApi from '@/api/heli/purchaseorder'
import * as PurchaseOrderMaterialApi from '@/api/heli/purchaseordermaterial'
import * as OutsourceStockMaterialApi from '@/api/heli/outsourcestockmaterial'
import * as PurchaseOrderBoomApi from '@/api/heli/purchaseorderboom'
import * as OutsourceStockBoomApi from '@/api/heli/outsourcestockboom'
import * as UserApi from '@/api/system/user'
import * as MaterialApi from '@/api/heli/material'
import * as SupplierApi from '@/api/heli/supplier'
import { deleteFile, downloadFile, getFilePage } from '@/api/infra/file'
import download from '@/utils/download'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { useUserStore } from '@/store/modules/user'
import { useTagsViewStore } from '@/store/modules/tagsView'
import MaterialSelect from '@/views/heli/hlvuestyle/materialSelect.vue'
import type { UploadUserFile } from 'element-plus'
import materials from '@/views/heli/storage/materials.vue'
import MaterialDialog from '@/views/heli/purchaseorder/materialDialog.vue'
import BoomDialog from '@/views/heli/purchaseorder/boomDialog.vue'
import * as OutsourceStockApi from '@/api/heli/outsourcestock'
import * as PlanSubApi from '@/api/heli/plansub'

const reload: any = inject('reload')
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { query } = useRoute()
const router = useRouter()
const tagsViewStore = useTagsViewStore()


const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  outsourceNo: undefined,
  purchaseId: undefined,
  purchaseNo: undefined,
  supplierId: undefined,
  supplierName: undefined,
  goodsType: undefined,
  autoStockIn: undefined,
  autoStockOut: undefined,
  deliver: undefined,
  receiver: undefined,
  arrivalDate: undefined,
  inspectionDate: undefined,
  remark: undefined,
  status: undefined,
  submitter: undefined,
  submitTime: undefined,
  createTime: new Date(),
  matItemDOList: [],
  matItemRemoveList: [],
  boomItemDOList: [],
  boomItemRemoveList: [],
  attachments: []
})
const formRules = reactive({
  currencyType: [{ required: true, message: '结算币种不能为空', trigger: 'blur' }]
})
const subFormRules = reactive({
  matId: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
  estimatedPrice: [{ required: true, message: '暂估价金额不能为空', trigger: 'blur' }],
  purchaseAmount: [{ required: true, message: '采购数量不能为空', trigger: 'blur' }]
})
const subBoomFormRules = reactive({
  boomName: [{ required: true, message: '零件名称不能为空', trigger: 'blur' }],
  composition: [{ required: true, message: '材质不能为空', trigger: 'blur' }],
  boomPurchaseAmount: [{ required: true, message: '采购数量不能为空', trigger: 'blur' }],
  boomEstimatedPrice: [{ required: true, message: '暂估价金额不能为空', trigger: 'blur' }],
  boomArriveTime: [{ required: true, message: '预计到货时间不能为空', trigger: 'blur' }],
})
const subOutSourceMatFormRules = reactive({
  currentCount: [{ required: true, message: '本次到货数量不能为空', trigger: 'blur' }],
  unqualifiedCount: [{ required: true, message: '不合格数量不能为空', trigger: 'blur' }],
  projectSubId: [{ required: true, message: '子项目编号不能为空', trigger: 'blur' }],
  repairable: [{ required: true, message: '修复判断不能为空', trigger: 'blur' }]
})
const subBoomPlanFormRules = reactive({
  boomName: [{ required: true, message: '零件名称不能为空', trigger: 'blur' }],
  boomPurchaseAmount: [{ required: true, message: '采购数量不能为空', trigger: 'blur' }],
  boomEstimatedPrice: [{ required: true, message: '暂估价金额不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const subFormRef = ref() // 表单 Ref
const subOutSourceMatFormRef = ref()
const subBoomPlanFormRef = ref()

const subBoomFormRef = ref()
const subBoomFormLoading = ref(false)
const matOpenFormRef = ref()

// const handleSelectedMaterialPlanMat = (arr) => {
//   arr.forEach((item) => {
//     if (formData.value.matItemDOList.filter((vo) => vo.matId == item.matId).length == 0) {
//       item.description = ''
//       formData.value.matItemDOList.push(item)
//     }
//   })
// }
const handleSelectedMaterialPlanMat = (arr) => {
  // 创建一个 Set 来存储现有的 matId
  debugger
  const existingMatIds = new Set(formData.value.matItemDOList.map(vo => vo.matId));
  arr.forEach((item) => {
    if (!existingMatIds.has(item.matId)) {
      item.description = '';
      formData.value.matItemDOList.push(item);
      existingMatIds.add(item.matId); // 将新添加的 matId 加入 Set
    }
  });
};
const handleSelectedMaterialPlanBoom = async (arrBoom) => {
  //debugger  
  const existingBoomDetailIds = new Set(formData.value.boomItemDOList.map(boom => boom.boomDetailId));

  arrBoom.forEach((item) => {
    if (!existingBoomDetailIds.has(item.boomDetailId)) {
      item.description = '';
      // formData.value.boomItemDOList.requireTime = item.boomArriveDate
      // formData.value.boomItemDOList.composition = item.compositionName
      // formData.value.boomItemDOList.boomName = item.materialName
      formData.value.boomItemDOList.push(item);
      existingBoomDetailIds.add(item.boomDetailId); // 将新添加的 boomDetailId 加入 Set
    }
  });
}
// const getBoomList = async (arrBoom) => {
//   //formData.value.boomItemDOList = arrBoom
//   arrBoom.forEach((item) => {
//     if (
//       formData.value.boomItemDOList.filter(
//         (boom) =>
//           item.materialName == boom.materialName && item.projectSubCode == boom.projectSubCode
//       ).length == 0
//     ) {
//       formData.value.boomItemDOList.push(item)
//     }
//   })
// }


const handleEstimatedPrice = () => {
  formData.value.matItemDOList.forEach((item) => {
    item.qualifiedCount = item.currentCount - item.unqualifiedCount
  })

  formData.value.boomItemDOList.forEach((item) => {
    item.qualifiedCount = item.currentCount - item.unqualifiedCount
  })
}
const handleActualPrice = () => {

}

// ====================附件信息 开始=======================================
const uploadUrl = ref(import.meta.env.VITE_UPLOAD_BATCH_URL)
const matUploadRef = ref()
const uploading = ref(false)

const matUploadFiles = ref<UploadUserFile[]>([])
const matUploadData = ref({
  businessType: 'OUTSOURCESTOCK',
  businessId: formData.value.id,
  businessFileType: 'MATERIAL'
})
const matUploadChange = (file, files) => {
  matUploadFiles.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 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 deleteFile(attachment.id)
    }
    // 清理待上传文件
    matUploadFiles.value = matUploadFiles.value.filter((file1) => {
      return file1.name != attachment.name || file1.businessFileType != type
    })
  }
}
// 下载文件
const downloadAttachment = async (name, url) => {
  if (url) {
    const data = await downloadFile(url)
    download.any(data, name)
  }
}
// ====================附件信息 结束=======================================

// 远程数据筛选物料
const getMatList = async (name) => {
  // 获得物料列表
  let matParams = {
    pageNo: 1,
    pageSize: 10,
    status: '1'
  }
  if (name.length > 0) {
    matParams.code = name
  }
  const dataMat = await MaterialApi.getMaterialPage(matParams)
  matList.value = dataMat.list
}
const matList = ref<MaterialApi.MaterialVO[]>([]) // 物料列表
const matSelectLoading = ref(false)
const remoteMatNameSearch = async (name) => {
  matSelectLoading.value = true
  // 获得物料列表
  await getMatList(name)
  matSelectLoading.value = false
}
const handleMatName = async (scope, matid) => {
  scope.row.matId = matList.value.find((item) => item.id === matid)?.id
  scope.row.matName = matList.value.find((item) => item.id === matid)?.name
  scope.row.matCode = matList.value.find((item) => item.id === matid)?.code
  scope.row.matSpec = matList.value.find((item) => item.id === matid)?.spec
  scope.row.matType = matList.value.find((item) => item.id === matid)?.materialType
  scope.row.matUnit = matList.value.find((item) => item.id === matid)?.unit
}

//新增物料信息
const onAddItem = () => {
  matOpenFormRef.value.open(0, 'group')
  // const newData = {
  //   // 新数据的属性
  //   purchaseOrderId: 0,
  //   matId: '',
  //   matName: '',
  //   matCode: '',
  //   matType: '',
  //   matSpec: '',
  //   matUnit: '',
  //   purchaseAmount: undefined,
  //   estimatedPrice: undefined,
  //   actualPrice: undefined,
  //   arriveTime: '',
  //   description: ''
  // }
  // formData.value.matItemDOList.push(newData)
}
const getList = async (arrMat) => {
  arrMat.forEach((row) => {
    if (formData.value.matItemDOList.filter((item) => item.matId == row.matId).length == 0) {
      row.id = undefined
      formData.value.matItemDOList.push(row)
    }
  })
}
const materialDialog = ref()
const boomDialog = ref()
const onBoomAddItemOpen = () => {
  boomDialog.value.open(formData.value.projectMaterialPlanId)
}
//删除新增物料信息
const handleDelete2 = (index: number) => {
  formData.value.matItemRemoveList.push(formData.value.matItemDOList[index])
  formData.value.matItemDOList.splice(index, 1)
  handleActualPrice()
  handleEstimatedPrice()
}

// 保存物料信息
const saveMaterials = async () => {
  formData.value.matItemDOList.forEach(async (item) => {
    var subData = item as unknown as PurchaseOrderMaterialApi.PurchaseOrderMaterialVO
    subData.materialId = item.matId
    subData.purchaseOrderId = formData.value.id
    if (subData.id == undefined) {
      subData.id = await PurchaseOrderMaterialApi.createPurchaseOrderMaterial(subData)
    } else {
      await PurchaseOrderMaterialApi.updatePurchaseOrderMaterial(subData)
    }
  })
  formData.value.matItemRemoveList.forEach(async (item) => {
    if (item.id != undefined) {
      await PurchaseOrderMaterialApi.deletePurchaseOrderMaterial(item.id)
    }
  })
}
// 修改物料信息
const saveUpMaterials = async () => {
  formData.value.matItemDOList.forEach(async (item) => {
    var subData = item as unknown as OutsourceStockMaterialApi.OutsourceStockMaterialVO
    subData.purchaseAmount = item.purchaseAmount
    subData.materialId = item.matId
    subData.outsourceStockId = formData.value.id
    await OutsourceStockMaterialApi.updateOutsourceStockMaterial(subData)
    // if (subData.id == undefined) {
    //   subData.id = await OutsourceStockMaterialApi.createOutsourceStockMaterial(subData)
    // } else {
    //   await OutsourceStockMaterialApi.updateOutsourceStockMaterial(subData)
    // }
  })
}
//新增物料信息
const onBoomAddItem = () => {
  const newData = {
    // 新数据的属性
    purchaseOrderId: 0,
    boomDetailId: undefined,
    boomName: '',
    boomSpec: '',
    composition: '',
    boomUnit: '',
    boomAmount: undefined,
    boomPurchaseAmount: undefined,
    boomEstimatedPrice: undefined,
    boomActualPrice: undefined,
    boomArriveTime: '',
    boomArriveDate: '',
    boomDescription: ''
  }
  formData.value.boomItemDOList.push(newData)
}
// 保存加工件信息
const saveBooms = async () => {
  formData.value.boomItemDOList.forEach(async (item) => {
    var subData = item as unknown as PurchaseOrderBoomApi.PurchaseOrderBoomVO
    //subData.boomName = item.materialName
    subData.purchaseAmount = item.purchaseAmount
    subData.estimatedPrice = item.estimatedPrice
    subData.actualPrice = item.actualPrice
    subData.arriveTime = item.arriveTime
    subData.requireTime = item.boomArriveDate
    subData.description = item.description
    subData.purchaseOrderId = formData.value.id
    if (subData.id == undefined) {
      subData.id = await PurchaseOrderBoomApi.createPurchaseOrderBoom(subData)
    } else {
      await PurchaseOrderBoomApi.updatePurchaseOrderBoom(subData)
    }
  })
  formData.value.boomItemRemoveList.forEach(async (item) => {
    if (item.id != undefined) {
      await PurchaseOrderBoomApi.deletePurchaseOrderBoom(item.id)
    }
  })
}
// 修改加工件信息
const saveUpBooms = async () => {
  formData.value.boomItemDOList.forEach(async (item) => {
    var subData = item as unknown as OutsourceStockBoomApi.OutsourceStockBoomVO
    subData.boomDetailId = item.boomDetailId
    subData.boomName = item.materialName
    // subData.boomSpec = item.boomSpec
    // subData.composition = item.composition
    // subData.boomUnit = item.boomUnit
    subData.purchaseAmount = item.purchaseAmount
    subData.currentCount = item.currentCount
    subData.unqualifiedCount = item.unqualifiedCount
    subData.projectSubId = item.projectSubId
    subData.unqualifiedContent = item.unqualifiedContent
    subData.repairable = item.repairable
    subData.reason = item.reason
    subData.remark = item.remark
    subData.outsourceStockId = formData.value.id
    await OutsourceStockBoomApi.updateOutsourceStockBoom(subData)
    // if (subData.id == undefined) {
    //   subData.id = await OutsourceStockBoomApi.createOutsourceStockBoom(subData)
    // } else {
    //   await OutsourceStockBoomApi.updateOutsourceStockBoom(subData)
    // }
  })
}
//删除新增物料信息
const handleDeleteBoom = (index: number) => {
  formData.value.boomItemRemoveList.push(formData.value.boomItemDOList[index])
  formData.value.boomItemDOList.splice(index, 1)
  handleActualPrice()
  handleEstimatedPrice()
}

const closeForm = async () => {


  var userId = useUserStore().getUser.id
  var iftrue = await OutsourceStockApi.outCancelWeiWai(formData.value.id, userId)
  reload()
}
const deleteForm = async () => {
  // 提示用户是否保存入库信息
  await message.confirm('确认删除当前采购订单?')

  await PurchaseOrderApi.deletePurchaseOrder(formData.value.id)
  router.push({ path: '/purchase/purchaseorder' })
  tagsViewStore.delVisitedView(router.currentRoute.value)
}
// 保存按钮数据提交
const saveForm = async () => {
  let validateForm = formData.value.goodsType + ''
  // 校验子表单
  try {
    switch (validateForm) {
      case "1":
        //物料
        await subOutSourceMatFormRef.value.validate()
        break
      case "2":
        //加工件
        await subBoomPlanFormRef.value.validate()
        break
      default:
        break
    }
  } catch (e) {
    return
  }
  // 保存数据请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OutsourceStockApi.OutsourceStockVO
    var outsourcestockId = await OutsourceStockApi.updateOutsourceStock(data)
    if (formData.value.goodsType == 1) {
      // 保存物料信息
      await saveUpMaterials()
    }
    if (formData.value.goodsType == 2) {
      // 保存加工件信息
      await saveUpBooms()
    }
    if (formData.value.attachments != undefined && formData.value.attachments.length > 0) {
      //附件信息保存
      matUploadData.value.businessId = formData.value.id
      await matUploadRef.value!.submit()
    }

    message.success(t('common.updateSuccess'))
    dialogVisible.value = false

    // 发送操作成功的事件
    emit('success')
  } finally {
    if (sumbefore.value == 0) {
      reload()
    }
    formLoading.value = false
  }
}
const handleInitPlanSub = async (projectPlanIdArr) => {
  // 生产计划子项列表
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 99,
    projectPlanId: projectPlanIdArr
  })
  formData.value.projectPlanSubs = (await PlanSubApi.getPlanSubPage(queryParams)).list
}
// 提交按钮数据保存
const submitForm = async () => {
  let validateForm = formData.value.goodsType + ''
  // 校验子表单
  try {
    switch (validateForm) {
      case "1":
        //物料
        await subOutSourceMatFormRef.value.validate()
        break
      case "2":
        //加工件
        await subBoomPlanFormRef.value.validate()
        break
      default:
        break
    }
  } catch (e) {
    return
  }
  // 保存数据请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OutsourceStockApi.OutsourceStockVO
    var outsourcestockId = await OutsourceStockApi.updateOutsourceStock(data)
    if (formData.value.goodsType == 1) {
      // 保存物料信息
      await saveUpMaterials()
    }
    if (formData.value.goodsType == 2) {
      // 保存加工件信息
      await saveUpBooms()
    }
    if (formData.value.attachments != undefined && formData.value.attachments.length > 0) {
      //附件信息保存
      matUploadData.value.businessId = formData.value.id
      await matUploadRef.value!.submit()
    }
    await inWarehouse()
    //message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    // if (sumbefore.value == 0) {
    //   reload()
    // }
    formLoading.value = false
  }
}
// 提交入库方法 
const inWarehouse = async () => {
  //先判断是加工件还是原材料
  if (formData.value.goodsType === 2) {
    //为加工件，调用加工件提交方法，生成入库单
    //获取当前登录用户ID
    var userId = useUserStore().getUser.id
    var iftrue = await OutsourceStockApi.outWeiWaiJiaGongJian(formData.value.id, userId)
    reload()
  } else {
    //获取当前登录用户ID
    var userId = useUserStore().getUser.id
    var iftrue = await OutsourceStockApi.outYanCaiLiao(formData.value.id, userId)
    reload()
  }

}
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const supplierInit = ref()
// const matSimpList = ref([]) // 物料基本信息列表

const queryParams = reactive({
  pageNo: 1,
  pageSize: 99,
  outsourceStockId: query.id
})
const matSimpList = ref([]) // 物料基本信息列表
// 页面数据加载初始化
onMounted(async () => {
  // 获取委外入库单信息
  formData.value = await OutsourceStockApi.getOutsourceStock(query.id)
  // 获取采购订单编号
  if (
    formData.value.purchaseId != undefined &&
    formData.value.purchaseId != ''
  ) {
    const purchaseOrderDo = await PurchaseOrderApi.getPurchaseOrder(formData.value.purchaseId)
    formData.value.purchaseNo = purchaseOrderDo.purchaseNo
    // 获取物料需求计划信息
    if (purchaseOrderDo.projectMaterialPlanId!=null){
      const materialPlan = await MaterialPlanApi.getMaterialPlan(purchaseOrderDo.projectMaterialPlanId)
      //获取物料需求计划中的生产计划id，去查询对应子项目
      // 获取生产计划单中子项目编号
      await handleInitPlanSub(materialPlan.projectPlanId)
    }

  }
  if (
    formData.value.supplierId != undefined &&
    formData.value.supplierId != ''
  ) {
    const supplierDo = await SupplierApi.getSupplier(formData.value.supplierId)
    formData.value.supplierName = supplierDo.name
  }

  // 获取原始物料信息
  matSimpList.value = await MaterialApi.getSimpList()

  // 获取采购订单的物料列表
  formData.value.matItemDOList = (
    await OutsourceStockMaterialApi.getOutsourceStockMaterialPage(queryParams)
  ).list
  // var matTypes = getIntDictOptions(DICT_TYPE.HELI_MATERIAL_TYPE)
  // var matUnits = getIntDictOptions(DICT_TYPE.HELI_MATERIAL_UNIT)
  // formData.value.matItemDOList.forEach((item) => {
  //   matList.value.push({ id: item.materialId, code: item.matCode })
  //   item.matType = matTypes.find( op => op.value == matSimpList.value.find((record) => record.id === item.materialId)?.material_type)?.label
  //   item.matUnit = matUnits.find( op => op.value == matSimpList.value.find((record) => record.id === item.materialId)?.unit)?.label
  // })
  formData.value.matItemRemoveList = []
  formData.value.boomItemRemoveList = []


  // 获取采购订单加工件数据
  formData.value.boomItemDOList = (
    await await OutsourceStockBoomApi.getOutsourceStockBoomPage(queryParams)
  ).list;

  // 遍历每个 item，进行属性赋值
  formData.value.boomItemDOList.forEach((item) => {
    if (item) { // 确保 item 存在
      item.boomPurchaseAmount = item.purchaseAmount;
      item.boomEstimatedPrice = item.estimatedPrice;
      item.boomActualPrice = item.actualPrice;
      item.boomArriveTime = item.arriveTime;
      item.boomArriveDate = item.requireTime;
      item.boomDescription = item.description;
      item.materialName = item.boomName;

      // 确保 composition 是一个有效的数组
      if (Array.isArray(item.composition) && item.composition.length > 0) {
        item.composition = Number(item.composition);
      }
    }
  });
  // 获取加工件列表
  // formData.value.boomItemDOList = (
  //   await PurchaseOrderBoomApi.getPurchaseOrderBoomPage(queryParams)
  // ).list
  // formData.value.boomItemDOList.forEach((item) => {
  //   item.boomPurchaseAmount = item.purchaseAmount
  //   item.boomEstimatedPrice = item.estimatedPrice
  //   item.boomActualPrice = item.actualPrice
  //   item.boomArriveTime = item.arriveTime
  //   item.boomArriveDate = item.requireTime
  //   item.boomDescription = item.description
  //   if (item.composition.length > 0) item.composition = Number(item.composition)
  // })

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

  //用户信息，用于底部数据展示
  userList.value = await UserApi.getSimpleUserList()

  supplierInit.value = await SupplierApi.getSimpList()
})

//接收物料传递的数据
const handleSelectedMaterial = (currentIndex: number, newValue: any) => {
  // console.log(currentIndex,'接收物料对应的数据:', newValue)
  formData.value.matItemDOList[currentIndex].matId = newValue?.id
  formData.value.matItemDOList[currentIndex].matName = newValue?.name
  formData.value.matItemDOList[currentIndex].matCode = newValue?.code
  formData.value.matItemDOList[currentIndex].matSpec = newValue?.spec
  formData.value.matItemDOList[currentIndex].matType = newValue?.materialType
  formData.value.matItemDOList[currentIndex].matUnit = newValue?.unit
}
//接收加工件物料传递的数据
const handleSelectedBoomMaterial = (currentIndex: number, newValue: any) => {
  // console.log(currentIndex,'接收物料对应的数据:', newValue)
  formData.value.boomItemDOList[currentIndex].boomDetailId = newValue?.id
  formData.value.boomItemDOList[currentIndex].materialName = newValue?.name
  // formData.value.boomItemDOList[currentIndex].matCode = newValue?.code
  // formData.value.boomItemDOList[currentIndex].matSpec = newValue?.spec
  // formData.value.boomItemDOList[currentIndex].matType = newValue?.materialType
  // formData.value.boomItemDOList[currentIndex].matUnit = newValue?.unit
}
//接收供应商传递的数据
const handleSelectedSupplier = (newValue: any) => {
  formData.value.supplierId = newValue?.id
}
</script>
