<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search ref="seachRef"   :hiddenFilterBtnFields="['detailVersion','itemCode','version']"   :schema="DemandforecastingMain.allSchemas.searchSchema" @search="searchClick" @reset="searchClick" @searchTableSuccess="searchQueryTableSuccess" @onChange="onSearchChange"/>
  </ContentWrap>

  <!-- 列表头部 -->
  <TableHead
    :HeadButttondata="HeadButttondata"
    @button-base-click="buttonBaseClick"
    :routeName="routeName"
    @updataTableColumns="updataTableColumns"
    @searchFormClick="searchFormClick"
    :allSchemas="DemandforecastingMain.allSchemas"
  />

  <!-- 列表 -->
  <ContentWrap>
    <Table v-clientTable
      ref="tableRef"
      :selection="true"
      :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"
      :reserve-selection="true"
      row-key="id"
    >
    <template v-for="name in tableObjectHead.tableList" :key="name" #[name]="{row}">
      <span :class="{'success-text':row['planType_F'].indexOf(name)>-1}">{{ row[name] }}</span>
    </template>
    <template #action="{ row,$index }">
      <ButtonBase :Butttondata="butttondata(row,$index)" @button-base-click="buttonTableClick($event,row)" />
    </template>
    </Table>
  </ContentWrap>
  <!-- :vLoading="formLoadingPlan" -->
  <Dialog title="预览要货计划" v-model="dialogVisiblePlan" width="80%" :close-on-click-modal="false" >
    <div v-loading="formLoadingPlan">
      <Table 
        ref="tablePlanRef"
        :selection="true"
        :columns="tableColumnsPlan"
        :data="tableObjectPlan.tableList"
        :loading="tableObjectPlan.loading"
        v-model:pageSize="tableObjectPlan.pageSize"
        v-model:currentPage="tableObjectPlan.currentPage"
        v-model:sort="tableObjectPlan.sort"
        @getSelectionRows="getSelectionRowsPlan"
      />
      <div style="padding-top: 20px;text-align: right;">
        <slot name="foorter"></slot>
        <ButtonBase :Butttondata="[
          defaultButtons.formSaveBtn(null), // 保存 
          defaultButtons.formCloseBtn(null) // 关闭 
          ]"
         @button-base-click="buttonBaseClickPlan" />
      </div>
    </div>
  </Dialog>


</template>

<script setup lang="ts">
import download from '@/utils/download'
import { DemandforecastingMain,DemandforecastingMainRules,DemandforecastingDetail,DemandforecastingDetailRules,DemandforecastingMainPlan } from './demandforecastingMain.data'
import * as DemandforecastingMainApi from '@/api/wms/demandforecastingMain'
import * as DemandforecastingDetailApi from '@/api/wms/demandforecastingDetail'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import { formatDate } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { isString } from '@/utils/is'
import {publish} from "@/api/wms/demandforecastingMain";
import { disable } from '@/api/infra/outerApiHis'

