<!--付款管理-->
<template>
  <div>
    <div class="mask" v-show="isShowPrintType"></div>
    <div class="print-type" v-show="isShowPrintType">
      <div class="print-type-content">
        <div class="print-type-title">打印凭证</div>
        <div class="print-type-checkbox">
          <el-checkbox-group v-model="ruleForm.type">
            <el-checkbox label="打印身份证（正反面）" name="type" class="label-width" @change="selectType"></el-checkbox>
            <el-checkbox label="打印银行卡（正反面）" name="type" class="label-width" @change="selectType"></el-checkbox>
            <el-checkbox label="打印结算凭证" name="type" class="label-width" @change="selectType($event)"></el-checkbox>
            <el-checkbox label="打印检斤单" name="type" class="label-width" @change="selectType($event)"></el-checkbox>
            <el-checkbox label="打印回执单" name="type" class="label-width" @change="selectType($event)"></el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <div class="bottom-btn">
        <el-button @click="typePrintClick(printType)">确定</el-button>
        <el-button @click="typePrintCannelClick">取消</el-button>
      </div>
    </div>
    <div class="top-btn">
      <div class="left">
        <ws-button :type="searchType == '' ? 'primary' : ''" @click="screen(-1)">全部</ws-button>
           <ws-button v-hasPermission="`acquisitionManagement.acquisitionPay.pay`" :type="searchType == 7 ? 'primary' : ''" @click="screen(7)">未付款</ws-button>
         <ws-button :type="searchType == 1 ? 'primary' : ''" @click="screen(1)">已付款</ws-button>
         <ws-button :type="searchType == 1 ? 'primary' : ''" @click="screen(1)">未收款</ws-button>
          <ws-button :type="searchType == 1 ? 'primary' : ''" @click="screen(1)">已收款</ws-button>
        <ws-button :type="searchType == 1 ? 'primary' : ''" @click="screen(1)">待审核</ws-button>

        <ws-button :type="searchType == 2 ? 'primary' : ''" @click="screen(2)"
          v-hasPermission="`acquisitionManagement.acquisitionPay.add`">待结算</ws-button>
          <ws-button :type="invoicing === 0 ? 'primary' : ''" @click="screen(0)">未开自采发票</ws-button>
        <ws-button :type="invoicing === 0 ? 'primary' : ''" @click="screen(0)">未开销售发票</ws-button>
      </div>
      <div class="right">
        <el-select class="warehouse_select" v-model="warehouseNameKey" placeholder="请选择仓库" @change="warehouseChange"
          filterable clearable style="margin: 0 10px">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id">
          </el-option>
        </el-select>
        <el-date-picker class="date-select" size="small" style="margin: 0 10px 0 0" value-format="yyyy-MM-dd" v-model="value2" @change="datechange"
          type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="结算时间起"
          end-placeholder="结算时间止">
        </el-date-picker>
        <div class="serch">
          <ws-input class='findinput' @keyup.enter.native="find()" v-model="searchKeyWord" placeholder="可按编号、客户名、车牌号查找"
            clearable maxlength="500" type="input">
          </ws-input>
          <!-- v-hasPermission="'procurement.sparepart.directShip'" -->
          <ws-button class="find" type="primary" @click="find()">
            <img width="16" height="16" src="../../../public/img/sousuo.png" alt />
          </ws-button>
        </div>

      </div>
    </div>
    <div class="top-btn-two">
      <div class="left">
        <ws-button type="primary" @click="reject">结算</ws-button>
        <ws-button type="primary" @click="reject">驳回</ws-button>
        <ws-button type="primary" @click="adopt">通过</ws-button>
       <ws-button type="primary" @click="payment" v-hasPermission="`acquisitionManagement.acquisitionPay.pay`">付款
       </ws-button>
       <ws-button type="primary" @click="payment" v-hasPermission="`acquisitionManagement.acquisitionPay.pay`">收款
       </ws-button>
       <ws-button type="primary" @click="selectPrint(1)"
         v-hasPermission="`acquisitionManagement.acquisitionPay.finace`">财务批量打印
       </ws-button>
       <ws-button type="primary" @click="invoicingClick"
          v-hasPermission="`acquisitionManagement.acquisitionPay.finace`">开自采发票</ws-button>
          <ws-button type="primary" @click="invoicingClick"
             v-hasPermission="`acquisitionManagement.acquisitionPay.finace`">开销售发票</ws-button>
        <ws-button type="primary" @click="exportlist" v-hasPermission="`acquisitionManagement.acquisitionPay.print`">导出
        </ws-button>
        <ws-button type="primary" @click="exportlist" v-hasPermission="`acquisitionManagement.acquisitionPay.print`">导入
        </ws-button>
        <ws-button type="primary" @click="agreementPrint()"
          v-hasPermission="`acquisitionManagement.acquisitionPay.dow`">模板下载
        </ws-button>
      </div>
    </div>
    <div class="content-top">
      <div class="content-top-item">合同编号：1234567</div>
      <div class="content-top-item">买方：xxx公司</div>
      <div class="content-top-item">货名：玉米</div>
      <div class="content-top-item">合同量：10000吨</div>
      <div class="content-top-item">已完成量：9000吨</div>
      <div class="content-top-item">代收费：10元/吨</div>
    </div>
    <el-table :data="paymentList" ref="table" style="width: 100%; margin-top: 20px" border height="calc(100% - 190px)"
      @row-click="handleRowClick" @selection-change="handleSelectionChange" :summary-method="getSummaries" show-summary>
      <el-table-column :selectable="selectInit" type="selection" width="30"></el-table-column>
      <el-table-column type="index" label="序号" width="50">
        <template scope="scope">
          <span v-if="scope.$index < 9">0{{ scope.$index + 1 }}</span>
          <span v-else>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column class="table_td" prop="customerName" label="客户" sortable>
        <template slot-scope="scope">
          <div @click.stop="customer(scope.row)">
            <span class="text_css">{{ scope.row.customerName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column class="table_td" prop="carNo" label="车牌号"></el-table-column>
      <el-table-column class="table_td" prop="goodsName" width="70" label="货名"></el-table-column>
      <el-table-column class="table_td" prop="goodsName" width="70" label="等级"></el-table-column>
      <el-table-column class="table_td" prop="netWeight" width="100" label="净重（吨）"></el-table-column>
       <el-table-column class="table_td" prop="netWeight" width="100" label="收购单价（元/吨）"></el-table-column>
       <el-table-column class="table_td" prop="amountIngPayable" width="80" label="应付(元)"></el-table-column>
       <el-table-column class="table_td" prop="amountEdPayable" width="80" label="已付(元)"></el-table-column>
         <el-table-column class="table_td" prop="status" width="80" label="自采发票">
           <template scope="scope">
             <span v-if="scope.row.invoicing == '0'">未开票</span>
             <span v-else>已开票</span>
           </template>
         </el-table-column>
          <el-table-column class="table_td" prop="netWeight" width="100" label="销售单价（元/吨）"></el-table-column>
          <el-table-column class="table_td" prop="amountIngPayable" width="80" label="应收(元)"></el-table-column>
          <el-table-column class="table_td" prop="amountEdPayable" width="80" label="已收(元)"></el-table-column>
         <el-table-column class="table_td" prop="status" width="80" label="销售发票">
           <template scope="scope">
             <span v-if="scope.row.invoicing == '0'">未开票</span>
             <span v-else>已开票</span>
           </template>
         </el-table-column>

           <el-table-column class="table_td" prop="updateDate" label="更新时间" width="150" sortable></el-table-column>


      <el-table-column class="table_td" prop="status" width="80" label="状态">
        <template scope="scope">
          <span v-if="scope.row.approveStatus">{{
            scope.row.approveStatus
          }}</span>
          <span v-else>{{ scope.row.status }}</span>
        </template>
      </el-table-column>

      <el-table-column class="table_td" prop="collectionEdPayable" label="操作" width="300">
        <template scope="scope">
          <el-button @click="rowLook(scope.row)" v-hasPermission="`acquisitionManagement.acquisitionPay.view`">查看
          </el-button>
          <el-button @click="rowEdit(scope.row)" v-hasPermission="`acquisitionManagement.acquisitionPay.print`">编辑</el-button>
          <el-button type="danger" v-if="
              (!scope.row.approveStatus ||
                scope.row.approveStatus == '待结算') &&
              scope.row.status == '待结算'
            " @click="del(scope.row)" v-hasPermission="`acquisitionManagement.acquisitionPay.delete`">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 付款弹窗 -->
    <el-dialog width="40%" :visible.sync="paymentForm" :append-to-body="true" title="付款">
      <div class="tanchuang">
        <ws-form>
          <ws-info-table>
            <ws-form-item label="未付金额（元）" prop="amountNotPayable">
              {{ payments.amountNotPayable }}
            </ws-form-item>
            <ws-form-item label="本次付款金额（元）" prop="money">
              <ws-input type="number" @mousewheel.native.prevent v-model="payments.money" placeholder="请输入本次付款金额（元）"
                maxlength="100" size="small" />
            </ws-form-item>
            <ws-form-item label="付款日期" prop=" paymentDate">
              <el-date-picker v-model="payments.paymentDate" type="date" placeholder="选择日期"></el-date-picker>
            </ws-form-item>
            <ws-form-item label="上传截图" prop=" paymentScreenshot"></ws-form-item>
            <div class="upLoad">
              <el-upload class="avatar-uploader" action="https://www.zthymaoyi.com/upload/admin" :show-file-list="false"
                :on-success="handleAvatarSuccess">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </ws-info-table>
          <div style="text-align: center; margin-top: 20px">
            <el-button @click="paymentForm = false">取消</el-button>
            <el-button @click="paymentSubmit">提交</el-button>
          </div>
        </ws-form>
      </div>
    </el-dialog>
    <!-- 付款截图 -->
<!--    <el-dialog width="50%" :visible.sync="showPayImgs" :append-to-body="true" title="付款截图">
      <el-upload action="https://www.zthymaoyi.com/upload/admin" list-type="picture-card"
        :on-success="handleAvatarSuccess1" :file-list='payImg' :limit='1'>
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">

          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="_handleRemove(file)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
      </el-upload>
      <div style="text-align: center; margin: 10px auto">
        <el-button @click="showPayImgs = false" type="primary">关闭</el-button>
      </div>
    </el-dialog> -->
    <div style="text-align: center">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 30, 50, 100, 500, 1000, 9999]" layout="total, sizes, prev, pager, next, jumper"
        :total="deptBudgetTotal"></el-pagination>
      <el-dialog width="70%" class="table-content" center :visible.sync="isShowPrint"
        :title="printData.compName + '结算凭证'">
        <paymentPrint :printData="printData" :customerInfo="customerList" :showType="ruleForm.type"></paymentPrint>
        <div style="text-align: center">
          <el-button type="primary" @click="isShowPrint = false">关闭</el-button>
          <!-- <el-button type="primary" @click="printSmall">打印小票</el-button> -->
          <el-button type="primary" @click="printBig">打印单据</el-button>
        </div>
      </el-dialog>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!--客户信息-->
    <el-dialog width="20%" title="客户信息" :visible.sync="customerInfo" :append-to-body="true" :close="customerclose">
      <el-form class="customer" label-position="right" label-width="120px">
        <el-form-item class="customer-item" label="客户" >
         <el-select class="warehouse_select" v-model="warehouseNameKey" placeholder="客户姓名" @change="warehouseChange"
           filterable clearable style="margin: 0 10px">
           <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id">
           </el-option>
         </el-select>
        </el-form-item>

        <el-form-item class="customer-item" label="身份证号" >
          <el-input v-model="customerlist.customerNumberCard" placeholder="请输入身份证号" maxlength="100"
            size="small" />
        </el-form-item>
        <el-form-item class="customer-item" label="车牌号" >
          <el-input v-model="customerlist.customerNumberCard" placeholder="请输入车牌号" maxlength="100"
            size="small" />
        </el-form-item>
        <el-form-item class="customer-item" label="净重(吨)">
          <el-input v-model="customerlist.customerNumberCard" placeholder="请输入净重" maxlength="100"
            size="small" />
        </el-form-item>
        <el-form-item class="customer-item" label="等级">
         <el-select class="warehouse_select" v-model="warehouseNameKey" placeholder="等级" @change="warehouseChange"
           filterable clearable style="margin: 0 10px">
           <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id">
           </el-option>
         </el-select>
        </el-form-item>
        <el-form-item class="customer-item" label="收购单价(元)">
         <el-input v-model="customerlist.customerNumberCard" placeholder="收购单价" maxlength="100"
           size="small" />
        </el-form-item>
        <el-form-item class="customer-item" label="入库日期">
          </el-date-picker>
           <el-date-picker
                v-model="value2"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
        </el-form-item>
        <el-form-item class="customer-item" label="销售单价(元)">
          <el-input v-model="customerlist.customerNumberCard" placeholder="销售单价" maxlength="100"
            size="small" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="customerclose">取 消</el-button>
      </div>
    </el-dialog>
<!--    <el-dialog width="50%" title="付款回执单" :visible.sync="isPreviewPayOrder" :close="paymentReceiptClose">
      <div class="no-messege" v-if="!paymentReceipt">暂未上传付款回执单</div>
      <el-image class="my-img" ref="myImg" v-if="paymentReceipt" :src="paymentReceipt"
        :preview-src-list="[paymentReceipt]">
      </el-image>
    </el-dialog>
 -->
  </div>
</template>
<script>
  import {
    dayjs,
    EventBus
  } from 'base-core-lib'
  import {
    downloadFile
  } from '@/utils/batchDown'
  import JSZip from 'jszip'
  import FileSaver from 'file-saver'
  import {
    getpayment,
    selectWarehouseSelf,
    delpayment,
    auditpayment,
    getpaymentexamine,
    getCustomerLook,
    paymentCommit,
    getJurisdiction,
    invoicing,
    export1,
    settlementEdit,
    workflowcontent
  } from '@/model/houseSelfCollect/index'
  import {
    posthandle,
    postqueryhandle
  } from '@/model/purchasingManagement/index'
  import paymentPrint from './component/paymentPrint.vue'
  import {
    getHp
  } from '@/utils/getHasPermission'
  import download from '../../components/WsDownload/download'
  export default {
    components: {
      paymentPrint,
    },
    watch: {},
    data() {
      return {
        viewLock:false,
        paymentReceipt: '',
        isPreviewPayOrder: false,
        printType: 0,
        isShowPrintType1: true,
        isShowPrintType2: true,
        isShowPrintType3: true,
        isShowPrintType4: true,
        customerInfo: false,
        form: {},
        formLabelWidth: '300px',
        invoicing: '',
        deleteshow: false,
        customerlist: {
          payeeAddressUrls: [],
        },

        ruleForm: {
          type: [
            '打印身份证（正反面）',
            '打印银行卡（正反面）',
            '打印结算凭证',
            '打印检斤单',
            '打印回执单'
            // '打印发票'
          ],
        },
        row: {},
        isShowPrintType: false,
        customerList: {
          customerName: '',
          customerNumberCard: '',
          bankCard: '',
          bankDeposit: '',
        },
        selectCustomerList: [],
        selectPrintList: [],
        identity: [],
        //分页
        currentPage: 1,
        pageSize: 10,
        paymentList: [],
        deptCircularPage: {},
        deptBudgetTotal: 0,
        paymentForm: false,
        searchType: '',
        searchTypeText: '',
        searchKeyWord: '',
        warehouseList: [],
        warehouseNameKey: '',
        warehouseName: '',
        isShowPrint: false,
        printData: {},
        warehouse: [],
        disabled: false,
        dialogImageUrl: '',
        dialogVisible: false,
        value1: '', //付款日期
        modification: [],
        userJurisdiction: true,
        payments: {
          amountNotPayable: 0,
          paymentDate: '',
        },
        showPayImgs: false,
        isShowAdopt: false,
        //上传截图路径
        imageUrl: '',
        payImg: [],
        rowData: {},
        value2: [],
        date: {
          year: dayjs().format('YYYY'),
          month: dayjs().format('MM'),
        },
      }
    },
    activated() {
      this.userJurisdiction = getHp('acquisitionManagement.acquisitionPay.print')
      this.getPassYearFormatDate()
      this.getWarehouse()
      // this.getList()
    },
    updated() {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
    },
    methods: {
      rowLook(row){
        this.customerInfo = true
        this.viewLock = true
      },
      rowEdit(row){
        this.customerInfo = true
      },
      imgshow() {
        this.deleteshow = false
        console.log(11111)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      previewPayOrder(val) {
        this.paymentReceipt = val.paymentScreenshot
        this.isPreviewPayOrder = true
        console.log(val.paymentScreenshot)

      },
      paymentReceiptClose() {},
      datechange() {
        this.getList()
      },
      getPassYearFormatDate() {
        var nowDate = new Date()
        nowDate.setTime(nowDate.getTime() - 24 * 60 * 60 * 1000 * 30)
        var seperator1 = '-'
        var year = nowDate.getFullYear()
        var month = nowDate.getMonth() + 1
        var strDate = nowDate.getDate()
        if (month >= 1 && month <= 9) {
          month = '0' + month
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = '0' + strDate
        }
        var formatDate = year + seperator1 + month + seperator1 + strDate
        this.getNowFormatDate(formatDate)
      },
      /* 获取现在时间，并接受过去时间的值 */
      getNowFormatDate(formatDate) {
        var date = new Date()
        date.setTime(date.getTime() + 24 * 60 * 60 * 1000)
        var seperator1 = '-'
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var strDate = date.getDate()
        if (month >= 1 && month <= 9) {
          month = '0' + month
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = '0' + strDate
        }
        var nowData = year + seperator1 + month + seperator1 + strDate
        this.value2 = [formatDate, nowData] // 默认赋值一年时间
      },
      selectPrint() {
        console.log('批量打印数据', this.modification)
        this.printType = 1
        this.isShowPrintType = true
      },
      agreementPrint() {
        var arr = []
        for (let i = 0; i < this.modification.length; i++) {
          if (this.modification[i].pictureAddress) {
            arr.push({
              fileUrl: this.modification[i].pictureAddress,
              renameFileName: '结算单' + i + '.png',
            })
          }

        }
        if (arr.length > 0) {
          this.filesToRar(arr, '结算单文件')
        }
      },
      async exportlist() {
        console.log('导出数据', this.modification)
        let _data = {
          paymentManagementList: this.modification,
        }
        const {
          data
        } = await export1(
          _data, {}, {
            responseType: 'blob',
          }
        ).toPromise()
        downloadFile({
          res: data,
          fileName: `${
          this.date.year + (this.date.month ? `-${this.date.month}` : '')
        }结算凭证`,
          type: 'xls',
        })
      },
      filesToRar(arrImages, filename) {
        let _this = this
        let zip = new JSZip()
        let cache = {}
        let promises = []
        _this.title = '正在加载压缩文件'
        for (let item of arrImages) {
          const promise = _this.getImgArrayBuffer(item.fileUrl).then((data) => {
            // 下载文件, 并存成ArrayBuffer对象(blob)
            zip.file(item.renameFileName, data, {
              binary: true
            }) // 逐个添加文件
            cache[item.renameFileName] = data
          })
          promises.push(promise)
        }
        Promise.all(promises)
          .then(() => {
            zip.generateAsync({
              type: 'blob'
            }).then((content) => {
              _this.title = '正在压缩'
              // 生成二进制流
              FileSaver.saveAs(content, filename) // 利用file-saver保存文件 自定义文件名
              _this.title = '压缩完成'
            })
          })
          .catch((res) => {
            _this.$message.error('文件压缩失败')
          })
      },
      //获取文件blob
      getImgArrayBuffer(url) {
        let _this = this
        return new Promise((resolve, reject) => {
          //通过请求获取文件blob格式
          let xmlhttp = new XMLHttpRequest()
          xmlhttp.open('GET', url, true)
          xmlhttp.responseType = 'blob'
          xmlhttp.onload = function() {
            if (this.status == 200) {
              resolve(this.response)
            } else {
              reject(this.status)
            }
          }
          xmlhttp.send()
        })
      },
      invoicingClick() {
        // let data = JSON.stringify({
        //   paymentManagementList : this.modification
        // })
        // //开票
        //   invoicing(data)
        //   .toPromise()
        //   .then(response => {
        //     console.log(response)
        //   })

        let data = {
          paymentManagementList: this.modification,
        }
        for (let i = 0; i < this.modification.length; i++) {
          if (
            this.modification[i].status != '全部付款' &&
            this.modification[i].status != '部分付款' &&
            this.modification[i].status != '已通过'
          ) {
            this.$message.error('开票只能选择全部付款或部分付款或已通过！')
            return
          }
        }
        //开票
        invoicing(data)
          .toPromise()
          .then((response) => {
            if (response.length > 0) {
              var arr = []
              for (let i = 0; i < response.length; i++) {
                arr.push({
                  fileUrl: response[i],
                  renameFileName: '发票' + i + '.xml',
                })
              }
              this.filesToRar(arr, '开票XML文件')
            }
          })
          .catch(() => {})
      },
      customer(row) {
        getCustomerLook({
            id: row.identityId,
            authenticationStatusKey: 7,
          })
          .toPromise()
          .then((response) => {
            this.customerInfo = true
            this.customerlist = response
            this.customerlist.cardAddressUrl1 =
              this.customerlist.cardAddressUrl.split(',')[0]
            this.customerlist.cardAddressUrl2 =
              this.customerlist.cardAddressUrl.split(',')[1]
            this.customerlist.payeeAddressUrls =
              this.customerlist.payeeAddressUrl.split(',')
          })
      },
      customerclose(e) {
        //  row.textcss = false
        this.customerInfo = false
      },
      //合计
      getSummaries(param) {
        console.log(param)
        const {
          columns,
          data
        } = param
        const sums = []
        var _number = []
        if (this.warehouseName == "鲅鱼圈金信库") {
          _number = [11, 12, 16, 17, 18]
        } else {
          _number = [10, 11, 15, 16, 17]
        }
        if (this.modification.length > 0) {
          columns.forEach((column, index) => {
            console.log(column, index)
            if (index === 0) {
              sums[index] = '合计'
            } else if (index === 10 || index === 11 || index === 15 || index === 16) {
              const values = this.modification.map((item) => Number(item[column.property]))
              if (!values.every((value) => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] = sums[index].toFixed(3)
              } else {
                // sums[index] = '元'
              }
            } else {
              sums[index] = '--'
            }
          })
        } else {
          columns.forEach((column, index) => {
            if (index === 0) {
              sums[index] = '合计'
            } else if (index === _number[0] || index === _number[1] || index === _number[2] || index === _number[
              3] || index === _number[4]) {
              const values = data.map((item) => Number(item[column.property]))
              if (!values.every((value) => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] = sums[index].toFixed(3)
              } else {
                // sums[index] = '元'
              }
            } else {
              sums[index] = '--'
            }
          })
        }

        // sums[6]=sums[6].toFixed(2)
        // sums[sums.length-2]=sums[sums.length-2].toFixed(2)
        return sums
      },
      selectType(val) {
        for (let i = 0; i < this.ruleForm.type.length; i++) {
          switch (this.ruleForm.type[i]) {
            case '打印身份证（正反面）':
              this.isShowPrintType1 = !this.isShowPrintType1
              break
            case '打印银行卡（正反面）':
              this.isShowPrintType2 = !this.isShowPrintType2
              break
            case '打印结算凭证':
              this.isShowPrintType3 = !this.isShowPrintType3
            case '打印检斤单':
              this.isShowPrintType4 = !this.isShowPrintType4
              break
          }
        }
      },
      typePrintCannelClick() {
        this.isShowPrintType = false
      },
      typePrintClick(type) {
        // type 1批量打印 0单个打印
        //  this.isShowPrint = true
        this.selectCustomerList = []
        this.selectPrintList = []
        if (type == 1) {
          let index1 = 0
          let index2 = 0
          for (let i = 0; i < this.modification.length; i++) {
            getCustomerLook({
                id: this.modification[i].identityId,
                authenticationStatusKey: 7,
              })
              .toPromise()
              .then((response) => {
                this.selectCustomerList.push(response)
                index2++
                if (
                  index1 == this.modification.length &&
                  index2 == this.modification.length
                ) {
                  this.printData.compName = ''
                  // this.isShowPrint = true
                  this.printBig()
                }
                getpaymentexamine({
                    id: this.modification[i].id,
                  })
                  .toPromise()
                  .then((response) => {
                    if (response.compName == '黑龙江秋收有限公司') {
                      response.compName = '黑龙江中天昊元贸易有限公司'
                    }
                    index1++
                    let date = new Date()
                    response.currentTime =
                      date.getFullYear() +
                      '年' +
                      Number(date.getMonth() + 1) +
                      '月' +
                      date.getDate() +
                      '日'
                    this.selectPrintList.push(response)
                    if (
                      index1 == this.modification.length &&
                      index2 == this.modification.length
                    ) {
                      this.printData.compName = ''
                      // this.isShowPrint = true
                      this.printBig()
                    }
                  })
              })
          }
        } else {
          let _url1 = process.env.VUE_APP_BASE_API + '/identityAuthenticationInfo/api/getIdentityAuthenticationInfo'
          let _url2 = process.env.VUE_APP_BASE_API + '/paymentManagement/getInfo'
          this.$axios.all([
            this.$axios.get(_url1, {
              params: {
                id: this.rowData.identityId,
                authenticationStatusKey: 7,
              }
            }).then(res => res.data),
            this.$axios.get(_url2, {
              params: {
                id: this.rowData.id
              }
            }).then(res => res.data)
          ]).then(
            this.$axios.spread((val1, val2) => {
              // val 是数组中每个接口返回的值 res.data
              console.log('两个接口全部加载完成', val1, val2);
              this.printData = val2.data
              if (val2.data.compName == '黑龙江秋收有限公司') {
                this.printData.compName = '黑龙江中天昊元贸易有限公司'
              }
              this.isShowPrint = true
              // if(this.printData.solidGrainPrice){
              //   this.printData.solidGrainPrice = (this.printData.tidalGrainPrice * this.printData.netWeight)/this.printData.pureWeight
              // }
              let date = new Date()
              this.printData.currentTime =
                date.getFullYear() +
                '年' +
                Number(date.getMonth() + 1) +
                '月' +
                date.getDate() +
                '日'
            })
          ).catch(err => {
            console.log(err);
          })
          // getCustomerLook({
          //     id: this.rowData.identityId,
          //     authenticationStatusKey: 7,
          //   })
          //   .toPromise()
          //   .then((response) => {
          //     this.customerList = response
          //     getpaymentexamine({
          //         id: this.rowData.id,
          //       })
          //       .toPromise()
          //       .then((response) => {
          //         this.printData = response
          //         this.isShowPrint = true
          //         // if(this.printData.solidGrainPrice){
          //         //   this.printData.solidGrainPrice = (this.printData.tidalGrainPrice * this.printData.netWeight)/this.printData.pureWeight
          //         // }
          //         let date = new Date()
          //         this.printData.currentTime =
          //           date.getFullYear() +
          //           '年' +
          //           Number(date.getMonth() + 1) +
          //           '月' +
          //           date.getDate() +
          //           '日'
          //       })
          //   })
        }
      },
      handleRowClick(row) {
        // if (row.status != '已驳回') {
        //   if (
        //     row.taskId == null &&
        //     row.status != '已通过' &&
        //     row.status != '部分付款'
        //   ) {
        //     return false
        //   } else {
        //     this.$refs.paymentList.toggleRowSelection(row)
        //     return true
        //   }
        // } else {
        //   this.$refs.paymentList.toggleRowSelection(row)
        //   return true
        // }
        return true
      },
      handlepass() {
        var that = this
        if (this.modification.length == 0) {
          this.$message.warning('请选择要通过的条目')
        } else {
          this.$confirm(`审核通过后，任务将发送给财务，是否确定通过？`, {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning',
          }).then(() => {
            that.audit(this.modification[0], 0, true, 2)
          })
        }
      },
      //查看付款截图
      showPayImg(row) {
        // if (!row.paymentScreenshot) {
        //   this.$message({
        //     message: '暂无付款截图！',
        //     type: 'warning',
        //   })
        //   return
        // } else {
        this.showPayImgs = true
        this.id = row.id
        var arr = row.paymentScreenshot.split('$')
        console.log(arr)
        this.payImg = []
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] != '') {
            this.payImg.push({
              url: arr[i]
            })
          }
        }
        // }
      },
      getWarehouse() {
        let _wareHouse = localStorage.getItem('houseSelfCollect_house1')
        _wareHouse = JSON.parse(_wareHouse)
        selectWarehouseSelf({
            compId: localStorage.getItem('ws-pf_compId'),
          })
          .toPromise()
          .then((response) => {
            this.warehouseList = response
            if (this.$route.query.warehouseName) {
              //判断是否在任务页面进来
              this.warehouseName = this.$route.query.warehouseName
              this.warehouseNameKey = this.$route.query.warehouseName
              this.getList()
            } else {
              for (let index = 0; index < this.warehouseList.length; index++) {
                if (_wareHouse && _wareHouse.value == this.warehouseList[index].warehouseName) {
                  this.warehouseName = this.warehouseList[index].warehouseName
                  this.warehouseNameKey = this.warehouseList[index].warehouseName
                  break
                } else {
                  this.warehouseNameKey = this.warehouseList[0].id
                  if (this.warehouseName) {
                    this.warehouseNameKey = this.WAREHOUSE[3].payname
                  } else {
                    this.WAREHOUSE[3].payname = this.warehouseList[0].id
                    this.warehouseName = this.warehouseList[0].warehouseName
                  }
                }
              }
            }
            this.getList()
          })
      },
      //上传付款截图
      handleAvatarSuccess(e) {
        this.imageUrl = e.url
      },
      handleAvatarSuccess1(file) {
        if (this.payImg[0]) {
          this.$set(this.payImg[0], 'url', file.url)
        } else {
          this.payImg[0] = {
            url: file.url
          }
        }
        settlementEdit({
            id: this.id,
            paymentScreenshot: this.payImg[0].url
          }).toPromise()
          .then((response) => {
            this.showPayImgs = false
            this.$message.success('修改成功')
            this.getList()
          })
      },
      _handleRemove() {
        this.payImg[0].url = ''
        settlementEdit({
            id: this.id,
            paymentScreenshot: this.payImg[0].url
          }).toPromise()
          .then((response) => {
            this.showPayImgs = false
            this.$message.success('修改成功')
            this.getList()
          })
      },
      printSmall() {
        window.open(
          '../../../../../static/payprint.html?type=1&dataList=' +
          JSON.stringify(this.printData)
        )
      },
      printBig() {
        let _list1 = []
        let _list2 = []
        if (this.printType == 1) {
          localStorage.setItem('cwprint', true)
          // 财务批量打印数据
          localStorage.setItem(
            'selectPrint_selectPrintList',
            JSON.stringify(this.selectPrintList)
          )
          localStorage.setItem(
            'selectPrint_selectCustomerList',
            JSON.stringify(this.selectCustomerList)
          )
        } else if (this.printType == 0) {
          localStorage.setItem('cwprint', true)
          _list1 = JSON.stringify(this.printData)
          _list2 = JSON.stringify(this.customerList)
        } else {
          _list1 = JSON.stringify(this.printData)
          _list2 = JSON.stringify(this.customerList)
        }
        window.open(
          '../../../../../static/payprint.html?type=2&dataList=' +
          _list1 +
          '&customerList=' +
          _list2 +
          '&printTypeList=' +
          this.ruleForm.type,
          '结算凭证'
        )
      },
      getList() {
        this.payments = {
          amountNotPayable: 0,
          paymentDate: '',
        }
        var searchParam = ''
        if (this.searchType != -1) {
          searchParam = this.searchType
        }
        var startDate = ''
        var endDate = ''
        if (this.value2) {
          startDate = this.value2[0] ? this.value2[0] : ''
          endDate = this.value2[1] ? this.value2[1] : ''
        }

        getpayment({
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            startDate: startDate,
            endDate: endDate,
            searchKeyWord: this.searchKeyWord,
            searchType: searchParam,
            warehouseName: this.warehouseName,
            managementType: 1,
            invoicing: this.invoicing,
            compId: localStorage.getItem('ws-pf_compId'),
          })
          .toPromise()
          .then((response) => {
            this.paymentList = response.records
            this.deptBudgetTotal = response.total
          })
        // getJurisdiction({
        //   managementType: 1,
        //   warehouseName: this.warehouseName,
        //   compId: localStorage.getItem('ws-pf_compId')
        // })
        //   .toPromise()
        //   .then(response => {
        //     this.isShowAdopt = response
        //   })
      },
      del(row) {
        this.$confirm(
            '对应的质检和检斤记录将一并删除，是否确定删除操作？',
            '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
          .then(() => {
            delpayment({
                id: row.id,
              })
              .toPromise()
              .then((response) => {
                this.$message.success('删除成功')
                this.getList()
              })
          })
          .catch(() => {
            return false
          })
      },
      screen(num) {
        if (num == 0) {
          this.searchType = -1
          this.invoicing = num
        } else {
          this.invoicing = ''
          this.searchType = num
        }
        this.currentPage = 1
        this.getList()
      },
      find() {
        this.getList()
      },
      settlement(index, row) {
        if (row.goodsName) {
          localStorage.setItem('paymentManagementReturn', false)
          this.$router.push({
            path: 'settlement',
            query: {
              type: index,
              id: row.id,
            },
          })
        }
      },
      payment() {
        this.imageUrl = ''
        if (this.modification.length == 0) {
          this.$message.warning('请选择要付款的条目')
        } else {
          for (let i = 0; i < this.modification.length; i++) {
            if (this.modification[i].status != '已驳回') {
              if (
                this.modification[i].approveStatus == '待决策人审核' || this.modification[i].approveStatus == '待财务审核' ||
                this.modification[i].status == '全部付款'
              ) {
                this.$message.error(
                  '请选择状态为已通过且待结算或者部分付款的条目'
                )
                return false
              } else {}
            } else {
              this.$message.error('状态为已驳回的条目不能付款')
              return false

            }
          }
          let sum = 0
          let count = 0
          for (let i = 0; i < this.modification.length; i++) {
            sum += this.modification[i].amountIngPayable
            count += this.modification[i].amountEdPayable
          }
          this.payments.amountNotPayable = (sum - count).toFixed(2)
          this.paymentForm = true
        }
      },
      paymentSubmit() {
        if (!this.payments.money) {
          this.$message({
            message: '付款金额不能为空',
            type: 'warning',
          })
          return
        }
        if (
          Number(this.payments.money) > Number(this.payments.amountNotPayable)
        ) {
          this.$message({
            message: '付款金额不能超过未付金额',
            type: 'warning',
          })
          return
        }
        if (!this.payments.paymentDate) {
          this.$message({
            message: '付款日期不能为空',
            type: 'warning',
          })
          return
        }
        if (!this.imageUrl) {
          this.$message({
            message: '请上传付款截图 ',
            type: 'warning',
          })
          return
        }
        this.payments.paymentScreenshot = this.imageUrl
        this.payments.cashier = localStorage.getItem('ws-pf_staffName')
        this.payments.paymentManagementList = this.modification
        this.$confirm('确定提交付款信息？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            //付款提交
            paymentCommit(this.payments)
              .toPromise()
              .then((response) => {
                this.$notify.success({
                  title: '成功',
                  message: '付款成功',
                })
                this.paymentForm = false
                this.getList()
              })
          })
          .catch(() => {
            return false
          })
      },
      reject() {
        if (this.modification.length == 0) {
          this.$message.warning('请选择要驳回的条目')
        } else {
          this.$confirm('是否确定驳回？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
            .then(() => {
              this.audit(this.modification[0], 0, false, '', '')
            })
            .catch(() => {
              return false
            })
        }
      },
      audit(item, index, status, status2, reason) {
        if (index < this.modification.length) {
          if (status == true && item.status == '已驳回') {
            auditpayment({
                compId: localStorage.getItem('ws-pf_compId'),
                id: item.id,
              })
              .toPromise()
              .then((response) => {
                workflowcontent({
                    workflowId: item.workflowId,
                    businessKey: item.id,
                    type: '付款管理'
                  }).toPromise()
                  .then((response1) => {
                    console.log(response1)
                    // this.$message.success('审核成功')
                    // this.$router.push({ path: 'tranManagementWarehouseInOuttask' })
                  })
                this.audit(
                  this.modification[index + 1],
                  index + 1,
                  status,
                  status2,
                  reason
                )
              })
          } else {
            posthandle({
                taskId: item.taskId,
                approved: status,
                auditMind: reason != undefined ? '已驳回' : '34',
                needReapply: status2 != undefined ? true : false,
              })
              .toPromise()
              .then((response) => {
                workflowcontent({
                    workflowId: item.workflowId,
                    businessKey: item.id,
                    type: '付款管理'
                  }).toPromise()
                  .then((response1) => {
                    console.log(response1)
                    // this.$message.success('审核成功')
                    // this.$router.push({ path: 'tranManagementWarehouseInOuttask' })
                  })
                // postqueryhandle({workflowId:item.workflowId}).toPromise()
                // .then((response) => {
                this.audit(
                  this.modification[index + 1],
                  index + 1,
                  status,
                  status2,
                  reason
                )
                // })
              })
              .catch((req) => {
                this.$message.warning(req.message)
              })
          }
        } else {
          if (status == true) {
            this.$message.success('通过成功')
            this.getList()
          } else if (status == false) {
            this.$message.success('驳回成功')
            this.getList()
          }
        }
      },
      adopt() {
        var that = this
        if (this.modification.length == 0) {
          this.$message.warning('请选择要通过的条目')
        } else {
          this.$confirm('是否确定通过？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
            .then(() => {
              this.audit(this.modification[0], 0, true)
            })
            .catch(() => {
              return false
            })
        }
      },
      print1(row) {
        this.printType = 0
        this.isShowPrintType = true
        this.rowData = row
        localStorage.setItem('cwprint', true)
      },
      print(row) {
        this.printType = 2
        localStorage.setItem('cwprint', false)
        getpaymentexamine({
            id: row.id,
          })
          .toPromise()
          .then((response) => {
            this.printData = response
            if (response.compName == '黑龙江秋收有限公司') {
              this.printData.compName = '黑龙江中天昊元贸易有限公司'
            }
            this.isShowPrint = true
            // if(this.printData.solidGrainPrice){
            //   this.printData.solidGrainPrice = (this.printData.tidalGrainPrice * this.printData.netWeight)/this.printData.pureWeight
            // }
            let date = new Date()
            this.printData.currentTime =
              date.getFullYear() +
              '年' +
              Number(date.getMonth() + 1) +
              '月' +
              date.getDate() +
              '日'
          })
      },
      examine() {
        if (this.modification.length == 0) {
          this.$message.warning('请选择要审核的条目')
        } else {
          this.$confirm('审核通过后，任务将发送给财务，是否确定通过？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
            .then(() => {})
            .catch(() => {
              return false
            })
        }
      },
      selectInit(row) {
        //在这里一定要记得类型匹配的上。
        // if (row.status != '已驳回') {
        //   if (
        //     row.taskId == null &&
        //     row.status != '已通过' &&
        //     row.status != '部分付款'
        //   ) {
        //     return false
        //   } else {
        //     return true
        //   }
        // } else {
        //   return true
        // }
        return true
      },
      handleSelectionChange(val) {
        this.modification = val
      },
      warehouseChange(e) {
        for (let i = 0; i < this.warehouseList.length; i++) {
          if (this.warehouseList[i].id == this.warehouseNameKey) {
            this.warehouseName = this.warehouseList[i].warehouseName


            localStorage.setItem('houseSelfCollect_house1',
              JSON.stringify({
                value: this.warehouseList[i].warehouseName,
                warehouseId: this.warehouseList[i].id,
                allowEdit: this.warehouseList[i].allowEdit,
                monitorUrl1: this.warehouseList[i].monitorUrl1,
                monitorUrl2: this.warehouseList[i].monitorUrl2,
                warehouseNo: this.warehouseList[i].commonWarehouseNo,
                compId: localStorage.getItem('ws-pf_compId')
              })
            )
            this.WAREHOUSE[3].payname = this.warehouseList[i].id
          }
        }
        this.getList()
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`)
        this.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        console.log(`当前页: ${val}`)
        this.getList()
      },
    },
  }
</script>
<style lang="scss" scoped>
  .ws-info-table {
    border: none;
  }

  .ws-info-table .el-form-item {
    width: 50%;
    border: none;
  }

  /deep/.ws-info-table .el-form-item .el-form-item__label {
    width: 30%;
    min-width: 125px;
    text-align: center;
    background: #ffffff;
    color: #8890b1;
  }

  /deep/.ws-info-table .el-form-item .el-form-item__content {
    border: none;
  }

  /deep/.el-dialog__title {
    font-size: 24px !important;
  }

  /deep/.el-dialog__header {
    text-align: center !important;
    padding: 10px 0 !important;
    height: auto !important;
    // border-bottom: none !important;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
  }

  .title {
    font-size: 16px;
    font-weight: 600;
  }

  table,
  table tr th,
  table tr td {
    border: 2px solid #333333;
    padding: 5px 0;
  }

  table {
    width: 100%;
    min-height: 25px;
    line-height: 25px;
    text-align: center;
    border-collapse: collapse;
    border: 3px solid #333333;
  }

  .formItem {
    width: 70% !important;
  }

  /deep/.el-table .el-table__header .cell,
  /deep/.el-table .cell {
    text-align: center;
    line-height: 15px;
  }

  /deep/.el-table--enable-row-transition .el-table__body td {
    text-align: center;
  }

  .title {
    padding: 10px;
    text-align: center;
  }

  .tanchuang {
    margin: 0 auto;
  }

  .tanchuang .ws-info-table {
    display: initial;
  }

  .tanchuang .ws-info-table .el-form-item {
    margin: 0 auto;
    text-align: center;
  }

  .upLoad {
    width: 40%;
    margin: 0 auto;
    // border: 1px solid #8890b1;
    // border-radius: 3px;
  }

  // .avatar{
  //   width: 150px;
  //   height: 150px;
  // }
  .avatar-uploader {
    position: relative;
    width: 178px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px solid #8890b1;
    border-radius: 5px;
  }

  .avatar {
    width: 178px;
    height: 178px;
    border: 1px solid #8890b1;
    border-radius: 5px;
    display: block;
  }

  .pay_img {
    width: 50%;
    // display: flex;
    display: inline-block;

    .img {
      height: 350px;
      width: 100%;
    }
  }

  .print-type {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 200px;
    height: 250px;
    background: white;
    border-radius: 10px;
    z-index: 999;
  }

  .label-width {
    width: 100%;
  }

  .mask {
    background: black;
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    z-index: 99;
    opacity: 0.3;
  }

  .print-type-title {
    text-align: center;
    font-size: 18px;
    margin: 20px;
  }

  .bottom-btn {
    margin: 20px 0;
    text-align: center;
  }

  .print-type-checkbox {
    padding-left: 20px;
  }

  .img_css {
    width: 90%;
    height: 220px;
  }

  .text_css {
    color: #5878e8;
  }

  /deep/.base_header_layout {
    height: 48px;
  }

  .warehouse_select {
    width:150px;
  }

  // .el-button {
  //   margin: 5px;
  // }

  .no-messege {
    text-align: center;
    font-size: 30px;
    padding: 50px;
  }

  .my-img {
    width: 200px;
    height: 200px;
  }

  .el-icon-delete {
    font-size: 20px;
  }

  /deep/.base_header_layout .find.el-button--primary {
    width: 30px;
    margin: 0;
    border-top-left-radius: 0px;
    border-bottom-left-radius: 0px;
  }
.findinput {
  width: 230px;
}
  /deep/.base_header_layout .findinput input {
    border-top-right-radius: 0px;
    border-bottom-right-radius: 0px;
  }
  .top-btn{
    display:flex;
    justify-content: space-between;
    .right,.serch{
      display: flex;
      .find{
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .date-select{
      width: 240px;
    }
  }
  .top-btn-two{
    margin-top: 20px;
  }
  .content-top{
    display: flex;
    margin-top: 20px;
  }
  .customer-item{
    margin-bottom: 0;
    display: flex;
  }
  .el-form-item__content{
    width: 100%;
    margin-left: 0!important;
  }
  .el-date-editor{
    width: 220px!important;
  }
</style>
