<template>
  <!-- 表单弹窗：添加/修改 -->
  <!-- 供应商发货申请 -->
  <BasicForm
    ref="formRef"
    :isOpenSearchTable="true"
    fieldTableColumn="poNumber"
    @success="getList"
    :rules="SupplierdeliverRequestMainRules"
    :formAllSchemas="SupplierdeliverRequestMain.allSchemas"
    :tableAllSchemas="SupplierdeliverRequestDetail.allSchemas"
    :tableFormRules="SupplierdeliverRequestDetailRules"
    :tableData="tableData"
    :apiUpdate="SupplierdeliverRequestMainApi.updateSupplierdeliverRequestMain"
    :apiCreate="SupplierdeliverRequestMainApi.createSupplierdeliverRequestMain"
    :isBusiness="true"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    :isShowReduceButtonSelection="true"
    @tableSelectionDelete="tableSelectionDelete"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
    @formFormDateChange="formFormDateChange"
    @inputNumberChange="inputNumberChange"
    @onEnter="onEnter"
  >

  <template  v-slot="{row}">
    <el-date-picker v-bind:modelValue="row['expireTime']?addDay(row['produceDate'],row['expireTime']).format('YYYY-MM-DD'):'2099-12-31'"
    :clearable="true"
    style="width: 100%"
    :disabled="true" 
    :placeholder="t('ts.选择日期')"/>
    </template>
  </BasicForm>
</template>
<script setup lang="ts">
import {
  SupplierdeliverRequestMain,
  SupplierdeliverRequestMainRules,
  SupplierdeliverRequestDetail,
  SupplierdeliverRequestDetailRules,
} from './supplierdeliverRequestMain.data'
import dayjs from 'dayjs'
import { Supplier } from '@/views/wms/basicDataManage/supplierManage/supplier/supplier.data'
import * as SupplierdeliverRequestMainApi from '@/api/wms/supplierdeliverRequestMain'
import * as PurchasePlanDetailApi from '@/api/wms/purchasePlanDetail'
import * as SupplierApi from '@/api/wms/supplier'
import * as ItembasicApi from '@/api/wms/itembasic'
import { addDay } from '@/utils/formatTime'
import { PurchasePlanDetail } from '../purchasePlanMain/purchasePlanMain.data'
import { formatDate } from '@/utils/formatTime'

const emit = defineEmits(['getList'])
const getList = () =>{
    emit('getList')
}
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const planArriveTimeStr = ref()
//添加/修改操作
const formRef = ref()
const tableData = ref([])
const tableFormKeys = {}
SupplierdeliverRequestDetail.allSchemas.tableFormColumns.forEach((item) => {
  tableFormKeys[item.field] = item.default ? item.default : ''
})
// 添加明细
const handleAddTable = () => {
  tableData.value.push(JSON.parse(JSON.stringify(tableFormKeys)))
}
// 删除明细
// 删除明细
const handleDeleteTable = (item, index) => {
  let itemIndex = tableData.value.indexOf(item)
  if(itemIndex>-1){
    tableData.value.splice(itemIndex, 1)
  }
}
const tableSelectionDelete = (selection) => {
  tableData.value = tableData.value.filter(item => !selection.includes(item))
}

