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

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

  <!-- 列表 -->
  <ContentWrap>
    <Table
      ref="tableRef"
      :selection="true"
      :selectionColor="true"
      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"
      @getSelectionRows="getSelectionRows"
    >
      <template #number="{ row }">
        <el-button type="primary" link @click="openDetail(row, '单据号', row.number)">
          <span>{{ row.number }}</span>
        </el-button>
      </template>
      <template #differencePrice="{ row }">
        <span :class="{ 'red-text': row.differencePrice != 0 }">{{
          Number(row.differencePrice).toFixed(5)
        }}</span>
      </template>
      <template #action="{ row, $index }">
        <ButtonBase
          :Butttondata="butttondata(row, $index)"
          @button-base-click="buttonTableClick($event, row)"
        />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗:添加/修改 -->
  <BasicForm
    ref="formRef"
    @success="getList"
    :isOpenSearchTable="true"
    fieldTableColumn="poLine"
    :showSearchTableQueryFields="['poLine']"
    :rules="SupplierinvoiceRequestMainRules"
    :formAllSchemas="SupplierinvoiceRequestMain.allSchemas"
    :searchTableParams="searchTableParams"
    :tableAllSchemas="SupplierinvoiceRequestDetail.allSchemas"
    :tableFormRules="SupplierinvoiceRequestDetailRules"
    :tableData="tableData"
    :sumFormDataByForm="
      (
        formRef,
        formModel,
        tableData,
        formType,
        originFormModel,
        updateOriginFormModel,
        sumFormDataHandle1
      ) => {
        const {
          taxRate = 0,
          amount = 0,
          taxAmount = 0,
          beforeTaxAmount = 0,
          totalTaxAmount = 0,
          discountAmount1 = 0,
          beforeTaxDiffAmount = 0,
          taxAmountDiff = 0,
          rebateTax=0,
        } = formModel
        // 2、系统税额:每条数据的合同价格X可开票数量,计算结果取两位小数之后*税率的计算结果,再保留2位。所有子表数据再求和
        if (formType == 'update') {
          // 编辑
          console.log('taxRate', taxRate)
          console.log('originFormModel', originFormModel.taxRate)
          console.log('taxAmount', taxAmount)
          if (taxRate != originFormModel.taxRate) {
            if (originFormModel) {
              sumFormDataHandle1()
            }
            updateOriginFormModel(formModel)
          }
          formRef.value.setValues({
            afterTaxAmount: amount + taxAmount, // 3、系统价税合计:系统未税金额+系统税额-索赔总额
            adTaxAmount: beforeTaxAmount + totalTaxAmount, //6、价税合计金额:未税金额+税额
            beforeTaxDiffAmount: beforeTaxAmount - amount, //未税差额:未税金额-系统未税金额
            taxAmountDiff: totalTaxAmount - taxAmount, // 税额差异:税额-系统税额
            totalTaxDiffAmount: beforeTaxDiffAmount + taxAmountDiff, // 价税合计差额=未税差额+税额差异
            rebateTax:Number(Number(discountAmount1*taxRate*0.01).toFixed(2)),
            rebateTotal:rebateTax+discountAmount1
          })
        } else if (formType == 'create') {
          // 新增
          let taxAmount_ = taxAmount
          if (taxRate != originFormModel.taxRate) {
            taxAmount_ = tableData.reduce(
              (prev, item) =>
                prev +
                Number(
                  Number(
                    taxRate *
                      0.01 *
                      Number(Number(item['singlePrice'] * item['invoicableQuantity']).toFixed(2))
                  ).toFixed(2)
                ),
              0
            )
            updateOriginFormModel(formModel)
          }
          formRef.value.setValues({
            taxAmount: taxAmount_,
            afterTaxAmount: amount + taxAmount, // 3、系统价税合计:系统未税金额+系统税额-索赔总额
            adTaxAmount: beforeTaxAmount + totalTaxAmount, //6、价税合计金额:未税金额+税额
            beforeTaxDiffAmount: beforeTaxAmount - amount, //未税差额:未税金额-系统未税金额
            taxAmountDiff: totalTaxAmount - taxAmount, // 税额差异:税额-系统税额
            totalTaxDiffAmount: beforeTaxDiffAmount + taxAmountDiff, // 价税合计差额=未税差额+税额差异
            rebateTax:Number(Number(discountAmount1*taxRate*0.01).toFixed(2)),
            rebateTotal:rebateTax+discountAmount1
          })
        }
      }
    "
    :sumFormDataByTableCustom="
      (formRef, formModel, tableData) => {
        // 1、系统未税金额: 合同价格X可开票数量。每条数据的合同价格X可开票数量,计算结果取两位小数之后,求和
        const { taxRate = 0 } = formModel
        const sumObject = {
          amount: tableData.reduce(
            (prev, item) =>
              prev + Number(Number(item['singlePrice'] * item['invoicableQuantity']).toFixed(2)),
            0
          ),
          taxAmount: tableData.reduce(
            (prev, item) =>
              prev +
              Number(
                Number(
                  taxRate *
                    0.01 *
                    Number(Number(item['singlePrice'] * item['invoicableQuantity']).toFixed(2))
                ).toFixed(2)
              ),
            0
          )
        }
        formRef.value.setValues(sumObject)
      }
    "
    :apiUpdate="SupplierinvoiceRequestMainApi.updateSupplierinvoiceRequestMain"
    :apiCreate="SupplierinvoiceRequestMainApi.createSupplierinvoiceRequestMain"
    :isBusiness="true"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    :isShowReduceButtonSelection="true"
    @tableSelectionDelete="tableSelectionDelete"
    @searchTableSuccess="searchTableSuccess"
    @submitForm="submitForm"
    @sumFormDataHandle="sumFormDataHandle"
    @onChange="onChange"
    @inputNumberChange="inputNumberChange"
  >
    <template #selectionsActionspoLine="{ selections }">
      <div style="text-align: left; margin-right: 10px">
        系统未税金额:{{
          Number(
            selections.reduce(
              (prev, item) =>
                prev +
                Number(
                  Number(
                    Number(Number(item['purchasePrice']).toFixed(5)) * item['invoicableQuantity']
                  ).toFixed(2)
                ),
              0
            )
          ).toFixed(2)
        }}
      </div>
    </template>
    
    <!-- <template #foorter>
    <div style="text-align: left">
      {{ basicFormFooter }}
    </div>
  </template> -->
    <template v-slot="{ row }">
      <el-input
        :disabled="true"
        :class="{ 'is-red': row['singlePrice'] - row['purchasePrice'] > 0 }"
        :modelValue="(row['singlePrice'] - row['purchasePrice']).toFixed(5)"
      />
    </template>
    <template #table>
      <div >
        <div style="padding-left: 10px;border-left: 6px solid #409eff;margin:10px 0px;font-size: 16px;font-weight: bold;">索赔明细</div>
        <!-- <Table
          :columns="ClaimDetails.allSchemas.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"
          style='width: calc(100% - 32px);'
        /> -->
        <div
          style="border: 1px solid #dedede;
          border-radius: 8px;
          padding: 10px;
          width: calc(100% - 32px);
          display: flex;">
          <TableForm
            ref="tableFormRef"
            class="w-[100%]"
            :tableFields="ClaimDetails.allSchemas.tableFormColumns"
            :tableData="claimDetailsList"
            :isShowButton="false"
            :isShowReduceButton="false"
          />
        </div>
       
       
      </div>
    </template>
  </BasicForm>

  <!-- 财务通过窗口 finance_mainPlanSub -->
  <BasicForm
    ref="formFinanceRef"
    :rules="SupplierinvoiceRequestFinanceRules"
    :formAllSchemas="SupplierinvoiceRequestFinance.allSchemas"
    :isBusiness="false"
    :footButttondata="undefined"
    @success="submitFormFinance"
  />
  <!-- 采购通过窗口-->
  <BasicForm
    ref="formPurchasePassRef"
    :rules="PurchasePassRules"
    :formAllSchemas="PurchasePass.allSchemas"
    :isBusiness="false"
    :footButttondata="undefined"
    @success="submitPurchasePass"
  />
  <!-- 详情 -->
  <!-- :apiUpdate="SupplierinvoiceRequestDetailApi.updateSupplierinvoiceRequestDetail" -->
  <Detail
    ref="detailRef"
    :isOpenSearchTable="true"
    fieldTableColumn="poLine"
    :annexTable="detailAnnexTable"
    direction="horizontal"
    :column="3"
    :annexAlias="{
      hidden: true,
      label: t('ts.其他附件')
    }"
    :otherHeadButttonData="[
      {
        label: t('ts.打印明细'),
        name: 'printing',
        hide: false,
        type: 'primary',
        // icon: 'ep:operation',
        color: '',
        float: 'left',
        hasPermi: ''
      },
      {
        label: t('ts.打印全部发货单'),
        name: 'printing-all',
        hide: false,
        type: 'primary',
        // icon: 'ep:operation',
        color: '',
        float: 'left',
        hasPermi: ''
      },
      {
        label: t('ts.导出明细'),
        name: 'export-detail',
        hide: false,
        type: 'primary',
        // icon: 'ep:operation',
        color: '',
        float: 'left',
        hasPermi: ''
      }
    ]"
    :buttondataTable="[
      {
        label: t('ts.打印'),
        name: 'print',
        hide: true,
        type: 'primary',
        // icon: 'ep:operation',
        color: '',
        float: 'left',
        link: true, // 文本展现按钮
        hasPermi: ''
      }
    ]"
    :sumFormDataByForm="
      (formRef, formModel) => {
        const { singlePrice = 0, purchasePrice = 0 } = formModel
        formRef.value.setValues({
          differencePrice: Number((Number(singlePrice) - Number(purchasePrice)).toFixed(5))
        })
      }
    "
    :isBasic="false"
    :allSchemas="SupplierinvoiceRequestDetailMain.allSchemas"
    :detailAllSchemas="SupplierinvoiceRequestDetail.allSchemas"
    :detailAllSchemasRules="SupplierinvoiceRequestDetailRules"
    :searchTableParams="searchTableParams"
    :apiCreate="SupplierinvoiceRequestDetailApi.createSupplierinvoiceRequestDetail"
    :apiPage="SupplierinvoiceRequestDetailApi.getSupplierinvoiceRequestDetailPage"
    :apiDelete="SupplierinvoiceRequestDetailApi.deleteSupplierinvoiceRequestDetail"
    :Echo="Echo"
    :detailButtonIsShowEdit="true"
    :detailButtonIsShowAddStatusArray="detailButtonIsShowAddStatusArray"
    :detailButtonIsShowDelete="true"
    :detailButtonIsShowAdd="true"
    @buttonBaseClick="detailButtonBaseClick"
    @tableFormButton="tableFormButton"
    :mainSubmitCreateApi="true"
    @searchTableSuccessDetail="searchTableSuccessDetail"
    @handleMainFefresh="handleMainFefresh"
    @detailOpenForm="detailOpenForm"
    @detailBasicFormOnChange="detailBasicFormOnChange"
    @handleSubmitForm="handleDetailSubmitForm"
  >
    <!-- 价税合计尾差 -->
    <template #Descriptions_totalTaxDiffAmount="{ row }">
      <span>{{row['totalTaxDiffAmount']}}<span class="red-text"> (含返利合计:{{ row['rebateTotal'] }})</span></span>
    </template>
    <!-- 未税尾差 -->
    <template #Descriptions_beforeTaxDiffAmount="{ row }">
      <span>{{row['beforeTaxDiffAmount']}}<span class="red-text"> (含返利未税:{{ row['discountAmount1'] }})</span></span>
    </template>
    <!-- 税额尾差 -->
    <template #Descriptions_taxAmountDiff="{ row }">
      <span>{{row['taxAmountDiff']}}<span class="red-text"> (含返利税额:{{ row['rebateTax'] }})</span></span>
    </template>
    <template #differencePrice="{ row }">
      <span :class="{ 'red-text': row.differencePrice != 0 }">{{ row.differencePrice }}</span>
    </template>
  </Detail>

  <!-- 导入 -->
  <ImportForm
    ref="importFormRef"
    url="/wms/supplierinvoice-request-main/import"
    :importTemplateData="importTemplateData"
    @success="importSuccess"
    :updateIsDisable="true"
    :coverIsDisable="true"
    :mode="2"
  />
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
// 供应商发票申请
import download from '@/utils/download'
import TableForm from '@/components/TableForm/src/TableForm.vue'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import {
  SupplierinvoiceRequestMain,
  SupplierinvoiceRequestMainRules,
  SupplierinvoiceRequestDetail,
  SupplierinvoiceRequestDetailRules,
  SupplierinvoiceRequestFinance,
  SupplierinvoiceRequestFinanceRules,
  PurchasePass,
  PurchasePassRules,
  SupplierinvoiceRequestDetailMain,
  ClaimDetails
} from './supplierinvoiceRequestMain.data'
import * as SupplierinvoiceRequestMainApi from '@/api/wms/supplierinvoiceRequestMain'
import * as SupplierinvoiceRequestDetailApi from '@/api/wms/supplierinvoiceRequestDetail'
import * as PurchaseClaimRequestDetailApi from '@/api/wms/purchaseClaimRequestDetail'