const { loadStart, loadDone } = usePageLoading()
// 要货预测
defineOptions({ name: 'DemandforecastingMain' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const orginTableColumns = ref(DemandforecastingMain.allSchemas.tableColumns)
const tableColumns = ref(DemandforecastingMain.allSchemas.tableColumns)
// 字段设置 更新主列表字段
const updataTableColumns = (val) => {
  orginTableColumns.value = val
}

const formLoadingPlan = ref(false)

// 查询页面返回
const searchQueryTableSuccess = (formField, searchField, val, formRef, type, row ) => {
  console.log('searchQueryTableSuccess',formField, searchField, val, formRef, type, row )
  nextTick(() => {
    const setV = {}
    if(formField == 'supplierCode'||formField == 'itemCode'||formField == 'version'){
      //供应商代码 品番 版本号
      let list = []
      val.forEach(item=>{
        list.push(item[searchField])
        setV['dueDate'] = item.yearMonth
      })
      setV[formField] = list.join(' ')
      formRef.setValues(setV)
    }else{
      setV[formField] = val[0][searchField]
      formRef.setValues(setV)
    }
  })
}


const { tableObject:tableObjectHead, tableMethods:tableMethodsHead } = useTable({
  getListApi: DemandforecastingDetailApi.getPageTableHead // 分页接口
})

// 获得表格的各种操作
const { getList:getListHead, setSearchParams:setSearchParamsHead } = tableMethodsHead

watch(()=>tableObjectHead.tableList,()=>{
  updateDateTableColumns()
},{deep:true})
const updateDateTableColumns = ()=>{
  console.log('tableObjectHead',tableObjectHead)
  let dateColumns = []
  if(tableObjectHead.tableList.length>10){
    tableObjectHead.tableList.forEach(item=>{
    dateColumns.push({
        width:120,
        field: item,
        label: item
      })
    })
  }else{
    tableObjectHead.tableList.forEach(item=>{
    dateColumns.push({
        field: item,
        label: item
      })
    })
  }
  tableColumns.value  = [...orginTableColumns.value,...dateColumns]
  console.log('tableColumns',tableColumns.value)
}
const { tableObject, tableMethods } = useTable({
  getListApi: DemandforecastingDetailApi.getDemandforecastingDetailPage // 分页接口
})

// 获得表格的各种操作
const { getList, setSearchParams } = tableMethods
watch(()=>tableObject.currentPage,async ()=>{
  tableObjectHead.currentPage = tableObject.currentPage
  updateDateTableColumns()
})
// 列表头部按钮
const HeadButttondata = [
defaultButtons.defaultExportBtn({hasPermi:'wms:demandforecasting-main:export'}), // 导出
{
  label: t(`ts.批量生成要货计划`).replace('ts.', ''),
  name: 'selectionPlan',
  hide: false,
  type: 'primary',
  icon: '',
  color: '',
  hasPermi: ''
},
defaultButtons.defaultFreshBtn(null), // 刷新
  // defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null), // 设置
  defaultButtons.mainListSelectionOrderPubBtn(null), // 批量发布按钮
  defaultButtons.mainUpdataForecastBtn({hasPermi:'wms:demandforecasting-main:updateDQA'}), // 更新要货预测
]

// 头部按钮事件
const buttonBaseClick = async (val, item) => {
  if (val == 'export') { // 导出
    handleExport()
  } else if (val == 'refresh') { // 刷新
    selectionRows.value = []
    if (tableObject.params.filters && tableObject.params.filters.length > 0 ) {
      searchFormClick({
        filters: tableObject.params.filters
      })
    } else {
      await getListHead()
      // updateDateTableColumns()
      getList()

    }
  } else if (val == 'filtrate') { // 筛选
  } else if (val == 'selectionPlan') { // 批量生成要货计划
    selectionPlan()
  } else if (val == 'mainOrderSelectionPub') { // 批量发布要货计划
    handleSelectionPublish()
  } else if (val == 'updataForecast') { // 要货预测调用QAD
    updateDemandforecaste()
  } else { // 其他按钮
    console.log('其他按钮', item)
  }
}

const isShowMainButton = (row,val) => {
  if (val.indexOf(row.status) > -1) {
    return false
  } else {
    return true
  }
}

// 列表-操作按钮
const butttondata = (row,$index) => {
  return [
    {
      label: t(`ts.生成要货计划`).replace('ts.', ''),
      name: 'previewPlan',
      hide: isShowMainButton(row, ['2']) || !(row['planType_F'].length>0&&(!tableObject.params.version || tableObject.params.version.length == 0)) || row.isMaxScpVersion == '1',
      type: 'primary',
      color: '',
      link: true, // 文本展现按钮
      hasPermi: ''
    },
    {
      label: '发布',
      name: 'publish',
      hide: isShowMainButton(row, ['1']) || row.isMaxScpVersion == '1',
      type: 'primary',
      color: '',
      link: true, // 文本展现按钮
      hasPermi: ''
    }
  ]
}

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'previewPlan') { // 生成要货计划
    tableObjectPlan.params.masterIds = row.mainId
    console.log('row===========',row);
    tableObjectPlan.params.scpVersion = row.version
    tableObjectPlan.params.dueDate = tableObject.params.dueDate
    handlePreviewPlan()
  } else if(val == 'publish') {
    handlePublish(row)
  }
}

