<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"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
    @formFormDateChange="formFormDateChange"
    @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="选择日期"/>
    </template>
  </BasicForm>
</template>
<script setup lang="ts">
import {
  SupplierdeliverRequestMain,
  SupplierdeliverRequestMainRules,
  SupplierdeliverRequestDetail,
  SupplierdeliverRequestDetailRules,
} from './supplierdeliverRequestMain.data'
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) => {
  tableData.value.splice(index, 1)
}

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['ppNumber'] = data['number'] // 要货单号
    searchPage: SupplierApi.getSupplierPage
    //新增--选择完要货计划，自动展示明细
    getSearchTableData(data['number'],'ppNumber','number')

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

    // 根据供应商代码获取联系人信息
    const {tableObject ,tableMethods} = useTable({
        defaultParams:{code:data['supplierCode']},
        getListApi: SupplierApi.getSupplierPage // 分页接口
    })
    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) => {
  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
      }
      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[formField] = item[searchField]
        newRow['poNumber'] = item['poNumber']
        newRow['itemCode'] = item['itemCode']
        newRow['poLine'] = item['poLine']
        newRow['orderQty'] = item['orderQty']
        newRow['uom'] = item['uom']
        itemCodes.push(item['itemCode'])
        tableData.value.push(newRow)
      })
      //有效期
      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'){
        //新增--选择完要货计划，自动展示明细
        getSearchTableData(val[0]['number'],formField,searchField)

        // 设置计划到货时间
        let beginTime =  val[0]['endTime']
        let deliveryDate =  formatDate(val[0]['deliveryDate'],'YYYY-MM-DD')
        planArriveTimeStr.value = deliveryDate + ' '+ beginTime+":00"
        setV['planArriveTime']= 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},
    getListApi: PurchasePlanDetailApi.getPurchasePlanDetailPage // 分页接口
  })
  // 获得表格的各种操作
  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['poNumber'] = row['poNumber']
    newRow['itemCode'] = row['itemCode']
    newRow['poLine'] = row['poLine']
    newRow['orderQty'] = row['orderQty']
    newRow['uom'] = row['uom']
    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'])
      findItem['expireTime'] = findItem['expireTime']

    })
  })
}


// 主子数据 提交
const submitForm = async (formType, data) => {
  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
  }
  try {
    if (formType === 'create') {
      let planArriveStr = formatDate(data.planArriveTime);
      if(planArriveStr > planArriveTimeStr.value){
        let confirmFlag = false;
        await message.confirm(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 formFormDateChange = (field, val,row, index) => {
  if(field == 'produceDate'){
    let produceDateStr = formatDate(val,'YYYYMMDD');
    row.batch = produceDateStr
    row.supplierBatch = produceDateStr
  }
}
//供应商代码 回车搜索
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>