import * as defaultButtons from '@/utils/disposition/defaultButtons'
import * as SupplierApi from '@/api/wms/supplier'
import { Supplier } from '../../../basicDataManage/supplierManage/supplier/supplier.data'
import { getAccessToken } from '@/utils/auth'
import { ElMessageBox } from 'element-plus'
import { getJmreportBaseUrl } from '@/utils/systemParam'
import { accountantFormart } from '@/utils/formatter'

import { formatDate } from '@/utils/formatTime'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const { loadStart, loadDone } = usePageLoading()
defineOptions({ name: 'SupplierinvoiceRequestMain' })

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

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

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

// 查询列表页面参数设置
const searchTableParams = ref([
  {
    formField: 'supplierCode',
    searchTableTitle: t('ts.供应商信息'),
    searchTableAllSchemas: Supplier.allSchemas,
    searchTablePage: SupplierApi.getSupplierPage
  }
])
const formPurchasePassRef = ref()
const searchList = (model) => {
  selectionRows.value = []
  let model1 = {
    ...model,
    statuss: model.status.join(',') ? model.status.join(',') : ''
  }
  delete model1.status
  setSearchParams(model1)
}
const selectionRows = ref<any>([])
const tableRef = ref()
const getSelectionRows = (currentPage, currentPageSelectionRows) => {
  console.log('getSelectionRows', currentPage, currentPageSelectionRows)
  const currentRows = selectionRows.value.find((item) => item.currentPage == currentPage)
  if (currentRows) {
    currentRows.selectionRows = currentPageSelectionRows
  } else {
    selectionRows.value.push({
      currentPage,
      selectionRows: currentPageSelectionRows
    })
  }
}
const handleMainFefresh = () => {
  getList()
}