const openFormByCreate = async ( data ) => {
    SupplierdeliverRequestMain.allSchemas.formSchema.forEach((item) => {
      if(item.field == 'supplierCode'){
        item.componentProps.isSearchList = true
      }
      if(item.field == 'ppNumber'){
        item.componentProps.isSearchList = true
      }
      if(item.field == 'asnNumber'){
        item.componentProps.disabled = false
      }
      // if(item.field == 'planArriveTime'){
      //   item.componentProps.disabled = false
      // }
    })
    const setV = {}
    // 供应商代码回显
    setV['supplierCode'] = data['supplierCode'] // 供应商代码
    setV['poNumber'] = data['poNumber'] //采购订单
    setV['ppNumber'] = data['number'] // 要货单号
    searchPage: SupplierApi.getSupplierPage
    //新增--选择完要货计划，自动展示明细
    getSearchTableData(data['number'],'ppNumber','number')

    // 设置计划到货时间
    let beginTime =  data['endTime']
    if(data['deliveryDate']){
      let deliveryDate =  formatDate(data['deliveryDate'],'YYYY-MM-DD')
      planArriveTimeStr.value = deliveryDate + ' '+ beginTime+":00"
      setV['planArriveTime']= new Date(planArriveTimeStr.value).valueOf();
      setV['arriveTime']= new Date(planArriveTimeStr.value).valueOf();
    }
    formRef.value.open('create', null)

    // 根据供应商代码获取联系人信息
    const {tableObject ,tableMethods} = useTable({
        defaultParams:{code:data['supplierCode']},
        getListApi: SupplierApi.getSupplierPage // 分页接口
    })
    tableObject.pageSize = 500
    const { getList } = tableMethods
    await getList()
    if(tableObject.tableList.length>0){
        setV['contactName'] = tableObject.tableList[0]['contacts'] //联系人 
        setV['contactPhone'] = tableObject.tableList[0]['phone'] //联系邮件
        setV['contactEmail'] = tableObject.tableList[0]['email'] //联系电话
    }
    nextTick(() => {
        console.log('formRef.value.formRef',formRef.value.formRef)
        formRef.value.formRef.setValues(setV)
    })
}
const openForm = async (type: string, row?: number, defaultSupplierCode?: string) => {
  if(type == "update"){
    SupplierdeliverRequestMain.allSchemas.formSchema.forEach((item) => {
      if(item.field == 'supplierCode'){
        item.componentProps.isSearchList = false
        item.componentProps.disabled = true
      }
      if(item.field == 'ppNumber'){
        item.componentProps.isSearchList = false
        item.componentProps.disabled = true
      }
      if(item.field == 'asnNumber'){
        item.componentProps.disabled = true
      }
      // if(item.field == 'planArriveTime'){
      //   item.componentProps.disabled = true
      // }
    })
  }else {
    SupplierdeliverRequestMain.allSchemas.formSchema.forEach((item) => {
      if(item.field == 'supplierCode'){
        item.componentProps.isSearchList = true
        item.value = defaultSupplierCode
      }
      if(item.field == 'ppNumber'){
        item.componentProps.isSearchList = true
      }
      if(item.field == 'asnNumber'){
        item.componentProps.disabled = false
      }
      // if(item.field == 'planArriveTime'){
      //   item.componentProps.disabled = false
      // }
    })
  }
  tableData.value = [] // 重置明细数据
  formRef.value.open(type, row)
}
// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef, type, row) => {
  nextTick(() => {
    console.log("type:",type)
    console.log("formField:",formField)
    console.log(formField, searchField, val, formRef, type, row)
    
    if (type == 'tableForm') {
      // 明细查询页赋值
      // row[formField] = val[0][searchField]
      // if (formField == 'poNumber') {
      //   row['poNumber'] = val[0]['poNumber']
      //   row['itemCode'] = val[0]['itemCode']
      //   row['poLine'] = val[0]['poLine']
      //   row['orderQty'] = val[0]['orderQty']
      //   row['uom'] = val[0]['uom']
      // }
      //添加费用明细--点击确定
      const itemCodes = []
      val.forEach(item=>{
        const newRow = {...row}
        newRow.id = dayjs().valueOf()
        newRow[formField] = item[searchField]
        newRow['allowOverShipment'] = item['allowOverShipment'] // 是否允许超发
        newRow['poNumber'] = item['poNumber']
        newRow['itemCode'] = item['itemCode']
        newRow['poLine'] = item['poLine']
        newRow['orderQty'] = item['orderQty']
        newRow['uom'] = item['uom']
        newRow['id'] = item['id']
        newRow['planQty'] = item['planQty']
        newRow['shippedQty'] = item['shippedQty']
        newRow['qty'] = item['planQty'] - item['shippedQty']
        newRow['produceDate'] = dayjs().valueOf() // 是否允许超发
        let produceDateStr = formatDate(newRow['produceDate'],'YYYYMMDD');
        newRow['batch'] = produceDateStr
        newRow['supplierBatch'] = produceDateStr
        newRow.expireDate =  item['expireTime']?addDay(newRow['produceDate'],item['expireTime']).valueOf():dayjs('2099-12-31').valueOf()

        // if(tableData.value.find(item1=>item1['itemCode'] == item['itemCode']&&item1['poLine'] == item['poLine']&&item1['poNumber'] == item['poNumber'])) return
        
        itemCodes.push(item['itemCode'])
        tableData.value.push(newRow)
      })
      if(itemCodes.length>0){
        //有效期
        ItembasicApi.getItembasicPage({
          code:itemCodes.join(',')
        }).then((res)=>{
          res.list.forEach((item,index)=>{
            const findItem = tableData.value.find(item1=>item1['itemCode']==item['code'])
            findItem['expireTime'] = item['expireTime']
          })
        })
      }
      
    } else {
      const setV = {}
      setV[formField] = val[0][searchField]
      if(formField == 'ppNumber'){
        //新增--选择完要货计划，自动展示明细
        
        setV['poNumber'] = val[0]['poNumber'] //采购订单
        getSearchTableData(val[0]['number'],formField,searchField)

        // 设置计划到货时间
        
        if(val[0]['deliveryDate']){
          let beginTime =  val[0]['endTime'] || '00:00'
          let deliveryDate =  formatDate(val[0]['deliveryDate'],'YYYY-MM-DD')
          planArriveTimeStr.value = deliveryDate + ' '+ beginTime+":00"
          setV['planArriveTime']= new Date(planArriveTimeStr.value).valueOf();
          setV['arriveTime']= new Date(planArriveTimeStr.value).valueOf();
        }
        // 清空子表数据
        tableData.value = []
      }
      if(formField == 'supplierCode'){
        setV['contactName'] = val[0]['contacts']
        setV['contactPhone'] = val[0]['phone']
        setV['contactEmail'] = val[0]['email']
      }
      formRef.setValues(setV)
    }
  })
}

