<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search class="search-box" :schema="SupplierinvoiceRequestMain.allSchemas.searchSchema" @search="searchList" @reset="resetList" >
      <template #cha>
        <div class="el-form-item__content " style="display:inline-flex;">
          <el-input-number style="flex:0.5;margin-right:10px" v-model="staDifferencePrice" :max="endDifferencePrice?endDifferencePrice:Infinity" :placeholder="t('ts.最小值')"/>-<el-input-number style="flex:0.5;margin-left:10px" v-model="endDifferencePrice" :min="staDifferencePrice?staDifferencePrice:-Infinity" :placeholder="t('ts.最大值')"/>
        </div>
      </template>
    </Search>
  </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(4) }}</span>
      </template>
    </Table>
  </ContentWrap>


  <!-- 详情 -->
  <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: false,
        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(4))
      })
    }"
    :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="false"
    :detailButtonIsShowDelete="false"
    :detailButtonIsShowAdd="false"
    @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>


</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 './supplierinvoiceRequestMainDifference.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 staDifferencePrice = ref()
const endDifferencePrice = ref()
const searchList = (model)=>{
  model.staDifferencePrice = staDifferencePrice.value
  model.endDifferencePrice = endDifferencePrice.value
  console.log('searchList',model)
  selectionRows.value = []
  setSearchParams(model)
}
const resetList = (model)=>{
  staDifferencePrice.value = null
  endDifferencePrice.value = null
  searchList(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 Echo = []

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

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

  // 列表头部按钮
  const HeadButttondata = [
    defaultButtons.defaultExportBtn({hasPermi: 'wms:supplierinvoice-request-main:export'}), // 导出
    defaultButtons.defaultFreshBtn(null), // 刷新
    defaultButtons.defaultFilterBtn(null), // 筛选
    defaultButtons.defaultSetBtn(null), // 设置
  ]

  // 头部按钮事件
  const buttonBaseClick = (val, item) => {
    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 { wsCache } = useCache()
  /** 详情操作 */
  const detailRef = ref()
  const clicKRowId = ref();
  const detailAnnexTable = ref(
  [{
    label: t('ts.合同附件'),
    prop: 'Annex',
    tableName:'contract',
    hiddenDelete:true,
    hiddenUpload:true,
    fileSize:20
  },{
    label: t('ts.发票附件'),
    prop: 'Annex',
    tableName:'invoice',
    hiddenDelete:true,
    hiddenUpload:true,
    fileSize:20

  },{
    label: t('ts.货运单附件'),
    prop: 'Annex',
    tableName:'waybill',
    hiddenDelete:true,
    hiddenUpload:true,
    fileSize:20
  },{
    label: t('ts.其他附件'),
    prop: 'Annex',
    tableName:'invoiceOther',
    hiddenDelete:true,
    hiddenUpload:true,
    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
    detailRef.value.openDetail(row, titleName, titleValue,"requestSupplierinvoiceMain")
  }

  /** 导出按钮操作 */
  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 importTemplateData = reactive({
  templateUrl: '',
  templateTitle: `${t('ts.供应商发票申请主导入模板')}.xlsx`
})


  // 筛选提交
  const searchFormClick = (searchData) => {
    tableObject.params = {
      ...tableObject.params,
      isSearch: true,
      filters: [...searchData.filters,{
        action: "==",
        column: "balanceStatementStatus",
        value: "TRUE"
      }]
    }
    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;
        }
      })
  }

  /** 初始化 **/
  onMounted(async () => {
    getList()
    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;
}

::v-deep(.el-input-number__decrease) {
  display: none !important;
}
::v-deep(.el-input-number__increase) {
  display: none !important;
}
::v-deep(.el-input-number .el-input__wrapper) {
  padding-left: 0;
  padding-right: 0;

}

</style>
