<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <ContentWrap class="borderxx">
      <el-form class="-mb-15px" :model="queryReqVo" :inline="true" label-width="108px">
        <el-form-item label=" 物料编码：" label-width="150px">
          <el-input v-model="queryReqVo.matCode" placeholder="物料编码" class="!w-240px" :disabled="!chkboxEnable" />
        </el-form-item>
        <el-form-item label=" 物料名称：" label-width="150px">
          <el-input v-model="queryReqVo.matName" placeholder="物料名称" class="!w-240px" :disabled="!chkboxEnable" />
        </el-form-item>
        <el-form-item label="规格/型号">
          <el-input v-model="queryReqVo.matSpec" placeholder="规格/型号" class="!w-240px" :disabled="!chkboxEnable" />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary" :disabled="!chkboxEnable">
            <Icon icon="ep:search" class="mr-5px" /> 搜索
          </el-button><el-button @click="resetQuery" :disabled="!chkboxEnable">
            <Icon icon="ep:refresh" class="mr-5px" /> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <el-card class="hl-table">
      <el-table ref="multipleTable" :data="list" v-loading="formLoading" class="hl-table" @selection-change="handleSelectionChange" :row-key="getRowKeys" min-width="1800" @row-click="clickRow">
        <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="row=>chkboxEnable" />
        <!-- <el-table-column prop="no" label="序号" min-width="120" align="center" /> -->
        <el-table-column label="序号" type="index" min-width="120" align="center" />
        <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="rgName" label="库区" min-width="120" align="center" v-if="formType !='in'">
          <template #default="scope">
            {{scope.row.num>1&&formType=='group'? '':scope.row.rgName}}
          </template>
        </el-table-column>
        <el-table-column prop="pnName" label="库位" min-width="140" align="center"  v-if="formType !='in'">
          <template #default="scope">
            {{scope.row.num>1&&formType=='group'? '':scope.row.pnName}}
          </template>
        </el-table-column>
        <el-table-column prop="storageOkQty" label="库存数量" min-width="120" align="center" v-if="formType=='out'"/>
        <el-table-column prop="matRest" label="库存数量" min-width="120" align="center" v-if="formType!='out'"/>
        <el-table-column prop="matUnit" label="库存单位" min-width="120" align="center" />
      </el-table>
      <!-- 分页 -->
      <Pagination :total="total" v-model:page="queryReqVo.pageNo" v-model:limit="queryReqVo.pageSize" @pagination="getList()" />
    </el-card>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as StorageLogApi from '@/api/heli/storagelog'
import * as ProcessBomApi from '@/api/heli/processbom'
import { ElTable } from 'element-plus'
import {formatDate} from "@/utils/formatTime";

//:selectable="row=>row.disabled || chkboxEnable"
const chkboxEnable = ref(true)
const queryEnable = ref(true)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数

const multipleTable = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
const handleSelectionChange = (val: []) => {
  multipleSelection.value = val
}

const clickRow = (row: any) => {
  if (chkboxEnable.value) {
    if (row) {
      multipleTable.value!.toggleRowSelection(row, undefined)
    } else {
      multipleTable.value!.clearSelection()
    }
  }
}
//指定key值,数据更新之后保留之前选中的数据
const getRowKeys = (row) => {
  return row.matId
}

const queryReqVo: any = reactive({
  pageNo: 1,
  pageSize: 10,
  whId: undefined,
  matCode: undefined,
  matSpec: undefined
})
/** 搜索按钮操作 */
const handleQuery = async () => {
  queryReqVo.pageNo = 1
  getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryReqVo.matCode = ''
  queryReqVo.matSpec = ''
  queryReqVo.matName = ''
  handleQuery()
}

const getList = async () => {
  formLoading.value = true
  var data;
  var dataone;
  try {
    if(formType.value  == 'out'){
      data = await StorageLogApi.getStorageNowAllPage(queryReqVo)
    }else  if(formType.value  == 'in'){
      data = await StorageLogApi.getStorageNowMaterialGroupPage(queryReqVo)
    }else  if(formType.value  == 'group'){
      data = await StorageLogApi.getStorageNowMaterialGroupPage(queryReqVo)
      data.list.forEach(mat =>{
        mat.storageOkQty = mat.matRest
        mat.requireAmount = mat.matRest

      })
    }else  if(formType.value  == 'bomfind'){
      dataone = await ProcessBomApi.getProcessBomDetailListByBomIdbyid(queryReqVo.whId.projectNo)
	   dataone = dataone.filter(item => item.whId === queryReqVo.whId.whId);
	      // 将过滤后的数据赋值给datatow
    }
	if(dataone){
		list.value = dataone.map(item => ({
		  ...item,
		  matCode: item.materialCode,
		  matName: item.materialName,
		   matSpec:item.spec,
		   storageOkQty:item.amount,
		   matUnit:item.unit,/// 如果你想要删除原来的 aa 属性
		     matType: item.type == 1 ? '标准件' : item.type == 2 ? '其他' : item.type,
			rgId:item.rgId,
			pnId:item.pnId,
			rgName:item.rgName,
			pnName:item.pnName,
			whId1:item.whId,
			matId:item.id,
			materialId:item.id
		}))
		total.value = dataone.length
	}
	if(data){
		list.value = data.list
		total.value = data.total
	}
    //list.value = data.splice((queryReqVo.pageNo - 1) * queryReqVo.pageSize, queryReqVo.pageSize)

  } finally {
    formLoading.value = false
  }
}
const formType = ref()
/** 打开弹窗 */
const open = async (whId: number,type:string) => {
  multipleSelection.value = []
  dialogVisible.value = true
  dialogTitle.value = '物料列表'

  formType.value = type
  // 修改时，设置数据

  queryReqVo.whId = whId
  queryReqVo.matCode = ''
  queryReqVo.matSpec = ''

  getList()
  chkboxEnable.value =  true

  list.value.forEach((row) => {
    setTimeout(() => {
      multipleTable.value.toggleRowSelection(row, !chkboxEnable.value) //让页面显示选中的数据
    }, 0)
  })
  try {
    // 获取物料库存实时列表
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    dialogVisible.value = false
    multipleSelection.value.forEach((item) => {
	if (item.amount) {
	    item.matRest = item.amount;
	} else {
	    item.matRest = item.storageOkQty;
	}
		if(item.whId1){
			item.matId = item.materialId
		}else{
			item.matId = item.id
		}
      item.storageOkQty = ''
      item.whId= item.whId??''
      item.rgId= item.rgId??''
      item.pnId= item.pnId??''
    })
    console.log(multipleSelection.value)
    // 发送操作成功的事件
    emit('success', multipleSelection.value)
  } finally {
    formLoading.value = false
  }
}
</script>
