<template>
  <!-- 出库 -->
  <el-card class="hl-card" style="position: relative">
    <template #header>
      <span v-text="dialogTitle"></span>
    </template>
    <div class="abstatus">
      <img src="/src/assets/imgs/status/status2.png" v-if="formData.status == 2" alt="" />
      <img src="/src/assets/imgs/status/statuszf.png" v-else-if="formData.status == 3" alt="" />
      <span v-else></span>
    </div>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="200px" 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="8">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="stockNo" label="盘点单号">
                  <el-input v-model="formData.stockNo" disabled placeholder="系统自动生成" class="!w-400px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item prop="whId" label="盘点仓库" required>
                  <el-select v-model="formData.whId" placeholder="下拉选择" clearable disabled class="!w-400px" @change="handleWh">
                    <el-option v-for="dict in whList" :key="dict.id" :label="dict.wh_name" :value="dict.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="status" label="单据状态">
                  <el-select v-model="formData.status" placeholder="下拉选择" clearable class="!w-400px" disabled>
                    <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_STORAGE_MAT_CHECK_STATUS)" :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 prop="checkType" label="盘点类型">
                  <el-select v-model="formData.checkType" clearable class="!w-400px" disabled>
                    <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_STORAGE_MAT_CHECK_TYPE)" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="24">
                <el-form-item label="排除库存为0的物料?" prop="noZero" >
                  <el-switch
                      v-model="noZeroSwich"
                      inline-prompt
                      active-text="是"
                      inactive-text="否"
                      disabled="true"
                    />
                  <!-- <el-radio-group v-model="formData.noZero" disabled>
                    <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)" :key="dict.value" :label="dict.value">
                      {{ dict.label }}
                    </el-radio>
                  </el-radio-group> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="盘点开始日期" prop="checkTime">
                  <el-date-picker v-model="formData.checkTime" value-format="x" placeholder="盘点开始时间" class="!w-220px" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="备注" prop="description">
              <el-input type="textarea" v-model="formData.description" show-word-limit maxlength="200" disabled />
            </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>
            <el-card class="hl-incard">
              <el-col>
                <el-button class="hl-addbutton" type="primary" size="large" :disabled="ctrView || ctrSave" @click="openMatForm">获取物料</el-button>
              </el-col>
              <el-form ref="matSubFormRef" :model="formData.matItemDOList" :rules="subFormRules" v-loading="subFormLoading" label-width="0">
                <el-table :data="formData.matItemDOList" class="hl-table">
                  <el-table-column prop="cid" label="序号" :width="80" />
                  <el-table-column prop="matCode" label="物料编码" min-width="120" align="center" />
                  <el-table-column prop="matName" label="物料名称" min-width="140" align="center" />
                  <el-table-column prop="matType" label="物料类型" min-width="120" align="center" />
                  <el-table-column prop="shortName" label="物料简称" min-width="120" align="center" />
                  <el-table-column prop="matSpec" label="规格/型号" min-width="120" align="center" />
                  <el-table-column prop="matBrand" label="品牌" min-width="120" align="center" />
                  <el-table-column prop="rgId" min-width="140" align="center">
                    <template #header> <span class="hl-table_header">*</span>库区 </template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.rgId`" :rules="subFormRules.rgId" class="mb-0px!">
                        <el-select v-model="scope.row.rgId" placeholder="" style="width: 100%" @change="(val)=>handleRg(val,scope)" :disabled="ctrView || ctrSave">
                          <el-option v-for="dict in rgList" :key="dict.id" :label="dict.rg_name" :value="dict.id" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="pnId" min-width="180" align="center">
                    <template #header> <span class="hl-table_header">*</span>库位 </template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.pnId`" :rules="subFormRules.pnId" class="mb-0px!">
                        <el-select v-model="scope.row.pnId" placeholder="" style="width: 100%" @change="(val)=>handlePn(val,scope)" :disabled="ctrView || ctrSave">
                          <el-option v-for="dict in scope.row.pnlist" :key="dict.id" :label="dict.pn_name" :value="dict.id" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="matRest" label="库存数量" min-width="120" align="center" />
                  <el-table-column prop="storageOkQty" min-width="120" align="center">
                    <template #header> <span class="hl-table_header">*</span>盘点数量</template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.storageOkQty`" :rules="subFormRules.storageOkQty" class="mb-0px!">
                        <el-input v-model="scope.row.storageOkQty" @change="(val)=>handleSub(val,scope)" :disabled="ctrView || ctrSave" />
                      </el-form-item>
                    </template>
                  </el-table-column>

				<!-- <el-table-column prop="money" min-width="120" align="center"  >
				  <template #header> <span class="hl-table_header">*</span>金额</template>
				  <template #default="scope">
				    <el-form-item :prop="`${scope.$index}.money`" :rules="subFormRules.money" class="mb-0px!" >
				      <el-input v-model="scope.row.money" :disabled="ctrView || ctrSave"  />
				    </el-form-item>
				  </template>
				</el-table-column> -->
				 <el-table-column prop="onemoney" label="单价" min-width="120" align="center">
          				  <template #default="scope">
				    <el-form-item :prop="`${scope.$index}.onemoney`"  class="mb-0px!" >
				      <el-input v-model="scope.row.onemoney" :disabled="ctrView || ctrSave"  />
				    </el-form-item>
				  </template>
        </el-table-column>





                  <el-table-column prop="matSub" label="盈亏差异" min-width="120" align="center">
                    <template #default="scope">
                      <div v-if="scope.row.matSub<0" style="color:#EC808D;">
                        {{scope.row.matSub}}
                      </div>
                      <span v-else-if="scope.row.matSub>0" style="color:#63A103;">
                        +{{scope.row.matSub}}
                      </span>
                      <span v-else>
                        {{scope.row.matSub}}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="matUnit" label="库存单位" min-width="120" align="center" />
                  <el-table-column label="操作" align="center" width="240">
                    <template #default="scope" >
                      <el-button link type="danger" size="small" @click.prevent="handleDelete2(scope.$index)" :disabled="ctrView || ctrDelete" v-if="scope.row.isCopy==1">
                        删除
                      </el-button>
                      <el-button link type="primary" v-if="scope.row.isCopy==0" @click="handleCopy(scope.$index, scope.row)" :disabled="ctrView || ctrDelete">复制</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 :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="ctrView || ctrSave">
                    <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="附件上传中..." style="margin-top: 10px" 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" @click="handleDeleteAttachment(scope.$index, scope.row.businessFileType)" :disabled="ctrView || ctrDelete">
                      删除
                    </el-button>
                    <el-button link type="primary" size="small" @click="downloadAttachment(scope.row.name, scope.row.url)" :disabled="ctrView || ctrDelete">
                      下载
                    </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="keeper" label="提交人">
              {{ userList.find((user) => user.id == formData.keeper)?.nickname }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="keepTime" label="提交时间">
              {{ formatDate(formData.keeperTime, 'YYYY-MM-DD HH:mm') }}
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row justify="center">
          <el-col :span="8">
            <el-form-item prop="cancel" label="作废人">
              {{ userList.find((user) => user.id == formData.cancel)?.nickname }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="cancelTime" label="作废时间">
              {{ formatDate(formData.cancelTime, 'YYYY-MM-DD HH:mm') }}
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-dialog v-model="centerDialogVisible" title="提醒" width="30%" center>
				<span>
					提交后将修改库存数量，是否继续！
				</span>
				<template #footer>
					<span class="dialog-footer">
            <el-button type="primary" @click="sureToSubmit()">
							确认
						</el-button>
						<el-button @click="centerDialogVisible = false">取消</el-button>
					</span>
				</template>
			</el-dialog>
      <el-dialog v-model="deleteDialogVisible" title="提醒" width="30%" center>
				<span>
					删除后单据将被作废，是否继续！
				</span>
				<template #footer>
					<span class="dialog-footer">
            <el-button type="primary" @click="sureToDelete()">
							确认
						</el-button>
						<el-button @click="deleteDialogVisible = false">取消</el-button>
					</span>
				</template>
			</el-dialog>
      </el-card>
    </el-form>
    <div class="hl-footer text-center">
      <el-button @click="() => router.go(-1)" size="large">取 消</el-button>
      <el-button @click="submitForm" type="success" v-if="btnSave" size="large">保
        存</el-button>
      <el-button @click="handleStatus(2)" type="primary" v-if="btnSave" size="large">提
        交</el-button>
      <el-button @click="handleStatus(3)" type="danger" v-if="btnCancel" size="large">删
        除</el-button>
    </div>
  </el-card>

  <!-- 表单弹窗：物料列表 -->
  <materials ref="matOpenFormRef" @success="getList" />
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { dateFormatter, formatDate } from '@/utils/formatTime'

import { getIntDictOptions, getDictLabel, DICT_TYPE } from '@/utils/dict'
import { getAccessToken, getTenantId } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'

import * as CheckApi from '@/api/heli/storagecheck'
import * as CheckMatApi from '@/api/heli/storagecheckmat'
import * as MatApi from '@/api/heli/material'

import * as UserApi from '@/api/system/user'
import * as WhApi from '@/api/heli/warehouse'
import * as RgApi from '@/api/heli/rg'
import * as PnApi from '@/api/heli/pn'

import type { UploadUserFile } from 'element-plus'
import { deleteFile, downloadFile, getFilePage } from '@/api/infra/file'
import download from '@/utils/download'
import materials from './materialsNew.vue'

const reload: any = inject('reload')
const centerDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { query } = useRoute()
const router = useRouter()
const noZeroSwich = ref(false)
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  stockNo: undefined,
  checkType: undefined,
  checkTime: undefined,
  status: undefined,
  noZero: undefined,
  whId: undefined,
  description: undefined,
  creator: undefined,
  createTime: undefined,
  keeper: undefined,
  keeperTime: undefined,
  outbound: undefined,
  outboundTime: undefined,
  cancel: undefined,
  cancelTime: undefined,
  matItemDOList: [],
  attachments: []
})