const getSearchTableData = async (number,formField,searchField)=>{
  const {tableObject ,tableMethods} = useTable({
    defaultParams:{number,flag:1},
    getListApi: PurchasePlanDetailApi.getPurchasePlanDetailPage // 分页接口
  })
  tableObject.pageSize = 500
  // 获得表格的各种操作
  const { getList:getList1 } = tableMethods
  await getList1()
  const tableColumns = PurchasePlanDetail.allSchemas.tableFormColumns
  tableColumns.forEach((item) => {
    item.width = item.table?.width || 150
  })
  tableData.value = []
  const itemCodes = []
  tableObject.tableList.forEach(row=>{
    const newRow = JSON.parse(JSON.stringify({...tableFormKeys,...row}))
    newRow[formField] = row[searchField]
    newRow['allowOverShipment'] = row['allowOverShipment'] // 是否允许超发
    newRow['poNumber'] = row['poNumber']
    newRow['itemCode'] = row['itemCode']
    newRow['poLine'] = row['poLine']
    newRow['orderQty'] = row['orderQty']
    newRow['uom'] = row['uom']
    newRow['planQty'] = row['planQty']
    newRow['shippedQty'] = row['shippedQty']
    newRow['qty'] = row['planQty'] - row['shippedQty']
    newRow['produceDate'] = dayjs().valueOf() // 是否允许超发
    let produceDateStr = formatDate(newRow['produceDate'],'YYYYMMDD');
    newRow['batch'] = produceDateStr
    newRow['supplierBatch'] = produceDateStr
    newRow.expireDate =  row['expireTime']?addDay(newRow['produceDate'],row['expireTime']).valueOf():dayjs('2099-12-31').valueOf()

    tableData.value.push(newRow)
    itemCodes.push(row['itemCode'])
  })

  //有效期
  ItembasicApi.getItembasicPage({
    code:itemCodes.join(',')
  }).then((res)=>{
    res.list.forEach((item,index)=>{
      const findItem = tableData.value.find(item1=>item1['itemCode']==item['code'])
      if(findItem){
        findItem['expireTime'] = findItem['expireTime']
      }
    })
  })
}


