<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search ref="seachRef" :showSearchTableQueryFields="['supplierCode','itemCode']" :hiddenFilterBtnFields="['supplierCode','itemCode']" :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
      :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"
    >
    <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>
    </Table>
  </ContentWrap>


</template>

<script setup lang="ts">
import download from '@/utils/download'
import { DemandforecastingMain,DemandforecastingMainRules,DemandforecastingDetail,DemandforecastingDetailRules } from './demandforecastingMain.data'
import * as DemandforecastingMainApi from '@/api/wms/demandforecastingMain'
import * as DemandforecastingDetailApi from '@/api/wms/demandforecastingDetail'
import * as defaultButtons from '@/utils/disposition/defaultButtons'

// 要货预测
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 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[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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultExportBtn({hasPermi:'wms:demandforecasting-main:export'}), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  // defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null), // 设置
]

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

    }
  } else if (val == 'filtrate') { // 筛选
  } else { // 其他按钮
    console.log('其他按钮', item)
  }
}


const seachRef = ref()
const onSearchChange = (field, value)=>{
  if(field=='planerId'){
    if(value.length>0){
      if(value[value.length-1]==''){
        //全选
        seachRef.value.setFormValues({
          planerId:['']
        })
      }else{
        seachRef.value.setFormValues({
          planerId:value.filter(item=>item!='')
        })
      }
    }
  }
}
const searchClick = async (data)=>{
  console.log('searchClick',data)
  await setSearchParamsHead(data)
  // updateDateTableColumns()
  setSearchParams(data)
}
/** 导出按钮操作 */
const exportLoading = ref(false) // 导出的加载中
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DemandforecastingMainApi.exportDemandforecastingMain(tableObject.params)
    download.excel(data, `${t('ts.要货预测主')}.xlsx`)
  } catch {
  } finally {
    exportLoading.value = false
  }
}


// 导入附件弹窗所需的参数
const importTemplateData = reactive({
  templateUrl: '',
  templateTitle: `${t('ts.要货预测主导入模版')}.xlsx`
})

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

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

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