const formRules = reactive({
  // name: [{ required: true, message: '模具类型不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '启用状态不能为空', trigger: 'blur' }],
  stockInType: [{ required: true, message: '出库类型不能为空', trigger: 'blur' }],
  whId: [{ required: true, message: '出库仓库不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const matSubFormRef = ref() //子表单 Ref
const matOpenFormRef = ref()

const openMatForm = () => {
  //noZero: number,whId?: number,isAll?: number
  matOpenFormRef.value.open(formData.value.noZero, formData.value.whId, formData.value.checkType)
}

const subFormLoading = ref(false) // 子表单的加载中
const subFormRules = reactive({
  matId: [{ required: true, message: '物料不能为空', trigger: 'blur' }],
  rgId: [{ required: true, message: '库区不能为空', trigger: 'blur' }],
  pnId: [{ required: true, message: '库位不能为空', trigger: 'blur' }],
  storageOkQty: [{ required: true, message: '盘点数量不能为空', trigger: 'blur' }],
  money: [{ required: true, message: '金额不能为空', trigger: 'blur' }]
})
const handleStatus = async (num) => {
  formData.value.status = num
  if (num == 2) {
    // 校验表单
    await formRef.value.validate()
    if (formData.value.matItemDOList == undefined || formData.value.matItemDOList.length === 0) {
      message.alertWarning('请添加物料信息!')
      return
    }

    // 校验子表单
    try {
      var isRepeat = false
      formData.value.matItemDOList.forEach((item) => {
        if (
          formData.value.matItemDOList.filter(
            (mat) => mat.matId == item.matId && mat.pnId == item.pnId
          ).length > 1
        ) {
          isRepeat = true
        }
      })
      if (isRepeat) {
        message.alertWarning('存在相同库位的物料信息,请修改,避免重复盘点!')
        return
      }
      await matSubFormRef.value.validate()
    } catch (e) {
      return
    }
    formData.value.keeper = useUserStore().getUser.id
    centerDialogVisible.value = true;
  } else {
    deleteDialogVisible.value = true;
  }
}
const sureToDelete = async() =>{
    formData.value.cancel = useUserStore().getUser.id
    const data = formData.value as unknown as CheckApi.StorageCheckVO
    deleteDialogVisible.value = false;
    await CheckApi.updateStorageCheck(data)
    await initStatus(formData.value.status)
    if (sumbefore.value == 0) {
      reload()
    }
}
const getList = async (arrMat) => {
  arrMat.forEach((row) => {
    row.cid = matCount
    if (
      formData.value.matItemDOList.filter(
        (item) =>
          item.matId == row.id &&
          item.whId == row.whId &&
          item.rgId == row.rgId &&
          item.pnId == row.pnId
      ).length == 0
    ) {
      row.isCopy = 0
      row.matId = row.id
      row.pnlist = ref([])
      row.pnlist = pnList.value.filter((pn) => pn.rg_id == row.rgId)
      if (row.pnlist.length == 0) {
        row.rgId = ''
        row.pnId = ''
        row.matRest = 0
      }
      console.log(row.price)
      if(row.price){
        row.onemoney = row.price
      }
      formData.value.matItemDOList.push(row)
      matCount = matCount + 1
    }
  })
  //formData.value.matItemDOList = arrMat
}
// 复制数据
const handleCopy = (index, item) => {
  const data: any = formData.value.matItemDOList[index]

  // 复制数据
  const newData: any = {
    ...data,
    isCopy: 1,
    cid: matCount
  }
  // 添加新数据
  formData.value.matItemDOList.splice(index + 1, 0, newData)
  matCount = matCount + 1
}
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

// ====================附件信息 开始=======================================
const uploadUrl = ref(import.meta.env.VITE_UPLOAD_BATCH_URL)
const matUploadRef = ref()
const matUploadFiles = ref<UploadUserFile[]>([])
const uploading = ref(false)
const matUploadData = ref({
  businessType: 'STORAGECHECK',
  businessId: formData.value.id,
  businessFileType: ''
})
const matUploadChange = (file, files) => {
  matUploadFiles.value = files
  refreshAttachments(files, '')
}

// 记录待上传、成功上传及失败上传的文件数量
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 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 emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const saveFormData = async () => {
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CheckApi.StorageCheckVO
    await CheckApi.updateStorageCheck(data)
    //物料信息保存
    if (formData.value.matItemDOList) {
      formData.value.matItemDOList.forEach((item) => {
        item.checkId = formData.value.id
        item.whId = formData.value.whId
      })
    }
    const dataMats = formData.value.matItemDOList as unknown as CheckMatApi.StorageCheckMatVO[]
    await CheckMatApi.createCheckMatBatch(dataMats, formData.value.id)

    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'))
  } finally {
    formLoading.value = false
  }
}
const sureToSubmit = async() =>{
  centerDialogVisible.value = false;
    //保存表单数据
    await saveFormData()
    await CheckApi.updateStorageCheckStatus(formData.value.id)
    await initStatus(formData.value.status)
    if (sumbefore.value == 0) {
      reload()
    }
}

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  if (formData.value.matItemDOList == undefined || formData.value.matItemDOList.length === 0) {
    message.alertWarning('请添加物料信息!')
    return
  }

  // 校验子表单
  try {
    var isRepeat = false
    formData.value.matItemDOList.forEach((item) => {
      if (
        formData.value.matItemDOList.filter(
          (mat) => mat.matId == item.matId && mat.pnId == item.pnId
        ).length > 1
      ) {
        isRepeat = true
      }
    })
    if (isRepeat) {
      message.alertWarning('存在相同库位的物料信息,请修改,避免重复盘点!')
      return
    }


    await matSubFormRef.value.validate()
  } catch (e) {
    return
  }
    //保存表单数据
    await saveFormData()

await initStatus(formData.value.status)

// 成功后刷新
if (sumbefore.value == 0) {
  reload()
}
}

var matCount = 1

//删除新增物料信息
const handleDelete2 = (index: number) => {
  var itemDelteing = formData.value.matItemDOList[index]
  if (itemDelteing.isCopy == 0) {
    message.alertWarning('原始物料不能删除')
  } else {
    formData.value.matItemDOList.splice(index, 1)
  }
}

//仓库全数据
const whList = ref([])
//库区全数据
var rgList = ref([])
//库位全数据
var pnList = ref([])

const handleRg = async (rgid, scope) => {
  //-------------------库位全数据
  scope.row.pnId = ''
  scope.row.pnlist = pnList.value.filter((pn) => pn.rg_id === rgid)
  //-------------------
}
const handlePn = async (pnid, scope) => {
  //-------------------库位全数据
  if (
    formData.value.matItemDOList.filter(
      (item) =>
        item.id == scope.row.id &&
        item.whId == scope.row.whId &&
        item.rgId == scope.row.rgId &&
        item.pnId == pnid
    ).length > 1
  ) {
    scope.row.matRest = 0
    message.alertWarning('物料编码' + scope.row.matCode + ',当前库位已存在，请修改，避免重复盘点')

    return
  }
  var currentMatRest = await CheckApi.getStorageNowMatRestNew(scope.row.id, scope.row.pnId)
  scope.row.matRest = currentMatRest
  if (scope.row.storageOkQty == undefined || scope.row.storageOkQty == '') {
    scope.row.matSub = 0
  } else {
    scope.row.matSub = scope.row.storageOkQty - scope.row.matRest
  }
  //-------------------
}
const handleSub = async (pNum, scope) => {
  //-------------------库位全数据
  // scope.row.matSub = Number(pNum) - Number(scope.row.matRest)
  // console.log(typeof scope.row.matSub)

  const matSubValue = Number(pNum) - Number(scope.row.matRest)
  scope.row.matSub = matSubValue.toFixed(2) // 保留两位小数
  console.log(typeof scope.row.matSub)
}

//仓库列表
const init_page_wh = async () => {
  whList.value = await WhApi.getSimpList()
}
//库区列表
const init_page_rg = async () => {
  var rgData = await RgApi.getSimpList()
  rgList.value = rgData.filter((item) => item.wh_id == formData.value.whId)
}
//库位列表
const init_page_pn = async () => {
  var pnData = await PnApi.getSimpList()
  pnList.value = pnData.filter((item) => item.wh_id == formData.value.whId)
}
// 按钮控制
const ctrView = ref(false)
const ctrSave = ref(false)
const ctrCancel = ref(true)
const ctrDelete = ref(false)
const btnSave = ref(true)
const btnCancel = ref(false)

// 根据页面动作和数据状态控制按钮输入框信息
const initStatus = async (status) => {
  switch (status) {
    case 1:
      ctrView.value = false
      ctrSave.value = false
      ctrCancel.value = true
      ctrDelete.value = false

      btnSave.value = true
      btnCancel.value = true
      break
    case 2:
      ctrView.value = false
      ctrSave.value = true
      ctrCancel.value = false
      ctrDelete.value = true
      btnSave.value = false
      btnCancel.value = false
      break
    case 3:
      ctrView.value = true
      ctrSave.value = true
      ctrCancel.value = true
      ctrDelete.value = true
      btnSave.value = false
      btnCancel.value = false
      break
    default:
      break
  }
  // 查看页面时可操作控件禁用
  if (query.type === 'review') {
    ctrView.value = true
    ctrSave.value = true
    ctrCancel.value = true
    ctrDelete.value = true

    btnSave.value = false
    btnCancel.value = false
  }
}
/** 初始化 **/
onMounted(async () => {
  dialogTitle.value = query.type === 'update' ? '编辑页' : '详情页'

  formData.value = await CheckApi.getStorageCheck(query.id)
  if(formData.value.noZero != 2){
    noZeroSwich.value = true
  }
  // 页面控件可视初始化
  await initStatus(formData.value.status)

  await init_page_wh()
  await init_page_rg()
  await init_page_pn()

  const dataCheckMats = await CheckMatApi.getStorageCheckListByCheckID(query.id)
  formData.value.matItemDOList = dataCheckMats

  if (formData.value.matItemDOList == undefined) {
    formData.value.matItemDOList = []
  }

  const dataMatSimples = await MatApi.getSimpList()

  formData.value.matItemDOList.forEach((item) => {
    var matFind = dataMatSimples.find((simp) => simp.id == item.matId)
    item.isCopy = 0
    item.matName = matFind?.name
    item.matCode = matFind?.code
    item.matSpec = matFind?.spec
    item.matUnit = getDictLabel(DICT_TYPE.HELI_MATERIAL_UNIT, matFind?.unit)
    item.matType = getDictLabel(DICT_TYPE.HELI_MATERIAL_TYPE, matFind?.unit)
    item.matBrand = matFind?.brand
    item.shortName = matFind?.short_name
    item.matSub = item.storageOkQty - item.matRest
    item.pnlist = pnList.value.filter((pn) => pn.rg_id == item.rgId)
  })

  formData.value.matItemDOList.sort((a, b) => a.matCode - b.matCode)
  formData.value.matItemDOList.forEach((item) => {
    item.cid = matCount
    matCount = matCount + 1
  })
  // 附件信息
  let attParams = {
    pageNo: 1,
    pageSize: 99,
    businessId: query.id,
    businessType: 'STORAGECHECK'
  }
  formData.value.attachments = (await getFilePage(attParams)).list
  //用户信息
  userList.value = await UserApi.getSimpleUserList()
})
</script>
<style>
a {
  color: #409eff;
  text-decoration: none;
}
</style>
