<template>
  <ContentWrap v-if="visibleSearch">
    <!-- 搜索工作栏 -->
    <Search ref="seachRef" :schema="[...PurchasePlanMain.allSchemas.searchSchema,...PurchasePlanDetail.allSchemas.searchSchema]" :formClassNames="['dateSearch']" @search="searchList" @reset="searchList" @searchTableSuccess="searchQueryTableSuccess" @onChange="onSearchChange" @foldUpClick="foldUpClick"/>
  </ContentWrap>

  <!-- 列表头部 -->
  <TableHead :HeadButttondata="HeadButttondata" @button-base-click="buttonBaseClick" :routeName="routeName"
    @updataTableColumns="updataTableColumns" @searchFormClick="searchFormClick"
    :allSchemas="PurchasePlanMain.allSchemas" :detailAllSchemas="PurchasePlanDetail.allSchemas">
    <template #rightBtn_left>
      <div style="display:flex;justify-content: center;align-items: center">
        <span style="color:var(--el-text-color-regular)">计划数量包含0</span>
        <el-switch v-model="isZero" style="margin:0 5px" @change="zeroChange"/>
      </div>
    </template>
    <template #rightBtn_right>
      <el-tooltip
        effect="dark"
        content="查询条件"
        placement="top-start"
      >
      <el-button @click="foldUpClick ">
            <Icon :icon="visibleSearch ? 'ep:arrow-up' : 'ep:arrow-down'" />
          </el-button>
      </el-tooltip>
    </template>
  </TableHead>

  <!-- 列表 -->
  <ContentWrap>
    <Table ref="tableRef" v-clientTable 
    :selection="false"
    :columns="tableColumns" 
    :data="tableObject.tableList" 
    :loading="tableObject.loading" 
    :pagination="{
        total: tableObject.total
      }" 
      v-model:pageSize="tableObject.pageSize" v-model:currentPage="tableObject.currentPage"
      v-model:sort="tableObject.sort"
      @getSelectionRows="getSelectionRows">
      <template #number="{row}">
        <el-button type="primary" link @click="openDetail(row, '供应商代码', row.number)">
          <span>{{ row.number }}</span>
        </el-button>
      </template>
      <template #action="{ row,$index }">
        <ButtonBase :Butttondata="butttondata(row,$index)" @button-base-click="buttonTableClick($event,row)" />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BasicForm ref="formRef" @success="getList" 
    :isOpenSearchTable="true"
    fieldTableColumn="poLine"    
    :rules="PurchasePlanMainRules"
    :formAllSchemas="PurchasePlanMain.allSchemas" 
    :tableAllSchemas="PurchasePlanDetail.allSchemas"
    :tableFormRules="PurchasePlanDetailRules" 
    :tableData="showTableData"
    :apiUpdate="PurchasePlanMainApi.updatePurchasePlanMain" 
    :apiCreate="PurchasePlanMainApi.createPurchasePlanMain"
    :isBusiness="true" 
    :isShowReduceButtonSelection="false" 
    :isShowReduceButton="false" 
    :isShowButton="false"
    @handleAddTable="handleAddTable" 
    @clearSearchInput="clearSearchInput"
    @handleDeleteTable="handleDeleteTable"
    @tableSelectionDelete="tableSelectionDelete"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm" 
    @onEnter="onEnter"
    @onBlur="onEnter">
  
    <template #TableFormHead>
     <div style="border-top:1px solid #ebeef5;padding:10px 10px 0 10px ;margin-right:10px">
      <el-form :inline="true" :model="tableDataSearch">
        <el-form-item label="筛选：   品番">
          <el-input v-model="tableDataSearch.itemCode" placeholder="请输入品番" clearable @change="changeTableDataSearch"/>
        </el-form-item>
        <el-form-item label="背番">
          <el-input v-model="tableDataSearch.backNumber" placeholder="请输入品番" clearable @change="changeTableDataSearch"/>
        </el-form-item>
      </el-form>
     </div>
    </template>
  </BasicForm>

  <!-- 详情 -->
  <!-- 隐藏子表编辑和删除是因为要货计划以后是接口发过来的，而且我们的计划数量是放入到采购订单已计划数量里，无法再次编辑数量-->
  <Detail
    ref="detailRef"
    :isBasic="false"
    :allSchemas="PurchasePlanMain.allSchemas"
    :detailAllSchemas="PurchasePlanDetail.allSchemas"
    :detailAllSchemasRules="PurchasePlanDetailRules"
    :apiCreate="PurchasePlanDetailApi.createPurchasePlanDetail"
    :apiPage="PurchasePlanDetailApi.getPurchasePlanDetailPage"
    :apiDelete="PurchasePlanDetailApi.deletePurchasePlanDetail"
    @searchTableSuccessDetail="searchTableSuccessDetail"
    :detailValidate="detailValidate" 
    :detailButtonIsShowAddStatusArray="['1','3','4','5','6']"
    :detailButtonIsShowEdit="detailData.type == 'SCHEDULE'&& detailData.status  != 4"
    :detailButtonIsShowDelete="detailData.type == 'SCHEDULE'&& detailData.status  != 4"
    :detailButtonIsShowAdd="false"
    addHasPermi="wms:purchase-plan-main:create"
    editHasPermi="wms:purchase-plan-main:update"
    deleteHasPermi="wms:purchase-plan-main:delete"
    :isOpenSearchTable="true"
    :mainSubmitCreateApi="true"
    fieldTableColumn="poLine"
    @detailOpenForm="detailOpenForm"
    @handleSubmitForm="handleDetailSubmitForm"

  />
  <!-- 导入 -->
  <ImportFormPlanCSV ref="importFormRef" url="/wms/purchase-plan-main/importCSV" :importTemplateData="importTemplateData" :announcements = "announcements"
    @success="importSuccess" :updateIsDisable="false" :appendIsDisable="true" :coverIsDisable="true" :mode="1" :coverIsShow="false" :appendIsShow="false"/>
  <!-- 创建供应商发货申请 -->
  <supplierdeliverBasicForm ref="supplierdeliverFormRef" @getList="getList" ></supplierdeliverBasicForm>
