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

    <!-- 列表头部 -->
    <TableHead
      :HeadButttondata="HeadButttondata"
      @button-base-click="buttonBaseClick"
      :routeName="routeName"
      @updataTableColumns="updataTableColumns"
      @searchFormClick="searchFormClick"
      :allSchemas="SaleShipmentMain.allSchemas"
      :detailAllSchemas="SaleShipmentDetail.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>

  <!-- 表单弹窗：添加/修改 -->
  <BasicForm
    ref="basicFormRef"
    :isOpenSearchTable="true"
    fieldTableColumn="soLine"
    @success="getList"
    :rules="SaleShipmentMainRules"
    :formAllSchemas="SaleShipmentMain.allSchemas"
    :tableAllSchemas="SaleShipmentDetail.allSchemas"
    :tableFormRules="SaleShipmentDetailRules"
    :tableData="tableData"
    :apiUpdate="SaleShipmentMainApi.updateSaleShipmentMain"
    :apiCreate="SaleShipmentMainApi.createSaleShipmentMain"
    :isBusiness="true"
    fromeWhere="SaleShipmentRequestMain"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    :isShowReduceButtonSelection="true"
    @tableSelectionDelete="tableSelectionDelete"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
    :isShowButton = isShowButton
  />
 <!-- 详情 -->
 <Detail
    ref="detailRef"
    :isBasic="false"
    :allSchemas="SaleShipmentMain.allSchemas"
    :detailAllSchemas="SaleShipmentDetail.allSchemas"
    :detailAllSchemasRules="SaleShipmentDetailRules"
    :apiCreate="SaleShipmentDetailApi.createSaleShipmentDetail"
    :apiUpdate="SaleShipmentDetailApi.updateSaleShipmentDetail"
    :apiPage="SaleShipmentDetailApi.getSaleShipmentDetailPage"
    :apiDelete="SaleShipmentDetailApi.deleteSaleShipmentDetail"
    fromeWhere="SaleShipmentRequestDetail"
    @searchTableSuccessDetail="searchTableSuccessDetail"
    :detailButtonIsShowAdd="trueFalse"
    :detailButtonIsShowDelete="trueFalse"
    @detailOpenForm="detailOpenForm"
  />

  <!-- 导入 -->
  <ImportForm ref="importFormRef" url="/wms/sale-shipment-main-request/import" :importTemplateData="importTemplateData" @success="importSuccess" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { SaleShipmentMain,SaleShipmentMainRules,SaleShipmentDetail,SaleShipmentDetailRules } from './saleShipmentMain.data'
import * as SaleShipmentMainApi from '@/api/wms/saleShipmentMain'
import * as SaleShipmentDetailApi from '@/api/wms/saleShipmentDetail'
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 { formatDate } from '@/utils/formatTime'
defineOptions({ name: 'SaleShipmentMain' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const tableColumns = ref([...SaleShipmentMain.allSchemas.tableColumns,...SaleShipmentDetail.allSchemas.tableMainColumns])

//定义  展示子表数据时是否显示新增/修改/删除按钮
const trueFalse = ref(false)

// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef, type, row ) => {
  nextTick(() => {
    if (type == 'tableForm') {
      if(formField == 'soLine') {
        let itemCodes = val.filter(item=>tableData.value.find(item1=>item1['soLine']==item['lineNumber']&&item1['soNumber']==item['number']&&item1['itemCode']==item['itemCode']))
        if(itemCodes.length>0){
          itemCodes = itemCodes.map(item=>(item.itemCode))
          message.warning(`物料${itemCodes.join(',')}已经存在`)
        }
        val = val.filter(item=>!tableData.value.find(item1=>item1['soLine']==item['lineNumber']&&item1['soNumber']==item['number']&&item1['itemCode']==item['itemCode']))
        if(val.length==0) return
        val.forEach(item=>{
          const newRow = JSON.parse(JSON.stringify({...tableFormKeys,...item}))
          newRow['soLine'] = item['lineNumber']
          newRow['soNumber'] = item['number']
          newRow['itemCode'] = item['itemCode']
          newRow['projectCode'] = item['projectCode']
          newRow['uom'] = item['uom']
          tableData.value.push(newRow)
        })

      }else if(formField == 'fromLocationCode'){
        row['fromLocationCode'] = val[0]['defaultLocationCode']
      }else{
        row[formField] = val[0][searchField]
      }
    }else {
      const setV = {}
      setV[formField] = val[0][searchField]
      if(formField == 'CustomerCode') {
        setV['CustomerCode'] = val[0]['CustomerCode']
      } else {
        setV[formField] = val[0][searchField]
      }
      formRef.setValues(setV)
    }
  })
}

// 查询页面返回——详情
const searchTableSuccessDetail = (formField, searchField, val, formRef ) => {
  nextTick(() => {
    const setV = {}
    if(formField == 'soLine') {
      setV['soLine'] = val[0]['lineNumber']
      setV['soNumber'] = val[0]['number']
      setV['itemCode'] = val[0]['itemCode']
      setV['projectCode'] = val[0]['projectCode']
      setV['uom'] = val[0]['uom']
    }else  if(formField == 'fromLocationCode') {
      setV['fromLocationCode'] = val[0]['defaultLocationCode']
    }else {
      setV[formField] = val[0][searchField]
    }
    formRef.setValues(setV)
  })
}

const isShowButton = ref(true)

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

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

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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({hasPermi:'wms:sale-shipment-main-request:create'}), // 新增
  defaultButtons.defaultImportBtn({hasPermi:'wms:sale-shipment-main-request:import'}), // 导入
  defaultButtons.defaultExportBtn({hasPermi:'wms:sale-shipment-main-request:export'}), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null), // 设置
  // {
  //   label: '自定义扩展按钮',
  //   name: 'zdy',
  //   hide: false,
  //   type: 'primary',
  //   icon: 'Select',
  //   color: ''
  // },
]