const searchTableSuccessDetail = async (
  formField,
  searchField,
  val,
  formRef,
  searchTableFormModel
) => {
  console.log('详情', formField, searchField, val, formRef, searchTableFormModel)
  val.forEach((item) => {
    item.deliveryDate = item['prhRcpDate']
    item.arrivalQty = item['prhRcvd']
  })
  await SupplierinvoiceRequestDetailApi.createSupplierinvoiceRequestDetail({
    masterId: searchTableFormModel.masterId,
    subList: val
  })
  detailRef.value.updateList()
  getList()
}

// const basicFormFooter = computed(()=>{
//   let formModel = formRef.value?.formRef?.formModel
//   if(formModel){
//     let price1 = formModel.amount+formModel.discountAmount+formModel.discountAmount1
//     let price2 = formModel.taxAmount+formModel.adjustingTaxAmount
//     return `合计金额:未税金额=${accountantFormart(undefined,undefined,price1)};税额=${accountantFormart(undefined,undefined,price2)};价税合计金额=${accountantFormart(undefined,undefined,price1+price2)};`
//   }
//   return `合计金额`

// })


const detailData = ref()
const detailOpenForm = (type, row)=>{
  detailData.value = row
}
const detailBasicFormOnChange  =  (field, cur)  => {
  console.log('detailBasicFormOnChange',field, cur)
  if (field == 'invoicableQuantity') {
    // 负数:默认默认开票数~0
    // 正数:0~默认开票数
    if(detailData.value.maxInvoicableQuantity){
      if(detailData.value.maxInvoicableQuantity>0){
        if(cur<0||cur>detailData.value.maxInvoicableQuantity){
          message.error(t('ts.可开票数量范围是')+`:0~${detailData.value.maxInvoicableQuantity}`)
        }
      }else{
        if(cur>0||cur<detailData.value.maxInvoicableQuantity){
          message.error(t('ts.可开票数量范围是')+`:${detailData.value.maxInvoicableQuantity}~0`)
        }
      }
    }
  }
}
const handleDetailSubmitForm = async (formType, data) => {
  if (formType === 'update') {
    console.log('handleDetailSubmitForm',data)
    if(data.invoicableQuantity==0){
      message.error(t('ts.可开票数量不能为0'))
      return
    }else if(data.maxInvoicableQuantity>0){
      if(data.invoicableQuantity<0||data.invoicableQuantity>data.maxInvoicableQuantity){
        message.error(t('ts.可开票数量范围是')+`:0~${data.maxInvoicableQuantity}`)
        return
      }
    }else{
      if(data.invoicableQuantity>0||data.invoicableQuantity<data.maxInvoicableQuantity){
        message.error(t('ts.可开票数量范围是')+`:${data.maxInvoicableQuantity}~0`)
        return
      }
    }
    await SupplierinvoiceRequestDetailApi.updateSupplierinvoiceRequestDetail(data)
    message.success(t('common.updateSuccess'))
  }
  detailRef.value.submitUpdateList()
}
const inputNumberChange = (field, index, row, val) => {
  if (field == 'invoicableQuantity') {
    // 负数:默认默认开票数~0
    // 正数:0~默认开票数
    console.log('inputNumberChange',field, index, row, val)
    if(row.maxInvoicableQuantity>0){
      if(row.invoicableQuantity<0||row.invoicableQuantity>row.maxInvoicableQuantity){
        message.error(t('ts.可开票数量范围是')+`:0~${row.maxInvoicableQuantity}`)
      }
    }else{
      if(row.invoicableQuantity>0||row.invoicableQuantity<row.maxInvoicableQuantity){
        message.error(t('ts.可开票数量范围是')+`:${row.maxInvoicableQuantity}~0`)
      }
    }
  }
}
const onChange = (field, cur) => {
  console.log('onChange',field)
  if(field=='orderType'){
    tableData.value = []
  }
}