const handlePublish = (row)=>{
  DemandforecastingMainApi.publish({id:row.mainId}).then(res => {
    console.log('res',res);
    getList()
  }).catch(err => {
    console.log(err)
  })
}




const dialogVisiblePlan = ref(false)
// 批量
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 tableColumnsPlan = ref(DemandforecastingMainPlan.allSchemas.tableColumns)
const { tableObject:tableObjectPlan, tableMethods:tableMethodsPlan } = useTable({
  getListApi: DemandforecastingDetailApi.getPreviewPlan // 分页接口
})
// 获得表格的各种操作
const { getList:getListPlan} = tableMethodsPlan
// 批量生成要货计划
const selectionPlan = async ()=>{
  if(!tableObject.tableList || tableObject.tableList.length === 0){
  return
 }
 if(tableObject.tableList[0].isMaxScpVersion == '1'){
    message.alert('选择版本号时无法生成要货计划!');
    return;
  }
  let rows: any = []
  selectionRows.value.forEach((item) => {
    rows = [...rows, ...item.selectionRows.map((item1) => item1.mainId)]
  })
  console.log('批量生成要货计划', rows.join(','))
  if(!rows || rows.length ===0){
    message.alert('勾选数据不能为空!');
    return 
  }
  console.log('批量生成要货计划', rows.join(','))
  tableObjectPlan.params.masterIds = rows.join(',')
  tableObjectPlan.params.dueDate = tableObject.params.dueDate
  handlePreviewPlan()
}
const handlePreviewPlan = async ()=>{

  // if(tableObject.params.dueDate&&tableObject.params.dueDate.length>0){
  //   if(isString(tableObject.params.dueDate[0])){
  //     tableObjectPlan.params.startDate = tableObject.params.dueDate[0]
  //   }else{
  //     tableObjectPlan.params.startDate = tableObject.params.dueDate[0].format('YYYY-MM-DD')
  //   }
  // }
  // if(tableObject.params.dueDate&&tableObject.params.dueDate.length>1){
  //   if(isString(tableObject.params.dueDate[1])){
  //     tableObjectPlan.params.endDate = tableObject.params.dueDate[1]
  //   }else{
  //     tableObjectPlan.params.endDate = tableObject.params.dueDate[1].format('YYYY-MM-DD')
  //   }
  // }
  // if (!tableObject.params.dueDate || tableObject.params.dueDate.length == 0) {
  //   tableObjectPlan.params.startDate = ''
  //   tableObjectPlan.params.endDate = ''
  // }

  await getListPlan()
  selectionPlanRows.value = []
  dialogVisiblePlan.value = true
  // 全选
  nextTick(()=>{
    tablePlanRef.value.toggleAllSelection(true)
  })
}

const buttonBaseClickPlan = async (val)=>{
  if (val == 'save') {
    // 保存
    formLoadingPlan.value =true
    try {
       let rows: any = []
      selectionPlanRows.value.forEach((item) => {
        rows = [...rows, ...item.selectionRows.map((item1) => item1.id)]
      })
      console.log('预览要货计划', selectionPlanRows.value)
      console.log('预览要货计划', rows.join(','))
      let res = await DemandforecastingDetailApi.generateOrderPlan(rows)
      message.success(t('common.submitSuccess'))
      buttonBaseClick('refresh', null)
      dialogVisiblePlan.value = false
      console.log('保存',res)
    } finally {
      formLoadingPlan.value =false
    }
   
  }
  // 关闭
  else if (val == 'close') {
    dialogVisiblePlan.value = false
  }
}
// 预览要货计划-批量
const selectionPlanRows = ref<any>([])
const tablePlanRef = ref()
const getSelectionRowsPlan = (currentPage, currentPageSelectionRows) => {
  const currentRows = selectionPlanRows.value.find((item) => item.currentPage == currentPage)
  if (currentRows) {
    currentRows.selectionRows = currentPageSelectionRows
  } else {
    selectionPlanRows.value.push({
      currentPage,
      selectionRows: currentPageSelectionRows
    })
  }
}

