<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search
      :schema="[
        ...PurchaseClaimRequestMain.allSchemas.searchSchema,
        ...PurchaseClaimRequestDetail.allSchemas.searchSchema
      ]"
      @search="setSearchParams"
      @reset="setSearchParams"
    />
  </ContentWrap>
  <!-- 列表头部 -->
  <TableHead
    :HeadButttondata="HeadButttondata"
    @button-base-click="buttonBaseClick"
    :routeName="routeName"
    @updataTableColumns="updataTableColumns"
    @searchFormClick="searchFormClick"
    :allSchemas="PurchaseClaimRequestMain.allSchemas"
    :detailAllSchemas="PurchaseClaimRequestDetail.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>
      <template #action="{ row, $index }">
        <ButtonBase
          :Butttondata="butttondata(row, $index)"
          @button-base-click="buttonTableClick($event, row)"
        />
      </template>
    </Table>
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <BasicForm
    ref="formRef"
    :isOpenSearchTable="false"
    fieldTableColumn="itemCode"
    :rules="PurchaseClaimRequestMainRules"
    :formAllSchemas="PurchaseClaimRequestMain.allSchemas"
    :tableAllSchemas="PurchaseClaimRequestDetail.allSchemas"
    :tableFormRules="PurchaseClaimRequestDetailRules"
    :tableData="tableData"
    :apiUpdate="PurchaseClaimRequestMainApi.updatePurchaseClaimRequestMain"
    :apiCreate="PurchaseClaimRequestMainApi.createPurchaseClaimRequestMain"
    :isBusiness="true"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    :isShowReduceButtonSelection="true"
    @tableSelectionDelete="tableSelectionDelete"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
  />
  <!-- 详情 -->
  <Detail
    ref="detailRef"
    :isBasic="false"
    :allSchemas="PurchaseClaimRequestMain.allSchemas"
    :detailAllSchemas="PurchaseClaimRequestDetail.allSchemas"
    :detailAllSchemasRules="PurchaseClaimRequestDetailRules"
    :apiCreate="PurchaseClaimRequestDetailApi.createPurchaseClaimRequestDetail"
    :apiUpdate="PurchaseClaimRequestDetailApi.updatePurchaseClaimRequestDetail"
    :apiPage="PurchaseClaimRequestDetailApi.getPurchaseClaimRequestDetailPage"
    :apiDelete="PurchaseClaimRequestDetailApi.deletePurchaseClaimRequestDetail"
  />
  <!-- 导入 -->
  <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 {
  PurchaseClaimRequestMain,
  PurchaseClaimRequestMainRules,
  PurchaseClaimRequestDetailRules,
  PurchaseClaimRequestDetail
} from './PurchaseClaimRequestMain.data'
import * as PurchaseClaimRequestMainApi from '@/api/wms/PurchaseClaimRequestMain'
import * as PurchaseClaimRequestDetailApi from '@/api/wms/purchaseClaimRequestDetail'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import { formatDate } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const { loadStart, loadDone } = usePageLoading()
defineOptions({ name: 'purchaseClaimRequestMain' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const businessType = ref()
const tableColumns = ref([
  ...PurchaseClaimRequestMain.allSchemas.tableColumns,
  ...PurchaseClaimRequestDetail.allSchemas.tableMainColumns
])
const { tableObject, tableMethods } = useTable({
  getListApi: PurchaseClaimRequestDetailApi.getPurchaseClaimRequestDetailPage // 分页接口
})

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

const tableData = ref([])

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

// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef, type, row) => {
  nextTick(async () => {
    if (type == 'tableForm') {
      if(formField == 'itemCode'){
        let itemCodes = val.filter(item=>tableData.value.find(item1=>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['itemCode']==item['itemCode']))
        if(val.length==0){
          return
        }
        let newVal = val.filter(item=>!tableData.value.find(item1=>item1['itemCode']==item['itemCode']))
        newVal.forEach(item=>{
          let tfk = JSON.parse(JSON.stringify(tableFormKeys))
          tfk['itemCode'] = item['itemCode']
          tfk['itemName'] = item['itemName']
          tfk['uom'] = item['supplierUom']
          tableData.value.push(tfk)
        }) 
      }
    } 
    const setV = {}
    if(formField === 'supplierCode'){
      setV['supplierCode'] = val[0]['code']
      setV['supplierName'] = val[0]['name']
      tableData.value = []
    }
    formRef.setValues(setV)
  })
}

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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({ hasPermi: `wms:purchaseClaimRequest:create` }), // 新增
  defaultButtons.defaultImportBtn({ hasPermi: `wms:purchaseClaimRequest:import` }), // 导入
  defaultButtons.defaultExportBtn({ hasPermi: `wms:purchaseClaimRequest: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.mainListPlanSubBtn({
      hide: isShowMainButton(row, ['0']),
      hasPermi: `wms:purchaseClaimRequest:sub`
    }), // 提交审批
    defaultButtons.mainListPlanTurBtn({
      hide: isShowMainButton(row, ['3']),
      hasPermi: `wms:purchaseClaimRequest:reject`
    }), // 驳回
    defaultButtons.mainListPlanAppBtn({
      hide: isShowMainButton(row, ['3']),
      hasPermi: `wms:purchaseClaimRequest:agree`
    }), // 审批通过
    defaultButtons.mainListEditBtn({
      hide: isShowMainButton(row, ['0']),
      hasPermi: `wms:purchaseClaimRequest:update`
    }) // 编辑
  ]
}

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'edit') {
    // 编辑
    openForm('update', row)
  } else if (val == 'mainPlanSub') {
    // 提交审批
    handleSub(row.masterId)
  }
  else if (val == 'delete') {
    // 删除
    handleDelete(row.masterId)
  }
}


/** 提交审批按钮操作 */
const handleSub = async (masterId: number) => {
  try {
    // 关闭的二次确认
    await message.confirm(t('ts.是否提交审批所选中数据？'))
    tableObject.loading = true
    // 发起关闭
    await PurchaseClaimRequestMainApi.subPurchaseClaimRequestMain(masterId)
    message.success(t('ts.提交审批成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}


/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, row?: number) => {
  tableData.value = [] // 重置明细数据
  formRef.value.open(type, row)
}
/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  detailRef.value.openDetail(row, titleName, titleValue, 'planDeliverMain')
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    tableObject.loading = true
    // 发起删除
    await PurchaseClaimRequestMainApi.deletePurchaseClaimRequestMain(id)
    tableObject.loading = false
    message.success(t('common.delSuccess'))
    // 刷新列表
    buttonBaseClick('refresh', null)
  } catch {}
}
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    loadStart()
    const excelTitle = ref(route.meta.title)
    const data = await PurchaseClaimRequestMainApi.exportPurchaseClaimRequestMain(
      tableObject.params
    )
    download.excel(data, `【${excelTitle.value}】【${formatDate(new Date())}】.xlsx`)
  } catch {
  } finally {
    loadDone()
  }
}

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

// 添加明细
const handleAddTable = () => {
  tableData.value.push(JSON.parse(JSON.stringify(tableFormKeys)))
}
// 删除明细
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))
}
//为true表示子表数据中存在数量为0的数据
const flag = ref(false)

// 主子数据 提交
const submitForm = async (formType, submitData) => {
  let data = { ...submitData }
  if (data.masterId) {
    data.id = data.masterId
  }
  data.subList = tableData.value // 拼接子表数据参数
  data.subList.forEach((item) => {
    item.toWarehouseCode = data.toWarehouseCode
    item.toLocationCode = data.toLocationCode
  })
  data.businessType = businessType.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) {
    formRef.value.formLoading = false
    return message.warning('物料代码重复')
  }
  data.subList.forEach((obj) => {
    if (obj.claimQty == 0) {
      message.error(`索赔数量不能为0!`)
      flag.value = true
      return
    }
    if (obj.claimAmount == 0) {
      message.error(`索赔金额不能为0!`)
      flag.value = true
      return
    }
  })
  if (flag.value) {
    return
  }
  formRef.value.formLoading = true
  try {
    if (formType === 'create') {
      await PurchaseClaimRequestMainApi.createPurchaseClaimRequestMain(data)
      message.success(t('common.createSuccess'))
    } else {
      await PurchaseClaimRequestMainApi.updatePurchaseClaimRequestMain(data)
      message.success(t('common.updateSuccess'))
    }
    formRef.value.dialogVisible = false
    // 刷新当前列表
    if (formType === 'create') {
      getList()
    } else {
      buttonBaseClick('refresh', null)
    }
  } finally {
    formRef.value.formLoading = 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 PurchaseClaimRequestMainApi.importTemplate()
})
</script>
