<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="projectMaterialPlanNo">
                      <el-input class="!w-265px" placeholder="系统自动生成" v-model="formData.projectMaterialPlanNo" disabled />
                    </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-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="生产计划单号" prop="planNo">
                      <el-input class="!w-265px" placeholder="生产计划单号" v-model="formData.planNo" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>

              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目编号" prop="projectCode">
                      <el-input class="!w-265px" v-model="formData.projectCode" placeholder="项目编号" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>

              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="description">
                  <el-input class="!w-713px" type="textarea" v-model="formData.description" show-word-limit maxlength="200" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input class="!w-265px" placeholder="项目名称" v-model="formData.projectName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="单据状态" prop="status">
                  <el-select v-model="formData.status" placeholder="单据状态" clearable class="!w-265px" disabled>
                    <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_MATERIAL_PLAN_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </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-button class="hl-addbutton" type="primary" size="large" @click="onAddItem" disabled>添加</el-button>
                <el-button class="hl-addbutton" type="primary" size="large" @click="onAddItem" disabled>新增</el-button>
              </el-col>
              <el-form ref="subFormRef" :model="formData.matItemDOList" :rules="subFormRules" v-loading="subFormLoading" 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="matCode" label="物料编码" min-width="120" align="center" /> -->
                  <el-table-column prop="matId" min-width="200" align="center">
                    <template #header> <span class="hl-table_header">*</span>物料编码/名称 </template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.matId`" :rules="subFormRules.matId" class="mb-0px!">
                        <!-- <el-select v-model="scope.row.matId" placeholder="物料编码/名称" :remote-method="remoteMatNameSearch"
                          remote-show-suffix remote clearable reserve-keyword filterable :loading="matSelectLoading"
                          @change="(val) => handleMatName(scope, val)" class="!w-180px">
                          <el-option v-for="item in matList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select> -->
                        <MaterialSelect v-model="scope.row.matId" disabled @update:new-value="handleSelectedMaterial(scope.$index, $event)" />

                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="matType" label="物料类型" min-width="125" align="center">
                    <template #default="scope">
                      <dict-tag :type="DICT_TYPE.HELI_MATERIAL_TYPE" :value="scope.row.matType" v-if="scope.row.matType ? true : false" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="matSpec" label="规格/型号" min-width="120" align="center" />
                  <el-table-column prop="matUnit" label="系统单位" min-width="100" align="center">
                    <template #default="scope">
                      <dict-tag :type="DICT_TYPE.HELI_MATERIAL_UNIT" :value="scope.row.matUnit" v-if="scope.row.matUnit ? true : false" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="requireAmount" min-width="160" align="center">
                    <template #header><span class="hl-table_header">*</span>需求数量</template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.requireAmount`" :rules="subFormRules.requireAmount" class="mb-0px!">
                        <el-input-number style="width: 100%" v-model="scope.row.requireAmount" placeholder="需求数量" :min="0" :precision="2" disabled />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="160" align="center">
                    <template #header> <span class="hl-table_header">*</span>需求到货日期 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.requireArriveTime`" :rules="subFormRules.requireArriveTime" class="mb-0px!">
                        <el-date-picker class="!w-265px" v-model="row.requireArriveTime" type="date" value-format="x" placeholder="需求到货日期" disabled />
                      </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`" :rules="subFormRules.projectSubId" class="mb-0px!">
                        <el-select class="!w-365px" v-model="row.projectSubId" clearable disabled>
                          <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="description" min-width="200" label="备注" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.description" disabled />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" fixed="right" width="120">
                    <template #default="scope">
                      <el-button link type="danger" size="small" @click.prevent="handleDeleteMat(scope.$index)" disabled>
                        删除
                      </el-button>
                    </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-button class="hl-addbutton" type="primary" size="large" @click="onAddBoomItem" disabled>新增</el-button>
              </el-col>
              <el-form ref="subBoomFormRef" :model="formData.boomItemDOList" :rules="subBoomFormRules" v-loading="subBoomFormLoading" label-width="0">
                <el-table :data="formData.boomItemDOList" class="hl-table" :show-overflow-tooltip="true" :stripe="true">
                  <el-table-column type="index" label="序号" min-width="60" align="center" />
                  <el-table-column prop="materialName" label="零件名称" min-width="120" align="center" />
                  <el-table-column prop="boomSpec" label="规格/型号" min-width="120" align="center" />
                  <el-table-column prop="compositionName" label="材质" min-width="100" align="center" />
                  <el-table-column prop="boomUnit" label="系统单位" min-width="100" align="center">
                    <template #default="scope">
                      <dict-tag :type="DICT_TYPE.HELI_MATERIAL_UNIT" :value="scope.row.boomUnit" v-if="scope.row.boomUnit ? true : false" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="boomAmount" min-width="160" align="center">
                    <template #header><span class="hl-table_header">*</span>需求数量</template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.boomAmount`" :rules="subBoomFormRules.boomAmount" class="mb-0px!">
                        <el-input-number style="width: 100%" v-model="scope.row.boomAmount" placeholder="需求数量" :min="0" :precision="2" disabled />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="180" align="center">
                    <template #header> <span class="hl-table_header">*</span>需求到货日期 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.boomArriveDate`" :rules="subBoomFormRules.boomArriveDate" class="mb-0px!">
                        <el-date-picker  v-model="row.boomArriveDate" type="date" value-format="x" placeholder="需求到货日期" disabled />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="projectSubCode" label="子项目编号" min-width="350" align="center" />
                  <!-- <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}.projectSubId`" :rules="subFormRules.projectSubId" class="mb-0px!">
                        <el-select class="!w-265px" v-model="row.projectSubId" clearable>
                          <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="description" min-width="200" label="备注" align="center">
                    <template #default="scope">
                      <el-input v-model="scope.row.description" disabled />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" fixed="right" width="120">
                    <template #default="scope">
                      <el-button link type="danger" size="small" @click.prevent="handleDeleteBoom(scope.$index)" disabled>
                        删除
                      </el-button>
                    </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 :limit="10" :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="UpError" class="upload-file-uploader">
                  <el-button type="primary" disabled>
                    <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 @click="handleDeleteAttachment(scope.$index, scope.row.businessFileType)">
                      删除
                    </el-button>
                    <el-button 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">
        <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="submitUserId" label="送审人">
              {{ userList.find((user) => user.id == formData.submitUserId)?.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-row justify="center">
          <el-col :span="8">
            <el-form-item prop="auditor" label="审核人">
              {{ userList.find((user) => user.id == formData.auditor)?.nickname }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="auditTime" label="审核时间">
              {{ formatDate(formData.auditTime, '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="closeForm" size="large">取 消</el-button>
    </div>
  </el-card>

  <!-- 表单弹窗：物料列表 -->
  <booms ref="boomOpenFormRef" @success="getBoomList" />
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as MaterialPlanApi from '@/api/heli/materialplan'
import * as MaterialPlanDetailApi from '@/api/heli/materialplandetail'
import * as MaterialPlanBoomApi from '@/api/heli/materialplanboom'
import type { UploadUserFile } from 'element-plus'
import * as PlanApi from '@/api/heli/plan'
import * as PlanSubApi from '@/api/heli/plansub'
import * as ProjectOrderApi from '@/api/heli/projectorder'
import * as UserApi from '@/api/system/user'
import * as MaterialApi from '@/api/heli/material'
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 booms from './boom.vue'

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,
  projectMaterialPlanNo: undefined,
  projectId: undefined,
  projectPlanId: undefined,
  projectPlanNo: undefined,
  projectCode: undefined,
  auditor: undefined,
  createTime: new Date(),
  status: undefined,
  description: undefined,
  boomItemDOList: [],
  boomItemRemoveList: [],
  matItemDOList: [],
  matItemRemoveList: [],
  attachments: []
})
const formRules = reactive({
  projectPlanId: [{ required: true, message: '生产计划单号不能为空', trigger: 'blur' }]
})

const subBoomFormRules = reactive({
  boomAmount: [{ required: true, message: '需求数量不能为空', trigger: 'blur' }],
  boomArriveDate: [{ required: true, message: '需求数量不能为空', trigger: 'blur' }]
})
const subFormRules = reactive({
  matId: [{ required: true, message: '物料编码不能为空', trigger: 'blur' }],
  requireAmount: [{ required: true, message: '需求数量不能为空', trigger: 'blur' }],
  requireArriveTime: [{ required: true, message: '需求到货日期不能为空', trigger: 'blur' }],
  projectSubId: [{ required: true, message: '子项目编号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const subFormRef = ref() // 表单 Ref

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

const onAddBoomItem = () => {
  //noZero: number,whId?: number,isAll?: number
  boomOpenFormRef.value.open(formData.value.projectPlanId)
}

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 uploadUrl = ref(import.meta.env.VITE_UPLOAD_BATCH_URL)
const matUploadRef = ref()
const uploading = ref(false)

const matUploadFiles = ref<UploadUserFile[]>([])
const matUploadData = ref({
  businessType: 'MATERIALPLAN',
  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.name = 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 = () => {
  const newData = {
    // 新数据的属性
    stockId: 0,
    matId: '',
    matName: '',
    matCode: '',
    matType: '',
    matSpec: '',
    matUnit: '',
    requireAmount: undefined,
    requireArriveTime: '',
    projectSubId: '',
    description: ''
  }
  formData.value.matItemDOList.push(newData)
}
//删除新增物料信息
const handleDeleteMat = (index: number) => {
  formData.value.matItemRemoveList.push(formData.value.matItemDOList[index])
  formData.value.matItemDOList.splice(index, 1)
}

//删除新增物料信息
const handleDeleteBoom = (index: number) => {
  formData.value.boomItemRemoveList.push(formData.value.boomItemDOList[index])
  formData.value.boomItemDOList.splice(index, 1)
}
const handleInitPlanSub = async () => {
  // // 项目子项列表
  // formData.value.projectOrderSubs = await ProjectOrderApi.getProjectOrderSubListByProjectOrderId(
  //   formData.value.projectId
  // )

  // 生产计划子项列表
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 99,
    projectPlanId: formData.value.projectPlanId
  })

  formData.value.projectPlanSubs = (await PlanSubApi.getPlanSubPage(queryParams)).list
  console.log( formData.value.projectPlanSubs)
  // formData.value.projectOrderSubs.forEach((item) => {
  //   if (formData.value.projectPlanSubs.filter((sub) => sub.projectSubId == item.id).length > 0) {
  //     var subTemp = formData.value.projectPlanSubs.find((sub) => sub.projectSubId == item.id)
  //     item.projectSubId = subTemp.projectSubId
  //     item.projectSubCode = subTemp.projectSubCode
  //   }
  // })
}
// 保存物料信息
const saveMaterials = async () => {
  formData.value.matItemDOList.forEach(async (item) => {
    var subData = item as unknown as MaterialPlanDetailApi.MaterialPlanDetailVO
    subData.materialId = item.matId
    subData.projectMaterialPlanId = formData.value.id
    if (subData.id == undefined) {
      subData.id = await MaterialPlanDetailApi.createMaterialPlanDetail(subData)
    } else {
      await MaterialPlanDetailApi.updateMaterialPlanDetail(subData)
    }
  })
  formData.value.matItemRemoveList.forEach(async (item) => {
    if (item.id != undefined) {
      await MaterialPlanDetailApi.deleteMaterialPlanDetail(item.id)
    }
  })
}
// 保存加工件信息
const saveBooms = async () => {
  formData.value.boomItemDOList.forEach(async (item) => {
    var subData = item as unknown as MaterialPlanBoomApi.MaterialPlanBoomVO
    subData.boomDetailId = item.boomDetailId
    subData.projectMaterialPlanId = formData.value.id
    if (subData.saveId == undefined) {
      subData.id = undefined
      subData.saveId = await MaterialPlanBoomApi.createMaterialPlanBoom(subData)
    } else {
      await MaterialPlanBoomApi.updateMaterialPlanBoom(subData)
    }
  })
  formData.value.boomItemRemoveList.forEach(async (item) => {
    if (item.saveId != undefined) {
      await MaterialPlanBoomApi.deleteMaterialPlanBoom(item.saveId)
    }
  })
}
const closeForm = async () => {
  router.push({ path: '/purchase/materialplan' })
  tagsViewStore.delVisitedView(router.currentRoute.value)
}
const deleteForm = async () => {
  // 提示用户确认删除当前物料需求计划
  await message.confirm('确认删除当前物料需求计划?')

  await MaterialPlanApi.deleteMaterialPlan(formData.value.id)
  router.push({ path: '/purchase/materialplan' })
  tagsViewStore.delVisitedView(router.currentRoute.value)
}
// 保存按钮数据提交
const saveForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaterialPlanApi.MaterialPlanVO
    await MaterialPlanApi.updateMaterialPlan(data)

    // 保存物料信息
    await saveMaterials()

    //保存加工件信息
    await saveBooms()
    //formData.value.matItemDOList

    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 {
    formLoading.value = false
    if (sumbefore.value == 0) {
      reload()
    }
  }
}
// 送审按钮数据提交
const submitForm = async () => {
  if (formData.value.matItemDOList.length == 0 && formData.value.boomItemDOList.length == 0) {
    message.alertWarning('物料明细和加工件明细不能同时为空，请添加!')
    return
  }
  let isRepeat = false
  let repeatInfo = ''

  formData.value.matItemDOList.filter((item) => {
    if (
      formData.value.matItemDOList.filter(
        (mat) => mat.matId == item.matId && mat.projectSubId == item.projectSubId
      ).length > 1
    ) {
      repeatInfo += '[' + item.matName + '-' + item.projectSubId + ']、'
      isRepeat = true
    }
  })
  if (isRepeat) {
    message.alertWarning('物料编码+子项目编号不能重复!')
    return
  }
  // 校验子表单
  try {
    await subFormRef.value.validate()
    await subBoomFormRef.value.validate()
  } catch (e) {
    return
  }
  // 计划状态为已送审
  formData.value.status = 2
  formData.value.submitUserId = useUserStore().getUser.id
  await saveForm()
}
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const planInit = ref()
const projectInit = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 99,
  projectMaterialPlanId: query.id
})
// 页面数据加载初始化
onMounted(async () => {
  // 获取物料需求计划信息
  formData.value = await MaterialPlanApi.getMaterialPlan(query.id)
  // 获取生产计划数据
  planInit.value = await PlanApi.getPlan(formData.value.projectPlanId)
  // 获取项目订单数据
  projectInit.value = await ProjectOrderApi.getProjectOrder(formData.value.projectId)

  formData.value.boomItemDOList = []
  formData.value.boomItemRemoveList = []
  formData.value.planNo = planInit.value.planNo
  formData.value.projectName = projectInit.value.projectName
  formData.value.projectCode = projectInit.value.code

  // 获取物料需求计划的加工件列表
  formData.value.boomItemDOList = (
    await MaterialPlanBoomApi.getMaterialPlanBoomPage(queryParams)
  ).list
  formData.value.boomItemDOList.map((item) => (item.saveId = item.id))

  // 获取物料需求计划的物料列表
  formData.value.matItemDOList = (
    await MaterialPlanDetailApi.getMaterialPlanDetailPage(queryParams)
  ).list
  formData.value.matItemDOList.forEach((item) => {
    matList.value.push({ id: item.matId, name: item.matName })
  })
  formData.value.matItemRemoveList = []
  // 获取生产计划单中子项目编号
  await handleInitPlanSub()

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

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

//接收物料传递的数据
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
}
</script>