</template>

<script setup lang="ts">
  import download from '@/utils/download'
  import { PurchasePlanMain, PurchasePlanMainRules, PurchasePlanDetail, PurchasePlanDetailRules } from './purchasePlanMain.data'
  import * as PurchasePlanMainApi from '@/api/wms/purchasePlanMain'
  import * as PurchasePlanDetailApi from '@/api/wms/purchasePlanDetail'
  import * as defaultButtons from '@/utils/disposition/defaultButtons'
  import * as PurchaseDetailApi from '@/api/wms/purchaseDetail'
  import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  import { PurchaseDetail } from '../purchaseMain/purchaseMain.data'
  import dayjs from 'dayjs'
  import supplierdeliverBasicForm from '../supplierdeliverRequestMain/supplierdeliverBasicForm.vue'
  import * as PurchaseMainApi from '@/api/wms/purchaseMain'
  import { PurchaseMain } from '../purchaseMain/purchaseMain.data'
  import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const { loadStart, loadDone } = usePageLoading()
  const { wsCache } = useCache()
  const language = wsCache.get('lang')
  const announcements  = ref<any>([])
  if('en-US'==language){
    announcements.value = ["1. The total number of data items of the quantity of goods in the template does not exceed 1000 data (row × column).","2. All data content in the template is in text format, and formula content cannot be used as import data","3. The delivery date is in YYYY-MM-DD format, no hours, minutes and seconds are required"]

  }else{
    //announcements.value = ["1. 模板中要货数量数据项总数不超过1000个数据（行×列）","2. 模板中全部数据内容格式为文本格式，不能使用公式内容作为导入数据","3. 要货日期为YYYY-MM-DD格式，不需填写时分秒"]
  }
  // 要货计划
  defineOptions({ name: 'PurchasePlanMain' })

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

  const route = useRoute() // 路由信息
  const routeName = ref()
  routeName.value = route.name
  const tableColumns = ref([...PurchasePlanMain.allSchemas.tableColumns,...PurchasePlanDetail.allSchemas.tableMainColumns])

  // 字段设置 更新主列表字段
  const updataTableColumns = (val) => {
    tableColumns.value = val
  }
  const seachRef = ref()
  const onSearchChange = (field, value)=>{
    if(field=='status'){
      if(value.length>0){
        if(value[value.length-1]==''){
          //全选
          seachRef.value.setFormValues({
            status:['']
          })
        }else{
          seachRef.value.setFormValues({
            status:value.filter(item=>item!='')
          })
        }
      }
    }
  }
  const searchQueryTableSuccess = (formField, searchField, val, formRef, type, row ) => {
    console.log('searchQueryTableSuccess',formField, searchField, val, formRef, type, row )
    nextTick(() => {
      const setV = {}
      setV[formField] = val[0][searchField]
      formRef.setValues(setV)
    })
  }
  // 为了折叠
  const visibleSearch = ref(false)
  const updateTable = ref(true)
  const foldUpClick = ()=>{
    visibleSearch.value = !visibleSearch.value
    // let tableList = tableObject.tableList
    // tableObject.tableList = []
    // updateTable.value = !updateTable.value
    tableObject.loading = true
    let timer = setTimeout(() => {
      tableObject.loading = false
      // tableObject.tableList = tableList
      // updateTable.value = !updateTable.value
      if(timer){
        clearTimeout(timer)
        timer = null
      }
    }, 500);
  }
  // 查询页面返回
  const searchTableSuccess = (formField, searchField, val, formRef, type, row) => {
    console.log('searchTableSuccess', formField, searchField, val, formRef, type, row)
    nextTick(async () => {
      if (type == 'tableForm') {
        // 明细查询页赋值
        val.forEach(item=>{
          if(tableData.value.find(item1=>item1['id'] == item['id'])) return
          const newRow = JSON.parse(JSON.stringify({...tableFormKeys,...row}))

          newRow[formField] = item[searchField]
          newRow['itemCode'] = item['code']
          newRow['poNumber'] = item['number']
          newRow['poLine'] = item['lineNumber']
          newRow['id'] = item['id']
          if (formField == 'poLine') {
            //添加费用明细--点击确定
            newRow['itemCode'] = item['itemCode']
            newRow['uom'] = item['uom']
            newRow['orderQty'] = item['orderQty']
            newRow['planQty'] = item['orderQty']-item['plannedQty']
            newRow['available'] = item['available']
            console.log('tableData.value',tableData.value)
            console.log('item',item)
            if(!tableData.value.find(tableItem=>tableItem['itemCode']==item['itemCode']&&tableItem['poNumber']==item['number']&&tableItem['poLine']==item['lineNumber'])){
              tableData.value.push(newRow)
            }
          }else{
            tableData.value.push(newRow)
          }
          
        })
      } else {
        const setV = {}
        setV[formField] = val[0][searchField]
        setV['itemCode'] = val[0]['code']
        setV['poNumber'] = val[0]['number']
        setV['poLine'] = val[0]['lineNumber']
        setV['receivedNumber'] = val[0]['receivedNumber']
        console.log(PurchasePlanDetail.allSchemas.tableFormColumns);
        
        PurchasePlanDetail.allSchemas.tableFormColumns.forEach(item =>{
        if(item.value == ''){
          if(item.field == 'receivedNumber'){
            item.tableForm.placeholder = ''
          }
        }
      })
        
        if(formField == 'supplierCode'){
          setV['supplierCode'] = val[0]['code']
          // await PurchasePlanMainApi.queryPurchasePlan(val[0]['code']).then(res => {
            
          //   // let beginTime = res.beginTime
          //   // var ms = beginTime.substring(0, 2)
		      //   // var me = beginTime.substring(3)
          //   // setV['beginTime'] = new Date(2024, 1, 1, Number(ms), Number(me))
          //   // let endTime = res.endTime
          //   // var ms = endTime.substring(0, 2)
		      //   // var me = endTime.substring(3)
          //   // setV['endTime'] = new Date(2024, 1, 1, Number(ms), Number(me))
          //   setV['timeWindow'] = res.timeWindow
          //   setV['beginTime'] = res.beginTime
          //   setV['endTime'] = res.endTime
          //   setV['contacts'] = res.contacts
          //   setV['phone'] = res.phone
          // })
          clearTableDataSearch()
        }
        if (formField == 'poLine') {
          setV['itemCode'] = val[0]['itemCode']
          setV['uom'] = val[0]['uom']
          setV['orderQty'] = val[0]['orderQty']
          setV['planQty'] = val[0]['orderQty']-val[0]['plannedQty']
          setV['available'] = val[0]['available']
        }
        if(formField == 'poNumber') {
          //订单类型
          setV['type'] = val[0]['type']
        }
        formRef.setValues(setV)
        console.log('formModel',formRef.formModel)
        if(formField == 'poNumber') {
          //新增--采购订单--
          // 请求明细数据
          await getSearchTableData(val[0]['number'], formField, searchField)
          await PurchasePlanMainApi.queryPurchasePlan(formRef.formModel.supplierCode,tableData.value[0]['itemCode']).then(res => {
            
            // let beginTime = res.beginTime
            // var ms = beginTime.substring(0, 2)
		        // var me = beginTime.substring(3)
            // setV['beginTime'] = new Date(2024, 1, 1, Number(ms), Number(me))
            // let endTime = res.endTime
            // var ms = endTime.substring(0, 2)
		        // var me = endTime.substring(3)
            // setV['endTime'] = new Date(2024, 1, 1, Number(ms), Number(me))
            setV['timeWindow'] = res.timeWindow
            setV['beginTime'] = res.beginTime
            setV['endTime'] = res.endTime
            setV['contacts'] = res.contacts
            setV['phone'] = res.phone
          })
        }
      }
    })
  }