// 主子数据 提交
const submitForm = async (formType, submitData) => {
  let data = {...submitData}
  if(data.masterId){
    data.id = data.masterId
  }
  data.subList = tableData.value // 拼接子表数据参数
  let isHave = data.subList.some((item) => {
    console.log("CCCCC",item.expireDate)
    if(item.expireDate != null){
      item.produceDate > item.expireDate
    }
  })
  if (isHave) {
    message.error(t('ts.生产日期不可以大于过期日期'))
    formRef.value.formLoading = false
    return
  }
  // 2.2. 如果物料不允许超发，申请发货数量不能大于 计划数量 - 已发货数量
  let itemCodes = []				
  let itemCodeSum = []				
  data.subList.forEach(item=>{
    if(item['allowOverShipment']!='TRUE'){
      let qtyDefault = item['planQty'] - item['shippedQty']
      if(item['qty']>qtyDefault){
        itemCodes.push(item['itemCode'])
      }

      if(!itemCodeSum.includes(item['itemCode'])){
        let planQty = item['planQty'] //计划数量
        let sumQty = data.subList.filter(item1=>item1['itemCode']==item['itemCode']).reduce((prev, item1) => prev + item1['qty'],0)
        if(sumQty>planQty){
          itemCodeSum.push(item['itemCode'])
        }
      }
    }
  })
  if(itemCodes.length>0){
    message.error(`${itemCodes.join(',')}${t('ts.不允许超发')}`)
    return
  }
  if(itemCodeSum.length>0){
    message.error(`${itemCodeSum.join(',')}${t('ts.总数量超出计划数量')}`)
    return
  }
  try {
    if (formType === 'create') {
      let planArriveStr = formatDate(data.planArriveTime);
      if(planArriveStr > planArriveTimeStr.value){
        let confirmFlag = false;
        await message.confirm(`${t('ts.计划到货时间大于')}${planArriveTimeStr.value}${t('ts.是否继续？')}`).then(() => {
          console.log("选择了OK")
          //选择OK
        }).catch(() => {
          //选择取消
          console.log("选择了cancel")
          confirmFlag = true;
          formRef.value.formLoading = false
          return;
        })
        if(confirmFlag){
          return;
        }
      }
      if(tableData.value.length <= 0){
        message.warning(`子表明细不能为空!`)
        formRef.value.formLoading = false
        return;
      }
      await SupplierdeliverRequestMainApi.createSupplierdeliverRequestMain(data)
      message.success(t('common.createSuccess'))
    } else {
      await SupplierdeliverRequestMainApi.updateSupplierdeliverRequestMain(data)
      message.success(t('common.updateSuccess'))
    }
    formRef.value.dialogVisible = false
    // 刷新当前列表
    getList()
  } finally {
    formRef.value.formLoading = false
  }
}


const inputNumberChange = (field, val,row, index) => {
  if(field=='qty'){
    if(row['allowOverShipment']!='TRUE'){
      let qtyDefault = row['planQty'] - row['shippedQty']
      if(row['qty']>qtyDefault){
        message.error(`${row['itemCode']}${t('ts.不允许超发')}`)
      }
      let planQty = row['planQty'] //计划数量
      let sumQty = tableData.value.filter(item1=>item1['itemCode']==row['itemCode']).reduce((prev, item1) => prev + item1['qty'],0)
      if(sumQty>planQty){
        message.error(`${row['itemCode']}${t('ts.总数量超出计划数量')}`)
      }
    }
  }
  console.log('inputNumberChange',field, val,row, index)
}
const formFormDateChange = (field, val,row, index) => {
  console.log('formFormDateChange',field, val,row, index)
  if(field == 'produceDate'){
    let produceDateStr = formatDate(val,'YYYYMMDD');
    row.batch = produceDateStr
    row.supplierBatch = produceDateStr
    row.expireDate =  row['expireTime']?addDay(row['produceDate'],row['expireTime']).valueOf():dayjs('2099-12-31').valueOf()
  }
}
//供应商代码 回车搜索
const onEnter = async (field,value)=>{
  console.log(field,value)
  formRef.value.opensearchTable('supplierCode', 'code', '供应商信息', Supplier.allSchemas, SupplierApi.getSupplierPage,[{
    key:'code',
    value:value
  }])
}
defineExpose({ openForm , openFormByCreate}) // 提供 open 方法，用于打开弹窗

</script>
<style lang="scss" scoped></style>