// 头部按钮事件
const buttonBaseClick = (val, item) => {
  if (val == 'add') { // 新增
    openForm('create')
  } else 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 isShowMainButton = (row,val) => {
  if (val.indexOf(row.status) > -1) {
    return false
  } else {
    return true
  }
}

// 列表-操作按钮
const butttondata = (row,$index) => {
  const findIndex = row['masterId']?tableObject.tableList.findIndex(item=>item['masterId'] == row['masterId']):-1
  if(findIndex>-1&&findIndex<$index){
    return []
  }
  return [
    defaultButtons.mainListEditBtn({hide:isShowMainButton(row,['1','4']),hasPermi:'wms:sale-shipment-main-request:update'}), // 编辑
    defaultButtons.mainListCloseBtn({hide:isShowMainButton(row,['1','2','3','4','6']),hasPermi:'wms:sale-shipment-main-request:close'}), // 关闭
    defaultButtons.mainListReAddBtn({hide:isShowMainButton(row,['4','5']),hasPermi:'wms:sale-shipment-main-request:reAdd'}), //重新添加
    defaultButtons.mainListSubmitBtn({hide:isShowMainButton(row,['1']),hasPermi:'wms:sale-shipment-main-request:submit'}), // 提交审批
    defaultButtons.mainListTurnDownBtn({hide:isShowMainButton(row,['2']),hasPermi:'wms:sale-shipment-main-request:refused'}), // 驳回
    defaultButtons.mainListApproveBtn({hide:isShowMainButton(row,['2']),hasPermi:'wms:sale-shipment-main-request:agree'}), // 审批通过
    defaultButtons.mainListHandleBtn({hide:isShowMainButton(row,['3']),hasPermi:'wms:sale-shipment-main-request:handle'}), // 处理
    defaultButtons.mainListAbortBtn({hide:isShowMainButton(row,['8']),hasPermi:'wms:sale-shipment-main-request:abort'}), // 终止
    // defaultButtons.mainListDeleteBtn({hasPermi:'wms:sale-shipment-main-request:delete'}), // 删除
  ]
}
const tableData = ref([])


// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'mainClose') { // 关闭
    await message.confirm('确认要关闭吗？')
    tableObject.loading = true
    SaleShipmentMainApi.close(row.masterId).then(() => {
      message.success(t('common.updateSuccess'))
      tableObject.loading = false
      buttonBaseClick('refresh',null)
    }).catch(err => {
      tableObject.loading = false
      console.log(err)
    })
  } else if (val == 'mainReAdd') { // 重新添加
    await message.confirm('确认要重新添加吗？')
    tableObject.loading = true
    SaleShipmentMainApi.reAdd(row.masterId).then(() => {
      message.success(t('common.updateSuccess'))
      tableObject.loading = false
      buttonBaseClick('refresh',null)
    }).catch(err => {
      tableObject.loading = false
      console.log(err)
    })
  } else if (val == 'mainSubmit') { // 提交审批
    await message.confirm('确认要提交审批吗？')
    tableObject.loading = true
    SaleShipmentMainApi.submit(row.masterId).then(() => {
      message.success(t('common.updateSuccess'))
      tableObject.loading = false
      buttonBaseClick('refresh',null)
    }).catch(err => {
      tableObject.loading = false
      console.log(err)
    })
  } else if (val == 'mainTurnDown') { // 驳回
    await message.confirm('确认要驳回吗？')
    tableObject.loading = true
    SaleShipmentMainApi.refused(row.masterId).then(() => {
      message.success(t('common.updateSuccess'))
      tableObject.loading = false
      buttonBaseClick('refresh',null)
    }).catch(err => {
      tableObject.loading = false
      console.log(err)
    })
  } else if (val == 'mainApprove') { // 审批通过
    await message.confirm('确认要审批通过吗？')
    tableObject.loading = true
    SaleShipmentMainApi.agree(row.masterId).then(() => {
      message.success(t('common.updateSuccess'))
      tableObject.loading = false
      buttonBaseClick('refresh',null)
    }).catch(err => {
      tableObject.loading = false
      console.log(err)
    })
  } else if (val == 'mainHandle') { // 处理
    await message.confirm('确认要处理吗？')
    tableObject.loading = true
    SaleShipmentMainApi.handle(row.masterId).then(() => {
      message.success(t('common.updateSuccess'))
      tableObject.loading = false
      buttonBaseClick('refresh',null)
    }).catch(err => {
      tableObject.loading = false
      console.log(err)
    })
  } else if (val == 'mainAbort') { // 废弃
    await message.confirm('确认要终止吗？')
    tableObject.loading = true
    SaleShipmentMainApi.abort(row.masterId).then(() => {
      message.success(t('common.updateSuccess'))
      tableObject.loading = false
      buttonBaseClick('refresh',null)
    }).catch(err => {
      tableObject.loading = false
      console.log(err)
    })
  }else if (val == 'edit') { // 编辑
    openForm('update', row)
  } else if (val == 'delete') { // 删除
    handleDelete(row.id)
  }
}