// 查询页面返回
const searchTableSuccess = (formField, searchField, val, searchFormRef, type, row) => {
  nextTick(() => {
    if (type == 'tableForm') {
      // 明细查询页赋值
      val.forEach((item) => {
        if (
          tableData.value.find(
            (item1) =>
              item1['recvBillNum'] == item['recvBillNum'] && item1['poLine'] == item['poLine']
          )
        )
          return

        const newRow = { ...row }
        newRow[formField] = item[searchField]
        if (formField == 'poLine') {
          newRow['id'] = item['id']
          newRow['poNumber'] = item['poNumber']
          newRow['poLine'] = item['poLine']
          newRow['tax'] = item['tax']
          newRow['projectCode'] = item['projectCode']
          newRow['billType'] = item['billType']
          newRow['recvBillNum'] = item['recvBillNum']
          newRow['asnBillNum'] = item['asnBillNum']
          newRow['supplierCode'] = item['supplierCode']
          newRow['singlePrice'] = item['purchasePrice'] //单价默认值 = 采购价格
          newRow['purchasePrice'] = item['purchasePrice']
          newRow['maxInvoicableQuantity'] = item['invoicableQuantity']
          newRow['invoicableQuantity'] = item['invoicableQuantity']
          newRow['itemCode'] = item['itemCode']
          newRow['deliveryDate'] = item['prhRcpDate']
          newRow['arrivalQty'] = item['prhRcvd']
          newRow['id'] = item['id']
          newRow['currency'] = item['currency']
        }
        tableData.value.push(newRow)
      })
    } else {
      // 切换供应商代码
    console.log(11,val[0][searchField])
    console.log(11,searchFormRef.formModel.supplierCode)
      if (
        formField == 'supplierCode' &&
        val[0][searchField] != searchFormRef.formModel.supplierCode
      ) {
        tableData.value = []
      }
      if (formField == 'supplierCode') {
        claimDetails(val[0][searchField])
      }
      // 切换订单类型
      if (formField == 'orderType' && val[0][searchField] != searchFormRef.formModel.orderType) {
        tableData.value = []
      }
      const setV = {}
      setV[formField] = val[0][searchField]
      searchFormRef.setValues(setV)
    }
  })
}
const Echo = []

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

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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({ hasPermi: 'wms:supplierinvoice-request-main:create' }), // 新增
  defaultButtons.defaultImportBtn({ hasPermi: 'wms:supplierinvoice-request-main:import' }), // 导入
  defaultButtons.defaultExportBtn({ hasPermi: 'wms:supplierinvoice-request-main:export' }), // 导出
  defaultButtons.mainLisSelectiontPointBtn(null), // 批量打印
  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 == 'selection_point') {
    // 批量打印
    handleSelectionPoint()
  } 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) => {
  return [
    // defaultButtons.mainListPurchasePlanOpeBtn({ hide: isShowMainButton(row, ['9']) ,hasPermi: 'wms:supplierinvoice-request-main:open'}), // 打开
    defaultButtons.mainListPlanSubBtn({
      hide: isShowMainButton(row, ['1', '6']),
      hasPermi: 'wms:supplierinvoice-request-main:sub'
    }), // 提交审批
    {
      label: t('ts.查看明细'),
      name: 'open_detail',
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: '',
      link: true // 文本展现按钮
    },
    {
      label: t('ts.采购通过'),
      name: 'purchase_mainPlanSub',
      hide: !(!isShowMainButton(row, ['2']) && row.currentIsProcurementCreator == true),
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: 'wms:supplierinvoice-request-main:app',
      link: true // 文本展现按钮
    },
    {
      label: t('ts.采购驳回'),
      name: 'purchase_mainPlanTur',
      hide: !(!isShowMainButton(row, ['2']) && row.currentIsProcurementCreator == true),
      type: 'danger',
      color: '',
      link: true, // 文本展现按钮
      hasPermi: 'wms:supplierinvoice-request-main:rej'
    },
    {
      label: t('ts.供应商确认'),
      name: 'invoice_sent_out',
      hide: isShowMainButton(row, ['3', '7']),
      type: 'danger',
      color: '',
      link: true, // 文本展现按钮
      hasPermi: 'wms:supplierinvoice-request-main:invoiceSentOut'
    },
    {
      label: t('ts.财务通过'),
      name: 'finance_mainPlanSub',
      hide: isShowMainButton(row, ['4']),
      type: 'primary',
      icon: '',
      color: '',
      hasPermi: 'wms:supplierinvoice-request-main:financeApp',
      link: true // 文本展现按钮
    },
    {
      label: t('ts.财务驳回'),
      name: 'finance_mainPlanTur',
      hide: isShowMainButton(row, ['4']),
      type: 'danger',
      color: '',
      link: true, // 文本展现按钮
      hasPermi: 'wms:supplierinvoice-request-main:financeRej'
    },
    defaultButtons.mainListEditBtn({
      hasPermi: 'wms:supplierinvoice-request-main:update',
      hide: isShowMainButton(row, ['1', '3', '6', '7'])
    }), // 编辑
    // defaultButtons.mainListPurchasePlanCloBtn({ hasPermi: 'wms:supplierinvoice-request-main:close' ,hide: isShowMainButton(row, ['1','3','6','7']) }), // 关闭
    {
      label: t('ts.作废'),
      name: 'repeal',
      hide: isShowMainButton(row, ['1', '3', '6', '7']),
      type: 'danger',
      color: '',
      link: true, // 文本展现按钮
      hasPermi: 'wms:supplierinvoice-request-main:repeal'
    },
    // defaultButtons.mainListDeleteBtn({hasPermi:'wms:supplierinvoice-request-main:delete'}), // 删除
    {
      label: t('ts.打印'),
      name: 'mian_print',
      hide: !(roleList.value.indexOf('financial_accounting') > -1 && row.status == 5),
      type: 'primary',
      color: '',
      link: true, // 文本展现按钮
      hasPermi: ''
    }
  ]
}

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

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'mainPurPlanOpe') {
    // 打开
    handleOpe(row.id)
  } else if (val == 'mainPurPlanClo') {
    // 关闭
    handleClo(row.id)
  } else if (val == 'mainPlanSub') {
    // 提交审批
    handleSub(row.id)
  } else if (val == 'open_detail') {
    // 查看明细
    openDetail(row, '单据号', row.number)
  } else if (val == 'purchase_mainPlanSub') {
    // 采购审批通过
    // handleApp(row.id)
    // 校验是否可以开票
    const res = await checkInvoicingCalendar()
    if (res?.flag) {
      message.alertWarning(res.msg)
      return
    }
    if (row.balanceStatementStatus) {
      formPurchasePassRef.value.open('update', row, null, '采购审批通过', '采购审批通过')
    } else {
      submitPurchasePass(row.id)
    }
  } else if (val == 'purchase_mainPlanTur') {
    // 采购驳回按钮
    resonSubmit(val, row)
    // handleTur(row.id)
  } else if (val == 'invoice_sent_out') {
    // 发票寄出确认
    handleInvoiceSentOut(row.id)
  } else if (val == 'finance_mainPlanSub') {
    // 财务审批通过
    handleFinanceApp(row)
  } else if (val == 'finance_mainPlanTur') {
    //财务审批拒绝
    resonSubmit(val, row)
    // handleFinaceTur(row.masterId)
  } else if (val == 'genRecords') {
    // 处理
    genRecords(row.id)
  } else if (val == 'edit') {
    // 编辑
    openForm('update', row)
  } else if (val == 'delete') {
    // 删除
    handleDelete(row.id)
  } else if (val == 'mian_print') {
    // 打印
    handleDocumentPrint(row.id)
  } else if (val == 'repeal') {
    // 作废
    handleRepeal(row.id)
  }
}
// const procurementCreators = ref([])
// SupplierinvoiceRequestMainApi.queryUserInfoByRoleCode({
//   roleCode: 'purchase',
//   pageSize: 1000,
//   pageNo: 1,
//   sort: '',
//   by: 'ASC'
// }).then((res) => {
// procurementCreators.value = res.list
// })
/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, row?: any) => {
  // 合同金额 采购金额 总差额 :只在详情里展示
  SupplierinvoiceRequestDetail.allSchemas.tableFormColumns =
    SupplierinvoiceRequestDetail.allSchemas.tableFormColumns.filter(
      (item) =>
        item.field != 'contractAmountTotal' &&
        item.field != 'purchaseAmontTotal' &&
        item.field != 'differencePriceTotal'
    )

  if (type == 'update') {
    //编辑
    SupplierinvoiceRequestMain.allSchemas.formSchema.forEach((item) => {
      // 供应商代码
      if (item.field == 'supplierCode') {
        item.componentProps.isSearchList = false
        item.componentProps.disabled = true
      }
      // 订单类型
      if (item.field == 'orderType') {
        item.componentProps.disabled = true
      }

      // 编辑---taxRate税率\beforeTaxAmount未税金额\totalTaxAmount税额\goldenTaxInvoiceNumber金税票号\invoiceTime发票日期
      if (
        item.field == 'taxRate' ||
        item.field == 'beforeTaxAmount' ||
        item.field == 'totalTaxAmount' ||
        item.field == 'goldenTaxInvoiceNumber' ||
        item.field == 'invoiceTime'
      ) {
        if (row.status == '1' || row.status == '3' || row.status == '6' || row.status == '7') {
          item.componentProps.disabled = false
        } else {
          item.componentProps.disabled = true
        }
      }
      // 编辑---procurementCreator采购审批人、discountAmount1折扣金额
      if (item.field == 'procurementCreator' || item.field == 'discountAmount1') {
        if (row.status == '1' || row.status == '6') {
          item.componentProps.disabled = false
        } else {
          item.componentProps.disabled = true
        }
      }
    })
     await claimDetailsForUpdate(row.supplierCode,row.id)
  } else {
    // 新增
    SupplierinvoiceRequestMain.allSchemas.formSchema.forEach((item) => {
      // 供应商代码
      if (item.field == 'supplierCode') {
        //默认供应商代码
        item.value = defaultSupplierCode.value
        item.componentProps.isSearchList = true
        item.componentProps.disabled = false
      }
      // 订单类型
      if (item.field == 'orderType') {
        item.componentProps.disabled = false
      }
      // 税率 \采购价格审批人 \未税金额 \税额\金税票号\开票日期\折扣金额
      if (
        item.field == 'taxRate' ||
        item.field == 'procurementCreator' ||
        // item.field == 'beforeTaxAmount' ||
        item.field == 'totalTaxAmount' ||
        item.field == 'goldenTaxInvoiceNumber' ||
        item.field == 'invoiceTime' ||
        item.field == 'discountAmount1'
      ) {
        item.componentProps.disabled = false
      }

      // if (item.field == 'procurementCreator') {
      //   item.componentProps.options = procurementCreators.value

      // }
    })
  }
  if (row && (row.status == '3' || row.status == '7')) {
    SupplierinvoiceRequestMainRules.beforeTaxAmount[0].required = true //未税金额
    SupplierinvoiceRequestMainRules.totalTaxAmount[0].required = true //税额
    SupplierinvoiceRequestMainRules.goldenTaxInvoiceNumber[0].required = true //金税票号
    SupplierinvoiceRequestMainRules.invoiceTime[0].required = true
  } else {
    SupplierinvoiceRequestMainRules.beforeTaxAmount[0].required = false //未税金额
    SupplierinvoiceRequestMainRules.totalTaxAmount[0].required = false //税额
    SupplierinvoiceRequestMainRules.goldenTaxInvoiceNumber[0].required = false //金税票号
    SupplierinvoiceRequestMainRules.invoiceTime[0].required = false
  }
  if (row && row.procurementCreator) row.procurementCreator = Number(row.procurementCreator)
  // 校验是否可以开票
  const res = await checkInvoicingCalendar()
  if (res?.flag) {
    message.alertWarning(res.msg)
    return
  }
  tableData.value = [] // 重置明细数据
  formRef.value.open(type, row)
}
// 获取索赔明细
const claimDetailsList = ref([])
const claimDetails = async (supplierCode) => {
  claimDetailsList.value = await PurchaseClaimRequestDetailApi.getPurchaseClaimRequestDetailList(supplierCode)
  formRef.value.formRef.formModel.claimAmount = claimDetailsList.value.map(item => item.claimAmount).reduce((prev, item) => prev + item).toFixed(5)
  
}
  // 编辑的时候获取索赔明细
