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

    <!-- 列表头部 -->
    <TableHead
      :HeadButttondata="HeadButttondata"
      @button-base-click="buttonBaseClick"
      :routeName="routeName"
      @updataTableColumns="updataTableColumns"
      @searchFormClick="searchFormClick"
      :allSchemas="CustomerSaleInvoiceMain.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 #number="{row}">
        <el-button type="primary" link @click="openDetail(row, '单据号', row.number)">
          <span>{{ row.number }}</span>
        </el-button>
      </template>
    </Table>
  </ContentWrap>


  <!-- 详情 -->
  <Detail
    ref="detailRef"
    :isBasic="false"
    :allSchemas="CustomerSaleInvoiceMain.allSchemas"
    :detailAllSchemas="CustomerSaleInvoiceDetail.allSchemas"
    :detailAllSchemasRules="CustomerSaleInvoiceDetailRules"
    :apiCreate="CustomerSaleInvoiceDetailApi.createCustomerSaleInvoiceDetail"
    :apiUpdate="CustomerSaleInvoiceDetailApi.updateCustomerSaleInvoiceDetail"
    :apiPage="CustomerSaleInvoiceDetailApi.getCustomerSaleInvoiceRecordDetailPage"
    :apiDelete="CustomerSaleInvoiceDetailApi.deleteCustomerSaleInvoiceDetail"
    :detailButtonIsShowAdd="false"
    :otherHeadButttonData = "[defaultButtons.defaultExportBtn({hasPermi:`wms:customer-sale-invoice-record-main:export` })]"
    @buttonBaseClick="detailButtonBaseClick"
    :Echo="Echo"
    @searchTableSuccessDetail="searchTableSuccessDetail"
  />

  <!-- 导入 -->
  <ImportForm ref="importFormRef" url="/wms/deliver-plan-main/import" :importTemplateData="importTemplateData"
  @success="importSuccess" :updateIsDisable="true" :coverIsDisable="true" :mode="2" :extend= "businessType"/>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { CustomerSaleInvoiceMain,CustomerSaleInvoiceDetailRules,CustomerSaleInvoiceDetail} from './customerSaleInvoiceRecordMain.data'
import * as CustomerSaleInvoiceMainApi from '@/api/wms/customerSaleInvoiceMain'
import * as CustomerSaleInvoiceDetailApi from '@/api/wms/customerSaleInvoiceDetail'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import { formatDate } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const { loadStart, loadDone } = usePageLoading()
// 销售开票记录
defineOptions({ name: 'customerSaleInvoiceRecordMain' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const businessType = ref()
const tableColumns = ref(CustomerSaleInvoiceMain.allSchemas.tableColumns)
const { tableObject, tableMethods } = useTable({
  getListApi: CustomerSaleInvoiceMainApi.getCustomerSaleInvoiceRecodeMainPage // 分页接口
})

// 字段设置 更新主列表字段
const updataTableColumns = (val) => {
  tableColumns.value = val
}
// 点击子表按钮事件
const detailButtonBaseClick = async (val, item,tableObject) => {
  if (val == 'export') {
    // 子表导出
    console.log('子表导出',val, tableObject)
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      loadStart()
      const excelTitle = ref(route.meta.title)
      const data = await CustomerSaleInvoiceDetailApi.exportCustomerSaleInvoiceRecordDetail(tableObject.params)
      download.excel(data, `【${excelTitle.value}】【${formatDate(new Date())}】.xlsx`)
    } catch {

    } finally {
      loadDone()
    }


  }
}
// 查询页面返回——详情
const searchTableSuccessDetail = (formField, searchField, val, formRef ) => {
  nextTick(() => {
    const setV = {}
    setV[formField] = val[0][searchField]
    // setV['soLine'] = val[0]['lineNumber']
    // setV['lineNumber'] = val[0]['lineNumber']
    // setV['itemCode'] = val[0]['itemCode']
    setV['remark'] = val[0]['remark']
    setV['uom'] = val[0]['customerUom']
    formRef.setValues(setV)
  })
}


// 子表新增的时候选择表格之后需要会显得字段
// const Echo = ['ppNumber','poLine', 'batch', 'altBatch', 'itemCode', 'itemName', 'itemDesc1', 'itemDesc2', 'projectCode', 'qty', 'uom']
const Echo =  []

// 获得表格的各种操作
const { getList, setSearchParams } = tableMethods
// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultImportBtn({hasPermi:`wms:customer-sale-invoice-record-main:import` }), // 导入
  defaultButtons.defaultExportBtn({hasPermi:`wms:customer-sale-invoice-record-main:export` }), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null), // 设置
]

// 头部按钮事件
const buttonBaseClick = (val, item) => {
  if (val == 'import') { // 导入
    handleImport()
  } else if (val == 'export') { // 导出
    handleExport()
  } else if (val == 'refresh') { // 刷新
    if (tableObject.params.filters && tableObject.params.filters.length > 0 ) {
      searchFormClick({
        filters: tableObject.params.filters
      })
    } else {
      getList()
    }
  } else if (val == 'filtrate') { // 筛选
  } else { // 其他按钮
    console.log('其他按钮', item)
  }
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  detailRef.value.openDetail(row, titleName, titleValue,'planDeliverMain')
}

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

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

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

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

// 筛选提交
const searchFormClick = (searchData) => {
  tableObject.params = {
    isSearch: true,
    filters: searchData.filters
  }
  getList() // 刷新当前列表
}
const seachRef = ref()
const onSearchChange = (field, value)=>{
  if(field=='customerCode'){
    if(value.length>0){
      if(value[value.length-1]=='ALL'){
        //全选
        seachRef.value.setFormValues({
          customerCode:['ALL']
        })
      }else{
        seachRef.value.setFormValues({
          customerCode:value.filter(item=>item!='ALL')
        })
      }
    }
  }
}
const searchClick = async (data)=>{
  console.log('查询',data)
  setSearchParams({...data,customerCode:data.customerCode.filter(item=>item!='ALL')})
}
/** 初始化 **/
onMounted(async () => {
  getList()
  importTemplateData.templateUrl = await CustomerSaleInvoiceMainApi.importTemplate()
})
</script>
