<template>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <Search ref="seachRef"
        :schema="SupplierMoldCostMain.allSchemas.searchSchema"
        @search="searchClick"
        @reset="searchClick"
        @onChange="onSearchChange"
      />
    </ContentWrap>
  
    <!-- 列表头部 -->
    <TableHead
      :HeadButttondata="HeadButttondata"
      @button-base-click="buttonBaseClick"
      :routeName="routeName"
      @updataTableColumns="updataTableColumns"
      @searchFormClick="searchFormClick"
      :allSchemas="SupplierMoldCostMain.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 #number="{ row }">
          <el-button type="primary" link @click="openDetail(row, '单据号', row.number)">
            <span>{{ row.number }}</span>
          </el-button>
        </template>
        <template #action="{ row, $index }">
          <ButtonBase
            :Butttondata="butttondata(row, $index)"
            @button-base-click="buttonTableClick($event, row)"
          />
        </template>
      </Table>
    </ContentWrap>
    <!-- 详情 -->
    <Detail
      ref="detailRef"
      :isBasic="false"
      :allSchemas="SupplierMoldCostMain.allSchemas"
      :detailAllSchemas="SupplierMoldCostDetail.allSchemas"
      :extendRowKeyValue = "[{
        key:'number',
        value:'number'
      }]"
      :apiPage="SuppliperMoldCostDetailApi.getSupplierMoldCostDetailPage"
      :detailButtonIsShowAdd="false"
      :otherHeadButttonData = "[]"
      @buttonBaseClick="detailButtonBaseClick"
    />
    <!-- 导入 -->
  <ImportSupplierMoldCostForm
    ref="importFormRef"
    url="/wms/supplier-tool-apport-statement-main/import"
    :importTemplateData="importTemplateData"
    @success="importSuccess"
  />
  </template>
  
  <script setup lang="ts">
  import download from '@/utils/download'
  import {
    SupplierMoldCostMain,
    SupplierMoldCostDetail
  } from './supplierMoldCostMain.data'
  import * as SuppliperMoldCostMainApi from '@/api/wms/suppliperMoldCostMain'
  import * as SuppliperMoldCostDetailApi from '@/api/wms/suppliperMoldCostDetail'
  import ImportSupplierMoldCostForm from '@/components/ImportForm/src/ImportSupplierMoldCostForm.vue'

  import * as defaultButtons from '@/utils/disposition/defaultButtons'
  import TableHead from '@/components/TableHead/src/TableHead.vue'
  import Detail from '@/components/Detail/src/Detail.vue'
  import { formatDate } from '@/utils/formatTime'
  // 供应商模具费用
  defineOptions({ name: 'supplierMoldCostMain' })
  
  const message = useMessage() // 消息弹窗
  const { t } = useI18n() // 国际化
  
  const route = useRoute() // 路由信息
  const routeName = ref()
  routeName.value = route.name
  const tableColumns = ref(SupplierMoldCostMain.allSchemas.tableColumns)
  
  const otherHeadButttonData = ref()
  
  // 查询页面返回
  const searchTableSuccess = (formField, searchField, val, formRef) => {
    nextTick(() => {
      const setV = {}
      setV[formField] = val[0][searchField]
      formRef.setValues(setV)
    })
  }
  
  // 字段设置 更新主列表字段
  const updataTableColumns = (val) => {
    tableColumns.value = val
  }
  
  const { tableObject, tableMethods } = useTable({
    getListApi: SuppliperMoldCostMainApi.getSupplierMoldCostMainPage // 分页接口
  })
  
  // 获得表格的各种操作
  const { getList, setSearchParams } = tableMethods
  
  // 列表头部按钮
  const HeadButttondata = [
    defaultButtons.defaultImportBtn({hasPermi:'wms:supplier-mold-cost-main:import'}), // 导入
    defaultButtons.defaultExportBtn({hasPermi:'wms:supplier-mold-cost-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') {
      // 刷新
      getList()
    } else if (val == 'filtrate') {
      // 筛选
    } else {
      // 其他按钮
      console.log('其他按钮', item)
    }
}
  
  // 列表-操作按钮
  const butttondata = (row, $index) => {
    const findIndex = row['masterId']
      ? tableObject.tableList.findIndex((item) => item['masterId'] == row['masterId'])
      : -1
    if (findIndex > -1 && findIndex < $index) {
      return []
    }
    return [
    {
      label: t('ts.发布'),
      name: 'publish',
      hide: row.status!=0,
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: '',
      link: true // 文本展现按钮
    },
    {
      label: t('ts.作废'),
      name: 'abrogate',
      hide: row.isAbrogate!=1,
      type: 'danger',
      icon: '',
      color: '',
      hasPermi: '',
      link: true // 文本展现按钮
    },
    {
      label: t('ts.退回'),
      name: 'back',
      hide: row.isBack!=1,
      type: 'warning',
      icon: '',
      color: '',
      hasPermi: '',
      link: true // 文本展现按钮
    }
    ]
  }
  
  // 列表-操作按钮事件
  const buttonTableClick = async (val, row) => {
    if(val=='publish'){
        //发布
        try {
            // 删除的二次确认
            await message.confirm('确认发布吗?')
            // 发起删除
            await SuppliperMoldCostMainApi.publish(row.id)
            message.success('发布成功')
            // 刷新列表
            buttonBaseClick('refresh')
        } catch {}
    }else if(val=='abrogate'){
        //作废
        try {
            // 删除的二次确认
            await message.confirm('确认作废吗?')
            // 发起删除
            await SuppliperMoldCostMainApi.nodeAbrogate(row.id)
            message.success('作废成功')
            // 刷新列表
            buttonBaseClick('refresh')
        } catch {}
    }else if(val=='back'){
        //作废
        try {
            // 删除的二次确认
            await message.confirm('确认退回吗?')
            // 发起删除
            await SuppliperMoldCostMainApi.sendBack(row.id)
            message.success('退回成功')
            // 刷新列表
            buttonBaseClick('refresh')
        } catch {}
    }
    
  }

  
  /** 详情操作 */
  const detailRef = ref()
  const tableObjectExtend = ref([])
  const openDetail = (row: any, titleName: any, titleValue: any) => {
    tableObjectExtend.value = [{
      key: 'number',
      value: row.number
    }]
    detailRef.value.openDetail(row, titleName, titleValue, 'basicCustomerStatementMain')
  }
  
  
  
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SuppliperMoldCostMainApi.exportSupplierMoldCostMain(tableObject.params)
    download.excel(data, '供应商模具费用主表.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
  /** 导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}
// 导入附件弹窗所需的参数
const importTemplateData = reactive({
  templateTitle: '供应商模具费用导入模版.xlsx',
  templateUrl :  SuppliperMoldCostMainApi.importTemplate
})
// 导入成功之后
const importSuccess = () => {
  getList()
}


  
  // 筛选提交
  const searchFormClick = (searchData) => {
    tableObject.params = {
      isSearch: true,
      filters: searchData.filters
    }
    getList() // 刷新当前列表
  }
  const seachRef = ref()
  const onSearchChange = (field, value)=>{
    if(field=='status'){
        // 状态
        if(value.length>0){
        if(value[value.length-1]==''){
            //全选
            seachRef.value.setFormValues({
            status:['']
            })
        }else{
            seachRef.value.setFormValues({
            status:value.filter(item=>item!='')
            })
        }
        }
    }
    
  }
  const searchClick = async (data)=>{
    console.log('查询',data)
    setSearchParams({...data,status:data.status.filter(item=>item!='')})
  }
  /** 初始化 **/
  onMounted(async () => {
    getList()
  })
  
  
  // 根据状态返回该按钮是否显示
  const isShowMainButton = (row, val) => {
    if (val.indexOf(row.status) > -1) {
      return false
    } else {
      return true
    }
  }
  // 点击子表按钮事件
  const detailButtonBaseClick = async (val, item, detailTableObject) => {
    console.log(val, item, detailTableObject)
    if (val == 'export') {
      // 子表导出明细
      handleExportDetail(detailTableObject)
    }
  }
  /** 导出按钮操作 */
  const exportLoading = ref(false) // 导出的加载中
  // 子表导出明细
  const handleExportDetail = async (detailTableObject) => {
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await SuppliperMoldCostDetailApi.exportSupplierMoldCostDetail(
        detailTableObject.params
      )
      download.excel(data, `对账差异【${formatDate(new Date())}】.xlsx`)
    } catch {
    } finally {
      exportLoading.value = false
    }
  }
  
  
  </script>
  