const getSearchTableData = async (number,formField,searchField)=>{
  const {tableObject ,tableMethods} = useTable({
    defaultParams:{number,available:'TRUE'},
    getListApi: PurchaseDetailApi.getPurchaseDetailPagePoNumber // 分页接口
  })
  tableObject.pageSize = 500
  // 获得表格的各种操作
  const { getList:getList1 } = tableMethods
  await getList1()
  const tableColumns = PurchaseDetail.allSchemas.tableFormColumns
  tableColumns.forEach((item) => {
    item.width = item.table?.width || 150
  })
  tableData.value = []
  tableObject.tableList.forEach(row=>{
    const newRow = JSON.parse(JSON.stringify({...tableFormKeys,...row}))
    // 明细查询页赋值
    newRow[formField] = row[searchField]
    newRow['itemCode'] = row['itemCode']
    newRow['poNumber'] = row['number']
    newRow['poLine'] = row['lineNumber']
    newRow['planQty'] = 0 // 默认值
    if (formField == 'poLine') {
      newRow['itemCode'] = row['itemCode']
      newRow['uom'] = row['uom']
      newRow['orderQty'] = row['orderQty']
      newRow['planQty'] = row['orderQty']-row['plannedQty']
      newRow['available'] = row['available']
    }
    tableData.value.push(newRow)
  })
  // 清空筛选条件
  initTableDataSearch()
 
}
  // 查询页面返回——详情
  const searchTableSuccessDetail = (formField, searchField, val, formRef,formModel) => {
    console.log('searchTableSuccessDetail',formField, searchField, val, formRef,formModel)
    nextTick(async () => {
      if(formModel){
        console.log(formModel)
        //明细中新增
        let data = {...val[0]}
        data['planQty'] = val[0]['orderQty']
        data['poLine'] = val[0]['lineNumber']
        data['number'] = formModel['number']
        data['poNumber'] = formModel['poNumber']
        console.log('data',data)
        await PurchasePlanDetailApi.createPurchasePlanDetail(data)
        message.success(t('common.createSuccess'))
        detailRef.value.updateList()
        return
      }
      const setV = {}
      setV[formField] = val[0][searchField]
      setV['poNumber'] = val[0]['number']
      setV['poLine'] = val[0]['lineNumber']
      if (formField == 'poLine') {
        setV['itemCode'] = val[0]['itemCode']
        setV['uom'] = val[0]['uom']
        setV['orderQty'] = val[0]['orderQty']
        setV['planQty'] = val[0]['orderQty']-val[0]['plannedQty']
        setV['available'] = val[0]['available']
      }
      // await PurchaseDetailApi.getPurchaseDetailPage({
      //   number: setV['poNumber'],
      //   lineNumber: setV['poLine'],
      // }).then(res => {
      //   if (res.list.length == 1) {
      //     // 叶佳兴
      //     setV['itemCode'] = res.list[0].itemCode
      //   }
      // })
      formRef.setValues(setV)
    })
  }

  const { tableObject, tableMethods } = useTable({
    defaultParams:{isZero:1},
    getListApi: PurchasePlanDetailApi.getPurchasePlanDetailPage // 分页接口
  })

  // 获得表格的各种操作
  const { getList, setSearchParams } = tableMethods

  // 列表头部按钮
  const HeadButttondata = [
    defaultButtons.defaultAddBtn({ hasPermi: 'wms:purchase-plan-main:create' }), // 新增
    // defaultButtons.defaultImportBtn({ hasPermi: 'wms:purchase-plan-main:import' }), // 导入
    {
      label: t(`ts.导入SPARC订单`).replace('ts.', ''),
      name: 'import',
      hide: false,
      type: 'warning',
      icon: 'ep:upload',
      color: '',
      hasPermi: 'wms:purchase-plan-main:import'
    },
    // defaultButtons.defaultExportBtn({ hasPermi: 'wms:purchase-plan-main:export' }), // 导出
    defaultButtons.defaultExportDetailsBtn({ hasPermi: 'wms:purchase-plan-main:export' }), // 导出明细
    //defaultButtons.defaultExportTableBtn({ hasPermi: 'wms:purchase-plan-main:export' }), // 导出二维表
    // defaultButtons.mainListSelectionOrderPubBtn(null), // 批量发布
    defaultButtons.defaultFreshBtn(null), // 刷新
    defaultButtons.defaultFilterBtn(null), // 筛选
    defaultButtons.defaultSetBtn(null), // 设置
    
    // {
    //   label: '自定义扩展按钮',
    //   name: 'zdy',
    //   hide: false,
    //   type: 'primary',
    //   icon: 'Select',
    //   color: ''
    // },
  ]

  // 头部按钮事件
  const buttonBaseClick = (val, item) => {
    if (val == 'add') { // 新增
      openForm('create')
    } else if (val == 'import') { // 导入
      handleImport()
    } else if (val == 'export') { // 导出
      handleExport()
    } else if (val == 'export-details') { // 导出明细
      handleExportDetails()
    } else if (val == 'export-table') { // 导出二维表
      handleExportTable()
    } else if (val == 'refresh') { // 刷新
      if (tableObject.params.filters && tableObject.params.filters.length > 0 ) {
      searchFormClick({
        filters: tableObject.params.filters
      })
    } else {
      getList()
    }
    } else if (val=='mainOrderSelectionPub'){// 批量发布
      handleSelectionPublish()
    } else if (val == 'filtrate') { // 筛选
      console.log('筛选',tableObject)
    } else { // 其他按钮
      console.log('其他按钮', item)
    }
  }

  // 根据状态返回该按钮是否显示
  const isShowMainButton = (row, val) => {
   if (val.indexOf(row.status) > -1) {
    return false
  } else {
    return true
  }
}
const isShowMainButton1 = (row, val) => {
  if (row.type == 'DISCRETE') {
    return true
  } else {
    if (val.indexOf(row.status) > -1) {
      return false
    } else {
      return true
    }
   }
}

  // 列表-操作按钮
  const butttondata = (row,$index) => {
  const findIndex = row['masterId']?tableObject.tableList.findIndex(item=>item['masterId'] == row['masterId']):-1
  if(findIndex>-1&&findIndex<$index){
    return []
  }
    return [
      // defaultButtons.mainListPurchasePlanOpeBtn({ hide: isShowMainButton(row, ['2']) }), // 打开
      defaultButtons.mainListPurchasePlanCloBtn({ hide: !(row.status!=6&&row.status!=2&&row.type=='SCHEDULE'),hasPermi: 'wms:purchase-plan-main:close' }), // 关闭
      defaultButtons.mainListPurchasePlanPubBtn({ hide: isShowMainButton(row, ['1']) ,hasPermi: 'wms:purchase-plan-main:publish'}), // 发布
      defaultButtons.mainListPurchasePlanAccBtn({ hide: isShowMainButton(row, ['3']) ,hasPermi: 'wms:purchase-plan-main:accept'}), // 接受
      defaultButtons.mainListPurchasePlanRejBtn({ hide: isShowMainButton(row, ['3']) ,hasPermi: 'wms:purchase-plan-main:noaccept'}), // 不接受
      defaultButtons.mainListPurchasePlanWitBtn({ hide: isShowMainButton(row, ['3']) ,hasPermi: 'wms:purchase-plan-main:unpublish'}), // 下架
      defaultButtons.mainListPurchasePlanModBtn({ hide: isShowMainButton(row, ['5']) , hasPermi: 'wms:purchase-plan-main:update'}), // 修改
      defaultButtons.mainListEditBtn({ hide: isShowMainButton1(row, ['1','3','5']), hasPermi: 'wms:purchase-plan-main:edit' }), // 编辑
      // defaultButtons.mainListDeleteBtn({hide:isShowMainButton(row,['1']),hasPermi:'wms:purchase-plan-main:delete'}), // 删除
      {
        label: t('ts.创建发货申请'),
        name: 'supplierdeliver',
        hide: isShowMainButton(row, ['4']) || !row.isShowCreateRequestButton,
        type: 'primary',
        icon: '',
        color: '',
        hasPermi: 'wms:purchase-plan-main:supplyapply',
        link: true // 文本展现按钮
      }
    ]
  }
  const supplierdeliverFormRef = ref()

  // 列表-操作按钮事件
  const buttonTableClick = async (val, row) => {
    if (val == 'mainPurPlanOpe') { // 打开
      handleOpen(row.masterId)
    } else if (val == 'mainPurPlanClo') {// 关闭
      handleClose(row.masterId)
    } else if (val == 'mainPurPlanPub') { // 发布
      handlePublish(row.masterId)
    } else if (val == 'mainPurPlanAcc') { // 接受
      handleAcc(row.masterId)
    } else if (val == 'mainPurPlanRej') { // 不接受
      handleRej(row.masterId)
    } else if (val == 'mainPurPlanWit') { // 下架
      handleWit(row.masterId)
    } else if(val == 'mainPurPlanMod'){ // 修改
      handleReOpen(row.masterId)
    }else if (val == 'edit') { // 编辑
      openForm('update', row)
    } else if (val == 'delete') { // 删除
      handleDelete(row.masterId)
    } else if (val == 'supplierdeliver') { // 创建供应商发货申请
      supplierdeliverFormRef.value.openFormByCreate({
        number:row.number, //要货单号
        deliNo:row.deliNo, //便次
        poNumber:row.poNumber, //采购订单号
        supplierCode:row.supplierCode, //供应商代码 
        endTime:row.endTime, //结束时间
        deliveryDate:row.deliveryDate, // 送达日期
        schdShipDate:row.schdShipDate // 取货日期
      })
    }
  }

  /** 添加/修改操作 */
  const formRef = ref()
  const openForm = async (type : string, row ?: number) => {
    clearTableDataSearch()
    formRef.value.open(type, row)
    if('create'==type){
      nextTick(async () => {
        formRef.value.formRef.setValues({deliveryDate:dayjs().valueOf(),schdShipDate:dayjs().valueOf()})
      })
      PurchasePlanMain.allSchemas.formSchema.forEach((item) => {
        // 供应商代码
        if(item.field == 'supplierCode'){
          item.componentProps.disabled = false
          item.componentProps.isSearchList = true
        }
        if(item.field == 'deliveryDate'){
          item.componentProps.disabled = false
        }
        if (item.field == 'poNumber') {
        item.componentProps.isSearchList = true
        item.componentProps.disabled = false
        item.componentProps.enterSearch = true
      }
      })
    }else if('update'==type){
      PurchasePlanMain.allSchemas.formSchema.forEach((item) => {
        // 供应商代码
        if(item.field == 'supplierCode'){
          item.componentProps.disabled = true
          item.componentProps.isSearchList = false
        }
        if (item.field == 'poNumber') {
        item.componentProps.isSearchList = false
        item.componentProps.disabled = true
        item.componentProps.enterSearch = false
      }
        // if(item.field == 'deliveryDate'){
        //   item.componentProps.disabled = true
        // }
      })
    }
  }
