<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(2) }}</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} = 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-discountAmount1,//未税差额：未税金额-系统未税金额-折扣金额
          taxAmountDiff:totalTaxAmount-taxAmount,// 税额差异：税额-系统税额
          totalTaxDiffAmount:beforeTaxDiffAmount+taxAmountDiff // 价税合计差额=未税差额+税额差异
        })
      }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-discountAmount1,//未税差额：未税金额-系统未税金额-折扣金额
          taxAmountDiff:totalTaxAmount-taxAmount,// 税额差异：税额-系统税额
          totalTaxDiffAmount:beforeTaxDiffAmount+taxAmountDiff // 价税合计差额=未税差额+税额差异
        })
      }
      
    }"
    
    :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"
  >      
  
  <template #selectionsActionspoLine="{selections}">
    <div style="text-align: left;margin-right:10px">
      系统未税金额:{{Number(selections.reduce((prev, item) => prev + Number(Number(Number(Number(item['purchasePrice']).toFixed(2))*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(2)"/>
    </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" 
  />
  <!-- 详情 -->
  <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(2))
      })
    }"
    :isBasic="false" 
    :allSchemas="SupplierinvoiceRequestDetailMain.allSchemas"
    :detailAllSchemas="SupplierinvoiceRequestDetail.allSchemas"
    :detailAllSchemasRules="SupplierinvoiceRequestDetailRules" 
    :searchTableParams="searchTableParams"
    :apiCreate="SupplierinvoiceRequestDetailApi.createSupplierinvoiceRequestDetail"
    :apiUpdate="SupplierinvoiceRequestDetailApi.updateSupplierinvoiceRequestDetail"
    :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"
  >
    <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 { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  import { SupplierinvoiceRequestMain, 
    SupplierinvoiceRequestMainRules, 
    SupplierinvoiceRequestDetail, 
    SupplierinvoiceRequestDetailRules,
    SupplierinvoiceRequestFinance,
    SupplierinvoiceRequestFinanceRules,
    PurchasePass,
    PurchasePassRules,
    SupplierinvoiceRequestDetailMain
  } from './supplierinvoiceRequestMain.data'
  import * as SupplierinvoiceRequestMainApi from '@/api/wms/supplierinvoiceRequestMain'
  import * as SupplierinvoiceRequestDetailApi from '@/api/wms/supplierinvoiceRequestDetail'
  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'

  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 = []
  setSearchParams(model)
}
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 searchTableSuccess = (formField, searchField, val, searchFormRef, type, row) => {
    nextTick(() => {
      if (type == 'tableForm') {
        // 明细查询页赋值
        val.forEach(item=>{
          if(tableData.value.find(item1=>item1['poNumber'] == item['poNumber']&&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['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 {
        // 切换供应商代码
        if(formField=='supplierCode'&&val[0][searchField]!=searchFormRef.formModel.supplierCode){
          tableData.value = []
        }
        // 切换订单类型
        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.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) => {
    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']),
        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)
      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 formRef = ref()
  const openForm = async (type : string, row ?: number) => {
    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
          }
        }
      })
    }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(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)
    // 校验是否可以开票
    SupplierinvoiceRequestMainApi.checkInvoicingCalendar({}).then(res => {
      if(res.flag){
        message.alertWarning(res.msg)
        return
      }
      tableData.value = [] // 重置明细数据
      formRef.value.open(type, row)
    })
  }
  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,
    hiddenUpload:false,
    fileSize:20
  },{
    label: t('ts.发票附件'),
    prop: 'Annex',
    tableName:'invoice',
    hiddenDelete:false,
    hiddenUpload:false,
    fileSize:20

  },{
    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)
  }

  /** 删除按钮操作 */
  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 {
      // 提交审批的二次确认
      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)
    await SupplierinvoiceRequestMainApi.financeappSupplierinvoiceRequestMain({
      id:data.id,
      postingDate:data.postingDate,
      voucherNumberRemark:data.voucherNumberRemark,
    })
    formFinanceRef.value.dialogVisible = false
    getList()
    // 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 {
      // 驳回的二次确认
      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 exportLoading = ref(false) // 导出的加载中
  const handleExport = async () => {
    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}
    }
    console.log('批量导出',paramsData)
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await SupplierinvoiceRequestMainApi.exportSupplierinvoiceRequestMain(paramsData)
      download.excel(data, `${t('ts.供应商发票申请主')}.xlsx`)
    } catch {
    } finally {
      exportLoading.value = false
    }
  }



  /**
    * 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) => {
    let data = {...submitData}
    tableData.value.forEach((item) => {
      item.differencePrice = Number((Number(item?.singlePrice)-Number(item?.purchasePrice)).toFixed(2))
    })
    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;
        }
        await SupplierinvoiceRequestMainApi.createSupplierinvoiceRequestMain(data)
        message.success(t('common.createSuccess'))
      } else {
        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: `${t('ts.供应商发票申请主导入模板')}.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 data = await SupplierinvoiceRequestMainApi.exportSupplierinvoiceRequestDetail(params)
      download.excel(data, `${t('ts.供应商发票申请明细')}.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 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 () => {
    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>
