<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search ref="seachRef"  :schema="DemandforecastingMain.allSchemas.searchSchema" @search="searchClick" @reset="searchClick" @searchTableSuccess="searchQueryTableSuccess"/>
  </ContentWrap>

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

  <!-- 列表 -->
  <ContentWrap>
    <Table ref="tableRef" v-clientTable
      :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"
    >
    <template #isRead="{row}" >
      <el-button v-show="row.isRead!=2" :type="row.isRead==1?'info':'primary'" link  @click="readHandle(row,false)">
          <span>{{ row.isRead==1?'已读':'未读' }}</span>
      </el-button>
    </template>
    <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'
import { formatDate } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
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 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:demandforecastingSupplier-main:export'}), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  // defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null), // 设置
  {
      label: t('ts.全部已读'),
      name: 'read',
      hide: false,
      type: 'primary',
      // icon: 'ep:operation',
      color: '',
      float:'left',
      link: false, // 文本展现按钮
      hasPermi: ''
  }
]

// 头部按钮事件
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 if (val == 'read') { // 全部已读
    readHandle(null,true)
  } else { // 其他按钮
    console.log('其他按钮', item)
  }
}



const searchClick = async (data)=>{
  data.flag = 1
  data.status = 2
  console.log('searchClick',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.exportDemandforecastingMain(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() // 刷新当前列表
}

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 readHandle = (row,isAll)=>{
  let rows:any = []
  if(isAll){
    //全部已读
    if(selectionRows.value==0){
      return
    }
    selectionRows.value.forEach(item=>{
      let itemSelectionRows = item.selectionRows.filter(item1=>item1.isRead==0)
      console.log('itemSelectionRows',itemSelectionRows)
      rows = [...rows,...itemSelectionRows.map(item1=>item1.mainId)]
    })
    console.log('selectionRows',selectionRows)
    console.log('全部已读',rows.join(','))
  }else{
    //单行
    if(row.isRead==1){
      return
    }
    rows = [row.mainId]
    console.log('已读',rows.join(','))
  }
  
  let getLoading = ElLoading.service({
    lock: true,
    text: 'loading...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  DemandforecastingMainApi.updateIsRead({isReadMainIds:rows.join(',')}).then(res => {
    console.log('res',res);
    getLoading?.close()
    getList()
    if(isAll){
      selectionRows.value = []
    }
  }).catch(err => {
    console.log(err)
    getLoading?.close()
  })
  
}
const seachRef = ref()

/** 初始化 **/
onMounted(async () => {
  // await getListHead()
  // // 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>