const claimDetailsForUpdate = async (supplierCode,id) => {
  claimDetailsList.value = await PurchaseClaimRequestDetailApi.getPurchaseClaimRequestDetailListForUpdate(supplierCode,id)
}
// 校验是否可以开票
const checkInvoicingCalendar = async () => {
  let resData = ''
  await SupplierinvoiceRequestMainApi.checkInvoicingCalendar({}).then((res) => {
    resData = res
  })
  return resData
}
const defaultSupplierCode = ref('')
const getDefaultSupplier = async () => {
  let supplier = await SupplierApi.getSupplierPageSCP({ isSearch: false })
  if (supplier.list && supplier.list.length > 0) {
    defaultSupplierCode.value = supplier.list[0]['code']
  } else {
    defaultSupplierCode.value = ''
  }
  console.log('defaultSupplierCode', defaultSupplierCode)
}


// 获取部门 用于详情 部门回显
const { wsCache } = useCache()
/** 详情操作 */
const detailRef = ref()
const clicKRowId = ref()
const detailAnnexTable = ref([
  {
    label: t('ts.合同附件'),
    prop: 'Annex',
    tableName: 'contract',
    hiddenDelete: false,
    showPreview: true,
    showDownload:true,
    hiddenUpload: false,
    fileSize: 20
  },
  {
    label: t('ts.发票附件'),
    prop: 'Annex',
    tableName: 'invoice',
    hiddenDelete: false,
    hiddenUpload: false,
    showPreview: true,
    showDownload:true,
    fileSize: 20,
    maxLength:1,
    limit:1,
    fileType:['pdf']
  },
  {
    label: t('ts.货运单附件'),
    prop: 'Annex',
    tableName: 'waybill',
    fileSize: 20
  },
  {
    label: t('ts.其他附件'),
    prop: 'Annex',
    tableName: 'invoiceOther',
    fileSize: 20
  }
])
const openDetail = (row: any, titleName: any, titleValue: any) => {
  const departmentCode = wsCache
    .get(CACHE_KEY.DEPT)
    .find((account) => account.id == row.departmentCode)?.name
  if (departmentCode) row.departmentCode = JSON.parse(JSON.stringify(departmentCode))
  clicKRowId.value = row.id

  // 合同附件
  if (
    (roleList.value.indexOf('purchase') > -1 && row.status == '2') ||
    (roleList.value.indexOf('supplier_operator') > -1 && (row.status == '1' || row.status == '6'))
  ) {
    detailAnnexTable.value[0].hiddenDelete = false
    detailAnnexTable.value[0].hiddenUpload = false
  } else {
    detailAnnexTable.value[0].hiddenDelete = true
    detailAnnexTable.value[0].hiddenUpload = true
  }
  // 发票附件
  if (
    roleList.value.indexOf('supplier_operator') > -1 &&
    (row.status == '3' || row.status == '7')
  ) {
    detailAnnexTable.value[1].hiddenDelete = false
    detailAnnexTable.value[1].hiddenUpload = false
  } else {
    detailAnnexTable.value[1].hiddenDelete = true
    detailAnnexTable.value[1].hiddenUpload = true
  }

  detailRef.value.openDetail(row, titleName, titleValue, 'requestSupplierinvoiceMain')
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    tableObject.loading = true
    // 发起删除
    await SupplierinvoiceRequestMainApi.deleteSupplierinvoiceRequestMain(id)
    message.success(t('common.delSuccess'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 关闭按钮操作 */
const handleClo = async (id: number) => {
  try {
    // 关闭的二次确认
    await message.confirm(t('ts.是否关闭所选中数据?'))
    tableObject.loading = true
    // 发起关闭
    await SupplierinvoiceRequestMainApi.cloSupplierinvoiceRequestMain(id)
    message.success(t('ts.关闭成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 关闭按钮操作 */
const handleRepeal = async (id: number) => {
  try {
    // 关闭的二次确认
    await message.confirm(t('ts.是否作废所选中数据?'))
    tableObject.loading = true
    // 发起关闭
    await SupplierinvoiceRequestMainApi.repealSupplierinvoiceRequestMain(id)
    message.success(t('ts.作废成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 打开按钮操作 */
const handleOpe = async (id: number) => {
  try {
    // 打开的二次确认
    await message.confirm(t('ts.是否打开所选中数据?'))
    tableObject.loading = true
    // 发起打开
    await SupplierinvoiceRequestMainApi.opeSupplierinvoiceRequestMain(id)
    message.success(t('ts.打开成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 提交审批按钮操作 */
const handleSub = async (id: number) => {
  try {
    // 校验是否可以开票
    const res = await checkInvoicingCalendar()
    if (res?.flag) {
      message.alertWarning(res.msg)
      return
    }
    // 提交审批的二次确认
    await message.confirm(t('ts.是否提交审批所选中数据?'))
    tableObject.loading = true
    // 发起提交审批
    await SupplierinvoiceRequestMainApi.subSupplierinvoiceRequestMain(id)
    message.success(t('ts.提交审批成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 采购审批通过按钮操作 */
const submitPurchasePass = async (id, submitData) => {
  console.log(submitData)
  const id1 = submitData?.id || id

  console.log(id1)
  try {
    // 审批通过的二次确认
    await message.confirm(t('ts.是否审批通过所选中数据?'))
    tableObject.loading = true
    // 发起审批通过
    await SupplierinvoiceRequestMainApi.appSupplierinvoiceRequestMain(
      id1,
      submitData?.balanceStatement
    )
    message.success(t('ts.审批通过成功!'))
    tableObject.loading = false
    formPurchasePassRef.value.dialogVisible = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 审批通过按钮操作 finance_mainPlanSub */
const formFinanceRef = ref()
const handleFinanceApp = async (row) => {
  row.postingDate = dayjs().valueOf()
  row.voucherNumberRemark = '收到' + row.supplierName + '发票' + row.goldenTaxInvoiceNumber
  formFinanceRef.value.open('update', row, null, '财务通过', '财务通过')
}

const submitFormFinance = async (formType, submitData) => {
  let data = { ...submitData }
  console.log('submitFormFinance', data)
  formFinanceRef.value.formLoading = true
  try {
    await SupplierinvoiceRequestMainApi.financeappSupplierinvoiceRequestMain({
      id: data.id,
      postingDate: data.postingDate,
      voucherNumberRemark: data.voucherNumberRemark
    })
    formFinanceRef.value.dialogVisible = false
    formFinanceRef.value.formLoading = false
    getList()
  } catch {
    formFinanceRef.value.formLoading = false
  }
  
  // try {
  //   // 审批通过的二次确认
  //   await message.confirm(t('ts.是否审批通过所选中数据?'))
  //   tableObject.loading = true
  //   // 发起审批通过
  //   await SupplierinvoiceRequestMainApi.financeappSupplierinvoiceRequestMain(id)
  //   message.success(t('ts.审批通过成功!'))
  //   tableObject.loading = false
  //   // 刷新列表
  //   await getList()
  // } catch { }finally{
  //   tableObject.loading = false
  // }
}

/** 驳回按钮操作 */
const handleTur = async (id: number, cause: string) => {
  try {
    // 驳回的二次确认
    // await message.confirm(t('ts.是否驳回所选中数据?'))
    tableObject.loading = true
    // 发起驳回
    await SupplierinvoiceRequestMainApi.rejSupplierinvoiceRequestMain({
      id,
      cause
    })
    message.success(t('ts.驳回成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 发票寄出确认按钮操作 */
const handleInvoiceSentOut = async (id: number) => {
  try {
    // 校验是否可以开票
    const res = await checkInvoicingCalendar()
    if (res?.flag) {
      message.alertWarning(res.msg)
      return
    }
    // 驳回的二次确认
    await message.confirm(t('ts.是否确认发票寄出选中数据?'))
    tableObject.loading = true
    // 发起驳回
    await SupplierinvoiceRequestMainApi.invoiceSentOutSupplierinvoiceRequestMain(id)
    message.success(t('ts.发票寄出成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

const resonSubmit = async (val, row) => {
  ElMessageBox.prompt(t('ts.请输入驳回原因'), t('ts.提示'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空,且非空格
    inputErrorMessage: t(`ts.${'驳回原因不能为空,且不超过60字'}`),
    inputType: 'textarea',
    inputValidator: (value) => {
      if (value.length > 60 || value.length == 0) {
        return false
      } else {
        return true
      }
    }
  })
    .then(({ value }) => {
      // 驳回原因
      if (val == 'purchase_mainPlanTur') {
        // 采购驳回按钮
        handleTur(row.id, value)
      } else if (val == 'finance_mainPlanTur') {
        //财务审批拒绝
        handleFinaceTur(row.id, value)
      }
    })
    .catch(() => {})
}

/** 驳回按钮操作 */
const handleFinaceTur = async (id: number, cause: string) => {
  try {
    // 驳回的二次确认
    // await message.confirm(t('ts.是否驳回所选中数据?'))
    tableObject.loading = true
    // 发起驳回
    await SupplierinvoiceRequestMainApi.financerejSupplierinvoiceRequestMain({
      id,
      cause
    })
    message.success(t('ts.驳回成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 处理按钮操作 */
const genRecords = async (id: number) => {
  try {
    // 处理的二次确认
    await message.confirm(t('ts.是否处理所选中数据?'))
    tableObject.loading = true
    // 发起处理
    await SupplierinvoiceRequestMainApi.genRecordsSupplierinvoiceRequestMain(id)
    message.success(t('ts.处理成功!'))
    tableObject.loading = false
    // 刷新列表
    await getList()
  } catch {
  } finally {
    tableObject.loading = false
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  console.log(111)
  let rows: any = []
  selectionRows.value.forEach((item) => {
    rows = [...rows, ...item.selectionRows.map((item1) => item1.number)]
  })

  let paramsData = JSON.parse(JSON.stringify(tableObject.params))
  if (tableObject.params && tableObject.params.isSearch == true) {
    paramsData.filters.push({
      action: 'in',
      column: 'number',
      value: rows.join(',')
    })
  } else {
    paramsData = { ...paramsData, checkNums: rows }
  }
  if (!paramsData.createTime || (paramsData.createTime && paramsData.createTime.length == 0)) {
    delete paramsData.createTime
  }
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    loadStart()
    const excelTitle = ref(route.meta.title)
    const data = await SupplierinvoiceRequestMainApi.exportSupplierinvoiceRequestMain(paramsData)
    download.excel(data, `【${excelTitle.value}】【${formatDate(new Date())}】.xlsx`)
  } catch {
  } finally {
    loadDone()
  }
}

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

// 添加明细
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))
}

const sumFormDataHandle = async (
  formRef1,
  formModel,
  tableData,
  formType,
  originFormModel,
  updateOriginFormModel
) => {
  if (formType == 'update') {
    if (formModel && formModel.id && formModel.taxRate && originFormModel) {
      let res = await SupplierinvoiceRequestMainApi.getTaxAmount({
        id: formModel.id,
        taxRate: formModel.taxRate
      })
      console.log('更新taxAmount', res)
      formRef1.value.setValues({
        taxAmount: res
      })
    }
  }
}
// 主子数据 提交
const submitForm = async (formType, submitData) => {
  console.log('submitForm',tableData.value)
  let data = { ...submitData }
  tableData.value.forEach((item) => {
    item.differencePrice = Number(
      (Number(item?.singlePrice) - Number(item?.purchasePrice)).toFixed(5)
    )
  })
  let flagInvoicableQuantity = false
  tableData.value.forEach(item => {
    // 负数:默认默认开票数~0
    // 正数:0~默认开票数
    if(item.invoicableQuantity==0){
      flagInvoicableQuantity = true
      message.error(`${item.itemCode}`+t('ts.可开票数量不能为0'))
    }else if(item.maxInvoicableQuantity){
      if(item.maxInvoicableQuantity>0){
        if(item.invoicableQuantity<0||item.invoicableQuantity>item.maxInvoicableQuantity){
          flagInvoicableQuantity = true
          message.error(`${item.itemCode}`+t('ts.可开票数量范围是')+`:0~${item.maxInvoicableQuantity}`)
        }
      }else{
        if(item.invoicableQuantity>0||item.invoicableQuantity<item.maxInvoicableQuantity){
          flagInvoicableQuantity = true
          message.error(`${item.itemCode}`+t('ts.可开票数量范围是')+`:${item.maxInvoicableQuantity}~0`)
        }
      }
    }
  });
  if(flagInvoicableQuantity){
    return
  }
  data.subList = tableData.value // 拼接子表数据参数
  console.log('data', data)
  try {
    if (formType === 'create') {
      if (data.subList.length == 0) {
        message.warning(t('ts.请添明细数据'))
        return
      }
      if (data.subList.length > 20000) {
        message.warning(t('ts.明细数据条数已超过最大数量限制【20000条】'))
        return
      }
      formRef.value.formLoading = true
      await SupplierinvoiceRequestMainApi.createSupplierinvoiceRequestMain(data)
      message.success(t('common.createSuccess'))
    } else {
      formRef.value.formLoading = true
      data.masterId = data.id
      await SupplierinvoiceRequestMainApi.updateSupplierinvoiceRequestMain(data)
      message.success(t('common.updateSuccess'))
    }
    formRef.value.dialogVisible = false
    // 刷新当前列表
    getList()
  } finally {
    formRef.value.formLoading = false
  }
}

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

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

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

// 详情--头部按钮事件
const detailButtonBaseClick = (val, item) => {
  console.log('点击的按钮', val)
  if (val == 'printing') {
    // 单据打印
    handleDocumentPrint(clicKRowId.value)
  } else if (val === 'printing-all') {
    //打印全部发货单
    handlePrintAll(clicKRowId.value)
  } else if (val === 'export-detail') {
    console.log('导出明细:', clicKRowId.value)
    handleDetailExport(clicKRowId.value)
  }
}

const tableFormButton = (val, item) => {
  console.log('点击的按钮', val)
  if (val == 'print') {
    // 打印
    SupplierinvoiceRequestMainApi.printSupplierRecord(item.asnBillNum).then((res) => {
      if (res) {
        handleSupplierdeliverRecordPrint(res)
      }
    })
  }
}

/** 导出明细按钮操作 */
const exportLoadingDetail = ref(false) // 导出的加载中
const handleDetailExport = async (masterId) => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出导出明细
    exportLoadingDetail.value = true
    let params = {
      masterId: masterId
    }
    const excelTitle = ref(route.meta.title)
    const data = await SupplierinvoiceRequestMainApi.exportSupplierinvoiceRequestDetail(params)
    download.excel(data, `【${excelTitle.value}明细】【${formatDate(new Date())}】.xlsx`)
  } catch {
  } finally {
    exportLoadingDetail.value = false
  }
}

const BASE_URL = getJmreportBaseUrl()

//供应商发货单打印
const documentSupplierdeliverRecordSrc = ref(
  BASE_URL + '/jmreport/view/932556833517789184?token=' + getAccessToken()
)
const handleSupplierdeliverRecordPrint = async (id) => {
  window.open(documentSupplierdeliverRecordSrc.value + '&id=' + id)
}

// 单据打印
const documentSrc = ref(BASE_URL + '/jmreport/view/936875675614240768?token=' + getAccessToken())
const handleDocumentPrint = async (id) => {
  window.open(documentSrc.value + '&id=' + id)
}

const srcPoint = ref(BASE_URL + '/jmreport/view/972723426543935488?token=' + getAccessToken())
const handleSelectionPoint = async () => {
  let rows: any = []
  selectionRows.value.forEach((item) => {
    rows = [...rows, ...item.selectionRows.map((item1) => item1.id)]
  })
  if (rows.length == 0) {
    message.warning('至少选择一条数据!')
    return
  }
  console.log('批量打印', rows.join(','))
  window.open(srcPoint.value + '&ids=' + rows.join(','))
}

const handlePrintAll = async (masterId) => {
  // 打印
  SupplierinvoiceRequestMainApi.printSupplierRecordByMasterId(masterId).then((res) => {
    if (res && res.length > 0) {
      for (let i = 0; i < res.length; i++) {
        let id = res[i]
        handleSupplierdeliverRecordPrint(id)
      }
    } else {
      message.warning(t('ts.非SCP订单无法打印'))
      return
    }
  })
}
const detailButtonIsShowAddStatusArray = ref<any>([])
const roleList = ref<string[]>([])
const getLoginUserRoleList = async () => {
  let res = await SupplierinvoiceRequestMainApi.getLoginUserRoleList()
  console.log('roleList', res)
  if (res && res.length > 0) {
    roleList.value = res
  } else {
    roleList.value = []
  }
  if (roleList.value.indexOf('supplier_operator') > -1) {
    detailButtonIsShowAddStatusArray.value = ['1', '6']
  } else {
    detailButtonIsShowAddStatusArray.value = []
  }
}

/** 初始化 **/
onMounted(async () => {
  SupplierinvoiceRequestMain.allSchemas.formSchema.forEach(async (item) => {
    if (item.field == 'procurementCreator') {
      //采购审批人
      const procurementCreators = await SupplierinvoiceRequestMainApi.queryUserInfoByRoleCode({
        roleCode: 'purchase',
        pageSize: 1000,
        pageNo: 1,
        sort: '',
        by: 'ASC'
      })
      item.componentProps.options = procurementCreators.list
    }
  })
  getList()
  getDefaultSupplier()
  getLoginUserRoleList()
  importTemplateData.templateUrl = await SupplierinvoiceRequestMainApi.importTemplate()
})
</script>

<style lang="scss" scoped>
.is-red {
  border-radius: var(--el-border-radius-base);
  border: 1px solid var(--el-color-danger);
  box-shadow: 0 0 0 1px var(--el-color-danger) inset;
}
.red-text {
  color: var(--el-color-danger);
  font-weight: 700;
}
</style>