// 获取部门 用于详情 部门回显
  /** 详情操作 */
const detailRef = ref()
const detailData = ref({})
const openDetail = (row: any, titleName: any, titleValue: any) => {
    detailData.value = row
    detailRef.value.openDetail(row, titleName, titleValue,'planPurchaseMain')
    const departmentCode = wsCache.get(CACHE_KEY.DEPT).find((account) => account.id == row.departmentCode)?.name
    if (departmentCode) row.departmentCode = JSON.parse(JSON.stringify(departmentCode))
  }
  const detailOpenForm = (type, row) => {
    
    PurchasePlanDetail.allSchemas.formSchema.forEach(item=>{
      if(item.field == 'planQty'){
        //计划数量
        item.componentProps.disabled = row.available=="FALSE"
      }
    })
  }
  const handleDetailSubmitForm = async (formType, data)=>{
    if(formType == 'update'){
      if(Number(data.planQty)<=0){
        message.error(t('ts.计划数量必须大于0'))
        return
      }
      await PurchasePlanDetailApi.updatePurchasePlanDetail(data)
      message.success(t('common.updateSuccess'))
    }
    detailRef.value.submitUpdateList()
  }
  /** 删除按钮操作 */
  const handleDelete = async (id : number) => {
    try {
      // 删除的二次确认
      await message.delConfirm()
      tableObject.loading = true
      // 发起删除
      await PurchasePlanMainApi.deletePurchasePlanMain(id)
      message.success(t('common.delSuccess'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }

  /** 关闭按钮操作 */
  const handleClose = async (id : number) => {
    try {
      // 关闭的二次确认
      await message.confirm(t('ts.是否关闭所选中数据？'))
      // 发起关闭
      await PurchasePlanMainApi.closePurchasePlanMain(id)
      message.success(t('ts.关闭成功!'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }

  /** 打开按钮操作 */
  const handleOpen = async (id : number) => {
    try {
      // 打开的二次确认
      await message.confirm(t('ts.是否打开所选中数据？'))
      tableObject.loading = true
      // 发起打开
      await PurchasePlanMainApi.openPurchasePlanMain(id)
      message.success(t('ts.打开成功!'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }


  /** 打开按钮操作 */
  const handleReOpen = async (id : number) => {
    try {
      // 打开的二次确认
      await message.confirm(t('ts.是否重新打开所选中数据？'))
      tableObject.loading = true
      // 发起打开
      await PurchasePlanMainApi.openPurchasePlanMain(id)
      message.success(t('ts.打开成功!'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }

  const isZero = ref(false)
  const zeroChange = ()=>{
    // isZero.value
    if(tableObject.params.isSearch){
      tableObject.params.filters = tableObject.params.filters.filter(item=>item.column!='isZero')
      tableObject.params.filters = [...tableObject.params.filters,{
        action: "==",
        column: "isZero",
        value: isZero.value?0:1
      }]
    }else{
      tableObject.params.isZero = isZero.value?0:1
    }
    getList()
    console.log('tableObject',tableObject)
  }
  const searchList = (model)=>{
    model.isZero = isZero.value?0:1
    console.log('model',model)
    selectionRows.value = []
    setSearchParams(model)
  }
  const selectionRows = ref<any>([])
  const tableRef = ref()
  const getSelectionRows = (currentPage,currentPageSelectionRows) => {
    console.log("getSelectionRows",currentPage,currentPageSelectionRows)
    const currentRows = selectionRows.value.find(item=>item.currentPage==currentPage)
    if(currentRows){
      currentRows.selectionRows = currentPageSelectionRows
    }else{
      selectionRows.value.push({
        currentPage,
        selectionRows:currentPageSelectionRows
      })
    }
  }
  // 批量发布
const handleSelectionPublish = async ()=>{
  // 发布的二次确认
  await message.confirm(t('ts.是否发布所选中数据？'))
  tableObject.loading = true
  let rows:any = []
  selectionRows.value.map(item=>{
    rows = [...rows,...item.selectionRows.map(item1=>item1.masterId)]
  })
  tableObject.loading = true
  Promise.all( rows.map(item=>PurchasePlanMainApi.publishPurchasePlanMain(item))).then((res) => {
    console.log('发布',res)
    if(res.every(item=>item==true)){
      message.success(t('ts.发布成功!'))
    }
  }).finally(()=>{
    tableObject.loading = false
    // 刷新列表
    getList()
  })
}
  /** 发布按钮操作 */
  const handlePublish = async (id : number) => {
    try {
      // 发布的二次确认
      await message.confirm(t('ts.是否发布所选中数据？'))
      tableObject.loading = true
      // 发起发布
      await PurchasePlanMainApi.publishPurchasePlanMain(id)
      message.success(t('ts.发布成功!'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }

  /** 下架按钮操作 */
  const handleWit = async (id : number) => {
    try {
      // 下架的二次确认
      await message.confirm(t('ts.是否下架所选中数据？'))
      tableObject.loading = true
      // 发起下架
      await PurchasePlanMainApi.witPurchasePlanMain(id)
      message.success(t('ts.下架成功!'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }

  /** 接受按钮操作 */
  const handleAcc = async (id : number) => {
    try {
      // 接受的二次确认
      await message.confirm(t('ts.是否接受所选中数据？'))
      tableObject.loading = true
      // 发起接受
      await PurchasePlanMainApi.accPurchasePlanMain(id)
      message.success(t('ts.接受成功!'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }

  /** 驳回按钮操作 */
  const handleRej = async (id : number) => {
    try {
      // 驳回的二次确认
      await message.confirm(t('ts.是否驳回所选中数据？'))
      tableObject.loading = true
      // 发起驳回
      await PurchasePlanMainApi.rejPurchasePlanMain(id)
      message.success(t('ts.驳回成功!'))
      tableObject.loading = false
      // 刷新列表
      await getList()
    } catch { }finally{
      tableObject.loading = false
    }
  }

  /** 导出按钮操作 */
  const handleExport = async () => {
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      loadStart()
      const excelTitle = ref(route.meta.title)
      const data = await PurchasePlanMainApi.exportPurchasePlanMain(tableObject.params)
      download.excel(data, `【${excelTitle.value}】【${formatDate(new Date())}】.xlsx`)
    } catch {
    } finally {
      loadDone()
    }
  }

  const handleExportDetails = async () => {
    console.log('tableObject.params',tableObject.params)
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      loadStart()
      const excelTitle = ref(route.meta.title)
      const data = await PurchasePlanMainApi.exportDetailsPurchasePlanMain(tableObject.params)
      download.excel(data, `【${excelTitle.value}明细】【${formatDate(new Date())}】.xlsx`)
    } catch {
    } finally {
      loadDone()
    }
  }
  
  const handleExportTable = async () => {
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      loadStart()
      const excelTitle = ref(route.meta.title)
      const data = await PurchasePlanMainApi.exportTablePurchasePlanMain(tableObject.params)
      download.excel(data, `【${excelTitle.value}二维表】【${formatDate(new Date())}】.xlsx`)
    } catch {
    } finally {
      loadDone()
    }
  }
  /**
    * tableForm方法
  */
  const tableFormKeys = {}
  PurchasePlanDetail.allSchemas.tableFormColumns.forEach(item => {
    tableFormKeys[item.field] = item.default ? item.default : ''
  })
  const tableData = ref([])
  const showTableData = ref([])
  const tableDataSearch = ref({
    itemCode:'',
    backNumber:''
  })
  const clearTableDataSearch = ()=>{
    tableDataSearch.value = {
      itemCode:'',
      backNumber:''
    }
    showTableData.value = []
    tableData.value = []
  }
  
  const initTableDataSearch = ()=>{
    tableDataSearch.value = {
      itemCode:'',
      backNumber:''
    }
    showTableData.value = tableData.value
  }
  
  const changeTableDataSearch = ()=>{
    let filterList = tableData.value
    if(tableDataSearch.value['itemCode']){
      filterList = tableData.value.filter(item => {
        return item['itemCode'].includes(tableDataSearch.value['itemCode'])
      })
    }
    if(tableDataSearch.value['backNumber']){
      filterList = filterList.filter(item => {
        return item['backNumber'].includes(tableDataSearch.value['backNumber'])
      })
    }
    showTableData.value = filterList
  }

  // 添加明细
  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 onEnter = async (field,value)=>{
    console.log(field,value)
    if('supplierCode'==field){
      //供应商代码
      formRef.value.opensearchTable('poNumber', 'number', '采购订单信息', PurchaseMain.allSchemas, PurchaseMainApi.getPurchaseMainPage,[{
          key: 'type',
          value: 'SCHEDULE',
          isMainValue: false
        },{
          key: 'available',
          value: 'TRUE',
          isMainValue: false
        },{
          key: 'supplierCode',
          value: 'supplierCode',
          message: '请填写供应商代码！',
          isMainValue: true
        },{
          key: 'status',
          value: 2,
          isMainValue: false
      }])
      //修改弹窗宽度
      formRef.value.changeDialogWidth('1085px')
    }
  }

  // 主子数据 提交
  const submitForm = async (formType, submitData) => {
    let data = {...submitData}
    if(data.masterId){
      data.id = data.masterId
    }
    data.subList = []
    let flag = false
    for (let item of tableData.value) {
      if(item.planQty>0){
        data.subList.push(item) // 拼接子表数据参数
      }
      // await PurchaseDetailApi.getPurchaseDetailPageCheckData({
      //   number: item.poNumber,
      //   lineNumber: item.poLine,
      // }).then(res => {
      //   console.log("【要货计划】-每条数据结果",item)
      //   if(res.list[0].type == 'DISCRETE'){//只有离散单需要这个校验
      //     if (item.planQty > res.list[0].orderQty - res.list[0].plannedQty) {
      //       flag = true;
      //       message.error(t('ts.要货计划数量不得大于订单数量-已计划数量'))
      //       return
      //     }else{
      //       data.subList.push(item) // 拼接子表数据参数
      //     }
      //   }else{
      //     data.subList.push(item) // 拼接子表数据参数
      //   }
      // })
    }
    if(flag){
      formRef.value.formLoading = false
      return;
    }
    try {
      if (formType === 'create') {
        if(data.subList.length == 0){
          message.error(t('ts.子列表数量不能空'))
          return
        }
        formRef.value.formLoading = true
        await PurchasePlanMainApi.createPurchasePlanMain(data)
        message.success(t('common.createSuccess'))
      } else {
        formRef.value.formLoading = true
        await PurchasePlanMainApi.updatePurchasePlanMain(data)
        message.success(t('common.updateSuccess'))
      }
      formRef.value.dialogVisible = false
      // 刷新当前列表
      getList()
    } finally {
      formRef.value.formLoading = false
    }
  }

  // 子表新增/编辑校验
  const detailValidate = async (data) => {
    return true
    // let tag = false
    // await PurchaseDetailApi.getPurchaseDetailPageCheckData({
    //   number: data.poNumber,
    //   lineNumber: data.poLine
    // }).then(res => {
    //   if(res.list[0].type == 'DISCRETE'){//只有离散单需要这个校验
    //     if (data.planQty > res.list[0].orderQty - res.list[0].plannedQty) {
    //       message.error(t('ts.要货计划数量不得大于订单数量-已计划数量'))
    //       tag = false
    //     } else {
    //       tag = true
    //     }
    //   }else{
    //     tag = true
    //   }
    // }).catch(err =>{
    //   console.log(err);
    // })
    // return tag
  }

  /** 导入 */
  const importFormRef = ref()
  const handleImport = () => {
    importFormRef.value.open()
  }

  // 导入附件弹窗所需的参数
  const importTemplateData = reactive({
    templateUrl: '',
    templateTitle: `【${route.meta.title}】导入模版.xlsx`
  })

  // 导入成功之后
  const importSuccess = () => {
    getList()
  }

  // 筛选提交
  const searchFormClick = (searchData) => {
    searchData.filters = searchData.filters.filter(item=>item.column!='isZero')
    tableObject.params = {
      isSearch: true,
      filters: [...searchData.filters,{
        action: "==",
        column: "isZero",
        value: isZero.value?0:1
      }]
    }
    getList() // 刷新当前列表
  }
  const clearSearchInput = (field) => {
    if (field == 'supplierCode') {
      formRef.value.formRef.setValues({
        poNumber: ''
      })
      clearTableDataSearch()
    }
    if (field == 'poNumber') {
      clearTableDataSearch()
    }
  }

  /** 初始化 **/
  onMounted(async () => {
    getList()
    importTemplateData.templateUrl = await PurchasePlanMainApi.importTemplate()
    nextTick(()=>{
      tableColumns.value=tableColumns.value.filter(item=>item.field!='shippedQty')
    })
  })
</script>