/**
 * 详情 编辑页面打开
 * @param row
 */
 const detailOpenForm = (type) => {

}

/** 添加/修改操作 */
const basicFormRef = ref()
const openForm = (type: string, row?: any) => {
  tableData.value = []
  basicFormRef.value.open(type, row)
}


// 主子数据 提交
const submitForm = async (formType, submitData) => {
  let data = {...submitData}
  if(data.masterId){
    data.id = data.masterId
  }
  data.subList = tableData.value // 拼接子表数据参数
  let isExist = false
  tableData.value.forEach(item => {
   let rs =  tableData.value.filter(filterItem => (filterItem.itemCode == item.itemCode))
   if(rs.length > 1) isExist = true
  })
  if (isExist) {
    // basicFormRef.value.formLoading = false
    return message.warning('物料代码重复')
  }
  basicFormRef.value.formLoading = true
  try {
    if (formType === 'create') {
      if(tableData.value.length <= 0){
      message.warning(`子表明细不能为空!`)
      basicFormRef.value.formLoading = false
      return;
  }
      await SaleShipmentMainApi.createSaleShipmentMain(data)
      message.success(t('common.createSuccess'))
    } else {
      await SaleShipmentMainApi.updateSaleShipmentMain(data)
      message.success(t('common.updateSuccess'))
    }
    basicFormRef.value.dialogVisible = false
    // 刷新当前列表
    if (formType === 'create') {
      getList()
    }else{
      buttonBaseClick('refresh',null)
    }
  } finally {
    basicFormRef.value.formLoading = false
  }
}

/**
  * tableForm方法
*/
const tableFormKeys = {}
SaleShipmentDetail.allSchemas.tableFormColumns.forEach(item => {
  tableFormKeys[item.field] = item.default ? item.default : ''
})

// 添加明细
const handleAddTable = () => {
  let tableForm = JSON.parse(JSON.stringify(tableFormKeys))
    tableData.value.push(tableForm)
  }
// 删除明细
const handleDeleteTable = (item, index) => {
  let itemIndex = tableData.value.indexOf(item)
  if(itemIndex>-1){
    tableData.value.splice(itemIndex, 1)
  }
}
const tableSelectionDelete = (selection) => {
  tableData.value = tableData.value.filter(item => !selection.includes(item))
}

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

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SaleShipmentMainApi.deleteSaleShipmentMain(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    buttonBaseClick('refresh',null)
  } catch {}
}

/** 导出按钮操作 */
const exportLoading = ref(false) // 导出的加载中
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SaleShipmentMainApi.exportSaleShipmentMain(tableObject.params)
    download.excel(data, `【${route.meta.title}】【${formatDate(new Date())}】.xlsx`)
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导入 */
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() // 刷新当前列表
}

/** 初始化 **/
onMounted(async () => {
  getList()
  importTemplateData.templateUrl = await SaleShipmentMainApi.importTemplate()
})

</script>