// 批量发布
const handleSelectionPublish = async ()=>{
 if(!tableObject.tableList || tableObject.tableList.length === 0){
  return
 }
 if(tableObject.tableList[0].isMaxScpVersion == '1'){
    message.alert('选择版本号时无法批量发布!');
    return;
  }
 
 let rows: any = []
  selectionRows.value.forEach((item) => {
    rows = [...rows, ...item.selectionRows.map((item1) => item1.mainId)]
  })
  console.log('批量生成要货计划', rows.join(','))
  if(!rows || rows.length ===0){
    message.alert('勾选数据不能为空!');
    return 
  }
  tableObject.loading = true
  let ids  = rows.join(',')
  await DemandforecastingMainApi.batchPublish(ids)
      .then((res) => {
        // if (res?.status == '2') {
        //   message.error(res.message)
        // } else {
        //   message.success(res.message)
        // }
        console.log('获取到的数据',res);
        message.success(res.message)
        tableObject.loading = false
        buttonBaseClick('refresh', null)
      })
      .catch((err) => {
        tableObject.loading = false
        console.log(err)
      })
  // await PackageApi.batchPrintingLable(rows.join(',')).then(res => {
  //     console.log(res)
  //     window.open(srcPoint.value+'&relateNumber='+res)
  //     message.success('创建标签成功')
  // }).catch(err => {
  //   console.log(err)
  //   message.error('创建标签失败')
  // })
}

//点击要货预测调用QAD拉数据
const updateDemandforecaste = async ()=>{
  let submitData = {
    "supplierCodes":"",
    "itemCodes":""
  }
  //tableObject.loading = true
  try {
    let res = await DemandforecastingMainApi.updateDemandforecaste(submitData)
    console.log('更新结果',res)
    message.success(t('正在拉取数据，预计需要 20-30 分钟!'))
    getList()
  } finally{
    //tableObject.loading = false
  }

}




const seachRef = ref()
const onSearchChange = (field, value)=>{
  if(field=='planerId'){
    if(value.length>0){
      if(value[value.length-1]=='ALL'){
        //全选
        seachRef.value.setFormValues({
          planerId:['ALL']
        })
      }else{
        seachRef.value.setFormValues({
          planerId:value.filter(item=>item!='ALL')
        })
      }
    }
  }
}
const searchClick = async (data)=>{
  await setSearchParamsHead(data)
  // updateDateTableColumns()
  setSearchParams(data)
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    loadStart()
    const excelTitle = ref(route.meta.title)
    const data = await DemandforecastingMainApi.exportDemandforecastingPlannnerMain(tableObject.params)
    download.excel(data, `【${excelTitle.value}】【${formatDate(new Date())}】.xlsx`)
  } catch {
  } finally {
    loadDone()
  }
}


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

// 筛选提交
const searchFormClick = (searchData) => {
  tableObject.params = {
    isSearch: true,
    filters: searchData.filters
  }
  getList() // 刷新当前列表
}

/** 初始化 **/
onMounted(async () => {
  // try {
  //   await getListHead()
  // } catch (error) {
    
  // }
  // // updateDateTableColumns()
  // getList()
  seachRef.value.search()
  importTemplateData.templateUrl = await DemandforecastingMainApi.importTemplate()
})
</script>
<style lang="scss" scoped>

.success-text{
  color:var(--el-color-success);
  font-weight:700;
}
</style>
