<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search :schema="SettlementReport.allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
  </ContentWrap>

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

  <!-- 列表 -->
  <ContentWrap>
    <Table
      :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 #action="{ row }">
        <ButtonBase :Butttondata="butttondata(row)" @button-base-click="buttonTableClick($event,row)" />
      </template>
    </Table>
  </ContentWrap>

  <!-- 结算库位列表 -->
  <SearchTable
    ref="searchTableRef"
    :showSearchTableQueryFields="['itemCode']"
    :hiddenFilterBtnFields="[]"
    :isCheckStrictly="false"
    @searchTableSuccess="searchTableSuccess"
    :hiddenFooterActions="true"
  >
  <template #footerActions>
    <div class="flex items-center" style="justify-content: flex-end;">
      <el-button type="primary" @click="settlementClick">结算库位</el-button>
      <el-button @click="cancleClick">{{ t(`ts.${'取 消'}`) }}</el-button>
    </div>
  </template>
  <template #searchQueryhahaha>
    <Form
        ref="basicFormRef"
        :rules="SettlementReportSelectionFormRules"
        :schema="SettlementReportSelectionForm.allSchemas.formSchema"
        :is-col="true"
        @opensearchTable="opensearchTable"
        @onBlur="onBlur"
      />
    </template>
  </SearchTable>

  <!-- 库位 -->
  <SearchTable
    ref="searchTableRef1"
    @searchTableSuccess="searchTableSuccess1"
  />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { SettlementReport,SettlementReportRules,SettlementReportSelection,SettlementReportSelectionlRules,SettlementReportSelectionForm,SettlementReportSelectionFormRules } from './settlementReport.data'
import * as SettlementtReportApi from '@/api/wms/settlementReport'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import TableHead from '@/components/TableHead/src/TableHead.vue'
import ImportForm from '@/components/ImportForm/src/ImportForm.vue'
import Detail from '@/components/Detail/src/Detail.vue'
import { Warehouse } from '@/views/wms/basicDataManage/factoryModeling/warehouse/warehouse.data'
import * as WarehouseApi from '@/api/wms/warehouse'
import * as LocationApi from '@/api/wms/location'
import { Location } from '@/views/wms/basicDataManage/factoryModeling/location/location.data'
import { tableFormBlurVer, FormBlur, getListByBottonInput } from '@/api/wms/business/inputBlur'


// 上线结算配置管理
defineOptions({ name: 'SettlementReport' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const tableColumns = ref(SettlementReport.allSchemas.tableColumns)

// 字段设置 更新主列表字段
const updataTableColumns = (val) => {
  tableColumns.value = val
}

const { tableObject, tableMethods } = useTable({
  getListApi: SettlementtReportApi.getSettlementReportPage // 分页接口
})

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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultFreshBtn(null), // 刷新
  // {
  //   label: '自定义扩展按钮',
  //   name: 'zdy',
  //   hide: false,
  //   type: 'primary',
  //   icon: 'Select',
  //   color: ''
  // },
]

// 头部按钮事件
const buttonBaseClick = (val, item) => {
  if (val == 'refresh') { // 刷新
    getList()
  } else if (val == 'filtrate') { // 筛选
  } else { // 其他按钮
    console.log('其他按钮', item)
  }
}
// 列表-操作按钮
const butttondata = (row) => {
  return [{
    label: '结算',
    name: 'settlement',
    // hide: row.settledStatus!=2,
    hide: '',
    type: 'primary',
    icon: '',
    color: '',
    hasPermi: ''
  }]
}

const searchTableRef = ref()
// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if(val == 'settlement'){
    // 结算
    searchTableRef.value.open(
      "批量结算",
      SettlementReportSelection.allSchemas,
      SettlementtReportApi.getSettlementReportBalance,
      "hahaha",
      "hahaha",
      true,
      'tableForm',
      null,
      {
        supplierCode:row.supplierCode,
        itemCode:row.itemCode,
        batch:row.batch
      },
      undefined,
      false,
      null
    )
  }
}
// 批量结算
const settlementClick = ()=>{
  if(!basicFormRef.value.formModel['toLocationCode']){
    message.warning('请选择结算库位')
    return
  }else{
    searchTableRef.value.submitForm()
  }
}

const cancleClick = ()=>{
  searchTableRef.value.cancleClick()
}
// 批量结算
const searchTableSuccess = (formField, searchField, val, formRef, type, row) => {
  console.log('formModel',basicFormRef.value.formModel['toLocationCode'])
  console.log('searchTableSuccess',formField, searchField, val, formRef, type, row )
  nextTick(async () => {
    let ids = []
    ids = val.map(item=>(item['id']))
    ids.join(',')
    let res = await SettlementtReportApi.submitSettlementReport({
      ids,
      toLocationCode:basicFormRef.value.formModel['toLocationCode']||''
    })
    if(res==1){
      message.success('提交成功')
      getList()
    }
  })
}


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

/** 添加/修改操作 */
const basicFormRef = ref()
// 结算库位
const opensearchTable = (
  formField,
  searchField,
  searchTitle,
  searchAllSchemas,
  searchPage,
  searchCondition,
  multiple,
  type,
  row,
  isConcatDetailSchemas = false,
  searchDetailSchemas: any
) => {
  
    searchTableRef1.value.open(
      "结算库位",
      Location.allSchemas,
      LocationApi.getLocationPage,
      "toLocationCode",
      "code",
      false,
      'form',
      null,
      {
        // supplierCode:row.supplierCode,
        // itemCode:row.itemCode,
        // batch:row.batch
      },
      undefined,
      false,
      null
    )
}

const searchTableRef1 = ref()
const searchTableSuccess1 = (formField, searchField, val, formRef, type, row) => {
  console.log('searchTableSuccess',formField, searchField, val, formRef, type, row )
  nextTick(() => {
    const setV = {}
    setV[formField] = val[0][searchField]
    basicFormRef.value.setValues(setV)
  })
}
const onBlur = async (field, e) => {
  let formSchemaObj = SettlementReportSelectionForm.allSchemas.formSchema.find((item) => item.field == field)?.componentProps
  if (formSchemaObj?.enterSearch) {
    await FormBlur(
      field,
      e,
      routeName.value,
      basicFormRef.value,
      null,
      formSchemaObj,
      (list) => {
        searchTableSuccess1(field, formSchemaObj.searchField, list, basicFormRef.value, 'form')
      }
    )
  }
}
/** 初始化 **/
onMounted(async () => {
  getList()
  // importTemplateData.templateUrl = await SettlementConfigurationApi.importTemplate()
})

</script>
