<template>
  <div>
    <EMSTableNew
      ref="prepareAudit"
      :server="server"
      :autoFirst="false"
      action="queryAuditTable"
      :params="form"
      :columnsFn="preparePayColumns"
      :changePageFun="changePageFun"
      @on-selection-change="getSelections"
    >
      <Form
        slot="search-bar"
        ref="form"
        :model="form"
        :label-width="120"
        class="audit-form"
      >
        <Row>
          <Col span="6">
          <Form-item
            prop="ouCode"
            label="归属公司"
          >
            <Select
              v-model="form.ouCode"
              filterable
              transfer
              clearable
            >
              <Option
                v-for="item in companyList"
                :key="item.companyCode"
                :value="item.companyCode"
              >
                {{ item.ouName }}
              </Option>
            </Select>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="vendorName"
            label="供应商名称"
          >
            <Input
              v-model="form.vendorName"
              type="text"
              maxlength="30"
              clearable
            ></Input>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="claimNo"
            label="付款申请单号"
          >
            <Input
              v-model="form.claimNo"
              type="text"
              maxlength="30"
              clearable
            ></Input>
          </Form-item>
          </Col>

          <Col
            v-show="!showMore"
            span="6"
          >
          <div class="search_btns ivu-form-item">
            <Button
              type="warning"
              class="ems-btn-medium ems-btn-type1"
              style="padding: 0 18px;"
              @click.native="search"
            >
              {{ $t("查询") }}
            </Button>
            <Button
              class="ems-btn-medium ems-btn-type3"
              style="padding: 0 18px;"
              @click.native="reset"
            >
              {{ $t("重置") }}
            </Button>
            <a @click="changeShowMore">{{ $t('查看更多') }}</a>
          </div>
          </Col>

          <Col span="6">
          <Form-item label="到期日">
            <div
              class="pick-set-date"
              style="display: flex;height: 32.38px;"
            >
              <Date-picker
                v-model="form.startDueToDate"
                :editable="false"
                type="date"
                format="yyyy/MM/dd"
                clearable
                transfer
                style="flex: 1;"
              ></Date-picker>
              <span>-</span>
              <Date-picker
                v-model="form.endDueToDate"
                :editable="false"
                type="date"
                format="yyyy/MM/dd"
                clearable
                style="flex:1;"
                transfer
              ></Date-picker>
            </div>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="invoiceNo"
            label="发票编号"
          >
            <Input
              v-model="form.invoiceNo"
              type="text"
              maxlength="30"
              clearable
            ></Input>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="invoiceClaimNo"
            label="关联报账单号"
          >
            <Input
              v-model="form.invoiceClaimNo"
              type="text"
              maxlength="30"
              clearable
            ></Input>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="applyEmpName"
            label="申请人"
          >
            <Input
              v-model="form.applyEmpName"
              type="text"
              maxlength="30"
              clearable
            ></Input>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="categoryCode"
            label="申请类型"
          >
            <Select
              v-model="form.categoryCode"
              class="applyType"
              filterable
              transfer
              clearable
            >
              <Option
                v-for="item in applyTypeList"
                :key="item.categoryCode"
                :value="item.categoryCode"
              >
                {{ item.categoryName }}
              </Option>
            </Select>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="applyDeptName"
            label="申请部门"
          >
            <Input
              v-model="form.applyDeptName"
              type="text"
              maxlength="30"
              clearable
            ></Input>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="createTime"
            label="申请单创建日期"
          >
            <Date-picker
              v-model="createTime"
              :editable="false"
              type="daterange"
              format="yyyy/MM/dd"
              clearable
              transfer
            ></Date-picker>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="auditTime"
            label="审批结束日期"
          >
            <Date-picker
              v-model="auditTime"
              :editable="false"
              type="daterange"
              format="yyyy/MM/dd"
              clearable
              transfer
            ></Date-picker>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="vendorType"
            label="供应商类型"
          >
            <DataSelect
              v-model="form.vendorType"
              code="vendorType"
              clearable
              @loadFinish="vendorTypeCodeArray"
            ></DataSelect>
          </Form-item>
          </Col>

          <!-- <Form-item prop="projectCode" label="项目编码">
          <SelectProject @handleSelect="handleSelect" v-model="form.projectCode" isValidity="" isPost="Y" clearable></SelectProject>
        </Form-item> -->

          <Col span="6">
          <Form-item
            prop="currency"
            label="币种"
          >
            <DataSelect
              v-model="form.currency"
              code="currency"
              clearable
              @loadFinish="currencyCodeArray"
            ></DataSelect>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="paymentMethod"
            label="付款方式"
          >
            <DataSelect
              v-model="form.paymentMethod"
              code="PAYMENT_MODE"
              clearable
              @loadFinish="payWayCodeArray"
            ></DataSelect>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="amountRange"
            label="申请金额"
          >
            <!-- v-model="form.amount" -->
            <NumberRangeFix
              :startAmount="form.minApplyAmount"
              :endAmount="form.maxApplyAmount"
              :tofixed="2"
              placeholder=""
              clearable
              @inputStart="onInputStart"
              @inputEnd="onInputEnd"
            />
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="auditStatus"
            label="审核状态"
          >
            <DataSelect
              v-model="form.auditStatus"
              code="AUDIT_STATUS"
              clearable
              @loadFinish="auditStatusCodeArray"
            ></DataSelect>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="priority"
            label="优先级"
          >
            <DataSelect
              v-model="form.priority"
              code="PRIORITY"
              clearable
            ></DataSelect>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            v-show="false"
            prop="capitalPlan"
            label="资金计划"
          >
            <DataSelect
              v-model="capitalPlan"
              :value="capitalPlan"
              code="capitalPlan"
              @loadFinish="loadedCapitalPlan"
            >
            </DataSelect>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            v-show="false"
            prop="transfersType"
            label="付款通道"
          >
            <DataSelect
              v-model="transfersType"
              :value="transfersType"
              code="transfersType"
              @loadFinish="loadedTransfersType"
            >
            </DataSelect>
          </Form-item>
          </Col>

          <Col span="6">
          <Form-item
            prop="contractNo"
            label="合同编号"
          >
            <Input
              v-model="form.contractNo"
              type="text"
              maxlength="30"
              clearable
            ></Input>
          </Form-item>
          </Col>

          <Col
            v-show="showMore"
            span="12"
          >
          <div class="search_btns ivu-form-item">
            <Button
              type="warning"
              class="ems-btn-medium ems-btn-type1"
              style="padding: 0 18px;"
              @click.native="search"
            >
              {{ $t("查询") }}
            </Button>
            <Button
              class="ems-btn-medium ems-btn-type3"
              style="padding: 0 18px;"
              @click.native="reset"
            >
              {{ $t("重置") }}
            </Button>
            <a @click="changeShowMore">{{ $t('隐藏条件') }}</a>
          </div>
          </Col>

          <div
            v-if="showPaymentInfo"
            class="v-summary-tips"
          >
            <span>已选择付款申请行总申请金额:{{ selectApplyAmount }};</span>
            <span
              v-for="(item, index) in accountList"
              v-show="Number(item.value)!=0"
              :key="index"
            >{{ item.name }}:{{ item.value }};</span>
          </div>
        </Row>
      </Form>
      <!-- <div slot="handle-bar">
        <Button
          type="warning"
          icon="search"
          @click.native="search"
        >
          {{ $t('查询') }}
        </Button>
        <Button
          type="info"
          icon="loop"
          @click.native="reset"
        >
          {{ $t('重置') }}
        </Button>
      </div> -->
      <div slot="table-bar">
        <Button
          type="warning"
          icon=""
          :disabled="auditDisabled"
          @click="audit"
        >
          审核
        </Button>
        <Button
          type="warning"
          icon=""
          :disabled="cancelAuditDisabled"
          @click="cancelAudit"
        >
          撤销审核
        </Button>
        <Button
          type="warning"
          :loading="exportLoad"
          icon="plus-round"
          @click="exportData"
        >
          导出
        </Button>
        <!-- <Button type="warning" @click="checkPaymentApplyDetail">付款准备信息修改</Button> -->
      </div>
    </EMSTableNew>
    <PayInfo
      v-show="false"
      ref="payWayInfo"
      :showAmount="payWayInfo.showAmount"
      :disabledFlag="payWayInfo.disabledFlag"
      :companyCode="payWayInfo.companyCode"
      :applyAmount="payWayInfo.applyAmount"
      :payRequestLineId="payWayInfo.payRequestLineId"
      :buCode="payWayInfo.ouCode"
    />
    <Modal
      v-model="modal"
      title="大额提示"
      width="400"
      @on-cancel="onCancel"
      @on-ok="asyncOK"
    >
      <p>{{ tipData }}</p>
      <br />
      <p>确定审核？</p>
    </Modal>
  </div>
</template>
<script>
import miment from 'miment';
import accounting from 'accounting';
import EditPaymentInfo from './EditPaymentInfo.vue';
import util from '@paymentPlatformSrc/tools/util.js';
import { mapState, mapMutations } from 'vuex';
import {
  // SelectProject,
  NumberRangeFix,
  PayInfo,
  PaymentInfoRead
} from '@paymentPlatformComps/index.js';
import Server from './server.js';
const server = new Server();
let vm;
export default {
  components: {
    // SelectProject,
    NumberRangeFix,
    PayInfo
    // PaymentInfoRead,
  },
  data() {
    return {
      modal: false,
      tipData: '',
      payRequestLineIdArr: [],
      exportLoad: false,
      companyList: [],
      auditDisabled: true,
      cancelAuditDisabled: true,
      payMentModeData: {},
      accountList: [],
      capitalPlan: '',
      transfersType: '',
      capitalPlanData: [],
      transfersTypeData: [],
      showPaymentInfo: false,
      acceptanceAmount: 0,
      creditAmount: 0,
      reverseAmount: 0,
      getInvoAmount: 0,
      replaceAmount: 0,
      otherAmount: 0,
      bankTransAmount: 0,
      invoAmount: 0,
      draftAmount: 0,
      rejectAmount: 0,
      transAmount: 0,
      transferAmount: 0,
      DPAmount: 0,
      checkAmount: 0,
      chargeAmount: 0,
      orderAmount: 0,
      codeValues: {},
      auditStatusMap: [],
      payStateMap: [],
      payWayMap: [],
      currencyMap: [],
      vendorTypeMap: [],
      server: server,
      showAmount: true,
      selections: [],
      applyTypeList: [],
      dueDate: [],
      auditTime: [],
      createTime: [],
      priorityArry: [],
      selectApplyAmount: 0,
      form: {
        ouCode: '',
        claimNo: '',
        categoryCode: '',
        applyEmpName: '',
        applyDeptName: '',
        vendorName: '',
        vendorType: '',
        projectCode: '',
        amount: [],
        currency: '',
        paymentMethod: '',
        invoiceNo: '',
        invoiceClaimNo: '',
        // payState: "",
        auditStatus: '0',
        startCreateTime: '',
        endCreateTime: '',
        createTime: '',
        // dueDate: "",
        auditTime: '',
        // startDueDate: "",
        // endDueDate: "",
        startAuditTime: '',
        endAuditTime: '',
        priority: '',
        contractNo: '',
        reviceDate: '',
        startDueToDate: '', // 到期日开始
        endDueToDate: '', // 到期日结束
        minApplyAmount: '',
        maxApplyAmount: ''
      },
      // rule: {
      //   reviceDate: [
      //     {
      //       required: true,
      //       message: "请选择到期日"
      //     }
      //   ],
      // },
      payWayInfo: {
        payRequestLineId: '',
        applyAmount: 0,
        companyCode: '',
        disabledFlag: false,
        showAmount: ''
      },
      showMore: false
    };
  },
  computed: {
    ...mapState('createPaymentPreparation', {
      valueSet: state => state.valueSet
    }),
    ...mapState('paymentAudit', {
      priorityList: state => state.priorityList
    })
  },
  created: function() {
    vm = this;
  },
  beforeMount: function() {},
  mounted() {
    const self = this;
    self.$nextTick(() => {
      self.queryAndSetValueSet('PAYMENT_MODE');
      self.queryAndSetValueSet('remittanceSpeed');
      self.queryAndSetValueSet('capitalPlan');
      self.queryAndSetValueSet('LargePaymentReportPayType');
    });
    // 查询付款方式值集
    self.server.queryApplySelect().then(response => {
      if (response.statusCode == '-1') {
        self.$Message.error(response.msg);
      } else {
        self.applyTypeList = response;
      }
    });
    // 查询归属公司
    this.server.queryCompanySelect().then(response => {
      if (response.statusCode == '-1') {
        self.$Message.error(response.msg);
      } else {
        self.companyList = response;
      }
    });

    // 设置到期日位置
    // const setDateDom = document.querySelector('.ivu-form-no-margin-bottom .pick-set-date');
    // const realSetDom = document.querySelector('.ivu-form-no-margin-bottom .pick-set-date .set-title');
    // const getDateWidth = setDateDom.getBoundingClientRect().width;

    // realSetDom.style.top = '0';
    // realSetDom.style.right = -(getDateWidth + 100) + 'px';
    // realSetDom.style.display = 'block';

    // this.form.endDueToDate = miment(new Date()).format('YYYY-MM-DD');
    this.search();
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    ...mapMutations('createPaymentPreparation', ['setValueSet']),
    ...mapMutations('paymentAudit', ['setPriorityList']),
    changeShowMore() {
      this.showMore = !this.showMore;
      this.$refs.prepareAudit.showMore();
    },
    onInputStart(startVal) {
      this.form.minApplyAmount = startVal;
    },
    onInputEnd(endVal) {
      this.form.maxApplyAmount = endVal;
    },
    queryAndSetValueSet(code) {
      if (!code) {
        return;
      }
      const self = this;
      self.server.QueryValueSetByCode({ code: code }).then(response => {
        if (Array.isArray(response)) {
          self.codeValues[code] = response;
        } else {
          self.codeValues[code] = [];
        }
        self.$store.state.createPaymentPreparation.valueSet = self.codeValues;
        if (self.codeValues.length > 2) {
          self.setValueSet(self.codeValues);
        }
      });
    },
    onCancel() {
      this.modal = false;
    },
    asyncOK() {
      this.auditServer();
      this.modal = false;
    },
    handleSelect(data) {
      this.form.projectCode = data.projectCode;
    },
    // 表头字段定义
    preparePayColumns() {
      return [
        {
          type: 'selection',
          width: 60,
          resizable: true,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '付款申请单',
          align: 'left',
          key: 'claimNo',
          sortable: 'custom',
          width: 200,
          resizable: true,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    text: params.row.claimNo,
                    handle: () => {
                      this.openFormPage(params.row);
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: '供应商',
          align: 'left',
          key: 'vendorName',
          width: 220,
          resizable: true,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.vendorName
                  }
                },
                params.row.vendorName
              )
            ]);
          }
        },
        {
          title: '优先级',
          width: 100,
          resizable: true,
          align: 'left',
          // sortable: "custom",
          key: 'priority',
          render: (h, params) => {
            let flag = false;
            if (params.row.auditStatus == '1') {
              flag = true;
            }
            return h('DataSelect', {
              props: {
                value: params.row.priority,
                code: 'PRIORITY'
              },
              attrs: {
                disabled: flag
              },
              on: {
                'on-change': data => {
                  vm.$refs.prepareAudit.tableData[
                    params.index
                  ].priority = data;
                  let flag = false;
                  for (let i = 0; i < vm.priorityList.priority.length; i++) {
                    if (
                      vm.priorityList.priority[i].payRequestLineId ==
                      params.row.payRequestLineId
                    ) {
                      vm.priorityList.priority[i].priority = data;
                      flag = true;
                      break;
                    }
                  }
                  if (!flag) {
                    vm.priorityList.priority.push({
                      priority: data,
                      payRequestLineId: params.row.payRequestLineId
                    });
                  }
                  // 调取修改优先级接口
                  vm.server
                    .updatePriority({
                      priority: +data,
                      payRequestLineId: params.row.payRequestLineId
                    })
                    .then(response => {
                      if (response.statusCode == '-1') {
                        vm.$Message.error(response.msg);
                      } else {
                        vm.$Message.success('修改成功');
                      }
                    });
                }
              }
            });
          }
        },
        {
          title: '申请金额',
          align: 'right',
          key: 'applyAmount',
          // sortable: "custom",
          width: 100,
          resizable: true,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: accounting.formatNumber(params.row.applyAmount, 2)
                  }

                },
                accounting.formatNumber(params.row.applyAmount, 2)
              )
            ]);
          }
        },
        {
          title: '付款信息汇总',
          width: 160,
          resizable: true,
          align: 'left',
          key: 'payInfoGroupAmount',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.payInfoGroupAmount
                  }
                },
                params.row.payInfoGroupAmount
              )
            ]);
          }
        },
        {
          title: '付款信息',
          width: 100,
          resizable: true,
          align: 'left',
          key: 'claimNo',
          sortable: 'custom',
          render: (h, params) => {
            let flag = false;
            if (params.row.auditStatus == '1') {
              // debugger
              return (
                <PaymentInfoRead
                  trigger="hover"
                  placement="top"
                  width="650"
                  payRequestLineId={params.row.payRequestLineId}
                  payMentModeData={vm.payMentModeData}
                  capitalPlanData={vm.capitalPlanData}
                  transfersTypeData={vm.transfersTypeData}
                >
                  <a
                    href="javascript:;"
                    onClick={e => {
                      vm.showPaymentInfoWin(e, params.row);
                    }}
                  >
                    查看
                  </a>
                </PaymentInfoRead>
              );
              // flag = true;
            } else {
              flag = false;
              return (
                <PaymentInfoRead
                  trigger="hover"
                  placement="top"
                  width="650"
                  payRequestLineId={params.row.payRequestLineId}
                  payMentModeData={vm.payMentModeData}
                  capitalPlanData={vm.capitalPlanData}
                  transfersTypeData={vm.transfersTypeData}
                >
                  <a
                    href="javascript:;"
                    onClick={e => {
                      vm.showPaymentEdit(params.row);
                    }}
                  >
                    编辑
                  </a>
                </PaymentInfoRead>
              );
            }
          }
        },
        {
          title: '收款方户名',
          width: 200,
          resizable: true,
          align: 'left',
          // sortable: "custom",
          key: 'receiVendorName',
          // key: "receiVendorName",
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.receiVendorName
                  }
                },
                params.row.receiVendorName
              )
            ]);
          }
        },
        {
          title: '收款账户',
          width: 180,
          resizable: true,
          align: 'left',
          key: 'receiVendorAccountNo',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: `${params.row.receiVendorAccountNo}-${params.row.vendorAreaCode}-${params.row.vendorCbankCode}-${params.row.vendorBankId}`
                  }
                },
                params.row.receiVendorAccountNo
              )
            ]);
          }
        },
        {
          title: '币种',
          width: 100,
          resizable: true,
          align: 'left',
          key: 'currency',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: vm.currencyMap[params.row.currency]
                }
              },
              params.row.currency && vm.currencyMap[params.row.currency]
            );
          }
        },
        {
          title: '合同编号',
          align: 'left',
          key: 'contractNo',
          // sortable: "custom",
          width: 100,
          resizable: true,
          render: (h, params) => {
            return h('RowTools', {
              attrs: {
                title: params.row.contractNo
              },
              props: {
                data: [
                  {
                    text: params.row.contractNo,
                    handle: () => {
                      // 打开新页面查看明细
                      vm.openPayContractNo(params.row);
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: '申请类型',
          align: 'left',
          key: 'categoryName',
          resizable: true,
          width: 160,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.categoryName
                  }
                },
                params.row.categoryName
              )
            ]);
          }
        },
        {
          title: '归属公司',
          align: 'left',
          // sortable: "custom",
          key: 'ouName',
          width: 160,
          resizable: true,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.ouName
                  }
                },
                params.row.ouName
              )
            ]);
          }
        },
        {
          title: '地点',
          align: 'left',
          // key: "vendorSite",
          key: 'receiVendorSite',
          width: 90,
          resizable: true,
          // sortable: "custom",
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.receiVendorSite
                  }
                },
                params.row.receiVendorSite
              )
            ]);
          }
        },

        {
          title: '申请人',
          width: 100,
          resizable: true,
          align: 'left',
          // sortable: "custom",
          key: 'applyEmpName',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.applyEmpName
                  }
                },
                params.row.applyEmpName
              )
            ]);
          }
        },
        {
          title: '申请部门',
          width: 160,
          resizable: true,
          align: 'left',
          // sortable: "custom",
          key: 'applyDeptName',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.applyDeptName
                  }
                },
                params.row.applyDeptName
              )
            ]);
          }
        },

        {
          title: '创建日期',
          width: 160,
          resizable: true,
          align: 'left',
          sortable: 'custom',
          key: 'createdTime',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.createdTime
                  }
                },
                params.row.createdTime
              )
            ]);
          }
        },
        {
          title: '审批结束日期',
          width: 200,
          resizable: true,
          align: 'left',
          sortable: 'custom',
          key: 'workflowPassTime',
          render: (h, params) => {
            let dateTime, lastUpdateTimeArr;
            if (params.row.workflowPassTime) {
              const newDate = new Date(params.row.workflowPassTime).toJSON();
              dateTime = new Date(+new Date(newDate) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
              lastUpdateTimeArr = (dateTime || '').split(' ');
            }
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: dateTime || null
                }
              },
              dateTime || null
            );
          }
        },

        {
          title: '供应商类型',
          align: 'left',
          key: 'vendorType',
          width: 100,
          resizable: true,
          render: (h, params) => {
            let text = '';
            if (params.row.vendorType == 'EMPLOYEE') {
              text = '对私';
            } else if (params.row.vendorType == 'PROVIDER') {
              text = '对公';
            }
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: text
                }
              },
              text
            );
          }
        },
        {
          title: '审核状态',
          width: 100,
          resizable: true,
          align: 'left',
          key: 'auditStatus',
          render: (h, params) => {
            let text = '';
            if (params.row.auditStatus == '1') {
              text = '是';
            } else {
              text = '否';
            }
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: text
                }
              },
              text
            );
          }
        },
        {
          title: '行号',
          align: 'left',
          key: 'payRequestLineId',
          sortable: 'custom',
          width: 80,
          resizable: true,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.payRequestLineId
                  }
                },
                params.row.payRequestLineId
              )
            ]);
          }
        }
      ];
    },

    // 搜索
    search(cb, page = 1) {
      this.form.startCreateTime = this.createTime[0];
      this.form.endCreateTime = this.createTime[1];
      if (this.form.startCreateTime != '') {
        this.form.startCreateTime = miment(this.form.startCreateTime).format(
          'YYYY-MM-DD'
        );
      }
      if (this.form.endCreateTime != '') {
        this.form.endCreateTime = miment(this.form.endCreateTime)
          .add(1, 'DD')
          .add(-1, 'ss')
          .format('YYYY-MM-DD');
      }
      if (this.form.startDueToDate != '') {
        this.form.startDueToDate = miment(this.form.startDueToDate)
          .add(1, 'DD')
          .add(-1, 'ss')
          .format('YYYY-MM-DD');
      }
      if (this.form.endDueToDate != '') {
        this.form.endDueToDate = miment(this.form.endDueToDate)
          .add(1, 'DD')
          .add(-1, 'ss')
          .format('YYYY-MM-DD');
      }

      // 判断到期日期
      if (this.form.startDueToDate != '' && this.form.endDueToDate != '') {
        const dTime = (new Date(this.form.startDueToDate).getTime()) -
          (+new Date(this.form.endDueToDate).getTime());
        if (dTime > 0) {
          this.$Message.info('到期日的开始时间不能大于结束的日期！');
          return;
        }
      }
      // this.form.startDueDate = this.dueDate[0];
      // this.form.endDueDate = this.dueDate[1];
      // if (this.form.startDueDate != "") {
      //   this.form.startDueDate = miment(this.form.startDueDate).format(
      //     "YYYY-MM-DD hh:mm:ss"
      //   );
      // }
      // if (this.form.endDueDate != "") {
      //   this.form.endDueDate = miment(this.form.endDueDate)
      //     .add(1, "DD")
      //     .add(-1, "ss")
      //     .format("YYYY-MM-DD hh:mm:ss");
      // }
      this.form.startAuditTime = this.auditTime[0];
      this.form.endAuditTime = this.auditTime[1];
      if (this.form.startAuditTime != '') {
        this.form.startAuditTime = miment(this.form.startAuditTime).format(
          'YYYY-MM-DD'
        );
      }
      if (this.form.endAuditTime != '') {
        this.form.endAuditTime = miment(this.form.endAuditTime)
          .add(1, 'DD')
          .add(-1, 'ss')
          .format('YYYY-MM-DD');
      }
      if (this.form.ouCode == undefined) {
        this.form.ouCode = '';
      }

      // this.$refs['form'].validate(valid => {
      // if (valid) {
      this.$refs.prepareAudit.load(this.form, page, function(data) {
        // for (let i = 0; i < vm.$refs["prepareAudit"].tableData.length; i++) {
        //   if (
        //     vm.$refs["prepareAudit"].tableData[i].auditStatusName == "已审核"
        //   ) {
        //     vm.$refs["prepareAudit"].tableData[i]._disabled = true;
        //   }
        // }
        // cb && cb();
      });
      // } else {
      // return;
      // }
      // });
      this.getSelections([]);
    },
    changePriority() {
      for (let i = 0; i < vm.priorityList.priority.length; i++) {
        for (let m = 0; m < vm.$refs.prepareAudit.tableData.length; m++) {
          if (
            vm.priorityList.priority[i].payRequestLineId ==
            vm.$refs.prepareAudit.tableData[m].payRequestLineId
          ) {
            vm.$refs.prepareAudit.tableData[m].priority =
              vm.priorityList.priority[i].priority;
            break;
          }
        }
      }
    },
    // 重置
    reset() {
      this.createTime = ['', ''];
      this.auditTime = ['', ''];
      this.dueDate = ['', ''];
      const form = this.form;
      Object.keys(form).map(key => {
        if (key != 'auditStatus') {
          form[key] = '';
        } else {
          form[key] = '0';
        }
      });
      // this.$refs.form.resetFields();
      // this.form.endDueToDate = miment(new Date()).format('YYYY-MM-DD');
      this.search();
    },
    setReviceDate() {
      this.form.startDueToDate = '2099-12-31';
      this.form.endDueToDate = '2099-12-31';
    },
    // 查看行明细 打开新页面
    openPayBatch(data) {
      const newWindow = window.open();
      data.openFromPayPlatform = true;
      const params = {
        claimId: data.claimId,
        claimNo: data.claimNo,
        categoryName: data.categoryName,
        categoryCode: data.categoryCode || '',
        createdTime: data.createdTime,
        updateTime: data.updateTime,
        openFromPayPlatform: data.openFromPayPlatform,
        newWindow: newWindow
      };
      util.openByClaimIdAndClaimNo(params);
    },
    // 合同编号跳转
    openContractNo(data) {
      const newWindow = window.open();
      data.openFromPayPlatform = true;
      const params = {
        claimId: data.claimId,
        claimNo: data.claimNo,
        openFromPayPlatform: data.openFromPayPlatform,
        newWindow: newWindow
      };
      util.openByClaimIdAndClaimNo(params);
    },
    getKey(label) {
      const data = this.codeValues.PAYMENT_MODE;
      const obj = data.find(item => item.label === label);
      if (obj) {
        return obj.value;
      } else {
        return '';
      }
    },
    handleSelections() {
      const payInfoList = []; // 把付款信息数据放到每行中
      const payRequestLineIds = this.selections.map(item => item.payRequestLineId);
      const largeDataList = this.codeValues.LargePaymentReportPayType || []; // 要显示大额提示的数据
      this.server.queryBatchFindListPayInfo(payRequestLineIds).then(res => {
        const list = [];
        if (res) {
          for (const key in res) {
            this.selections.forEach(item => {
              const payInfoName = item.payInfoGroupAmount.split(':')[0].trim();
              const key1 = this.getKey(payInfoName);
              if (key == item.payRequestLineId) {
                largeDataList.forEach(item2 => {
                  if (item2.value === key1) {
                    if (res[key].length > 0) {
                      for (const item1 of res[key]) {
                        if (item1.payAmount >= 20000000) {
                          list.push(item);
                          break;
                        }
                      }
                    }
                  }
                });
              }
            });
          }
        } else {
        }
        const tipList = list.map(item => {
          return `${item.claimNo}${item.vendorAccountName}`;
        });
        if (tipList.length > 0) {
          const tip = tipList.join(';') + '的付款金额达到大额报备要求，请在OA发起大额报备申请。';
          this.tipData = tip;
          this.modal = true;
        } else {
          this.auditServer();
        }
      });
    },
    // 审核
    audit() {
      const self = this;
      if (self.selections.length == 0) {
        self.$Message.info('请至少勾选一条数据');
      } else {
        const labelList = ['银企直连', '汇票背书', '银行网银', '支票', '汇票开票', '微信支付'];// 付款方式为银企直连、汇票背书、银行网银、支票、汇票开票、微信支付label
        let vendorFlag = false;// 设置参数判断供应商是否和收款账户一样
        const vendorList = [];// 存储供应商与收款账户不一致的信息
        let text = '';
        for (let m = 0; m < self.selections.length; m++) {
          if (self.selections[m].payInfoGroupAmount.trim() == '') {
            self.$Message.info('付款信息不能为空');
            return;
          }
          if ((self.selections[m].vendorName).replace(/,/g, '') != (self.selections[m].vendorAccountName).replace(/,/g, '')) {
            vendorList.push({
              vendorName: (self.selections[m].vendorName).replace(/,/g, ''),
              vendorAccountName: (self.selections[m].vendorAccountName).replace(/,/g, ''),
              payRequestLineId: self.selections[m].payRequestLineId
            });
            text += '序号(' + self.selections[m].payRequestLineId + ')供应商(' + (self.selections[m].vendorName).replace(/,/g, '') + ')与收款单位(' + (self.selections[m].receiVendorName).replace(/,/g, '') + ')不一致;' + '<br/>';
            vendorFlag = true;
          }
        }
        this.payRequestLineIdArr = [];
        for (let i = 0; i < self.selections.length; i++) {
          this.payRequestLineIdArr.push(
            self.selections[i].payRequestLineId
          );
        }
        if (vendorFlag) {
          new $confirm(text + '<br/>' + '确定审核吗？', this).then(() => {
            self.handleSelections();
          });
        } else {
          self.handleSelections();
        }
      }
    },
    auditServer() {
      const self = this;
      self.server.audit(this.payRequestLineIdArr).then(response => {
        if (response.code == '0') {
          self.$Message.error(response.msg);
        } else {
          this.search();
          self.$Message.success('审核成功');
          this.getSelections([]);
        }
      });
    },
    // 撤销审核
    cancelAudit() {
      const payRequestLineId = [];
      const self = this;
      if (self.selections.length == 0) {
        self.$Message.info('请至少勾选一条数据');
      } else {
        for (let i = 0; i < self.selections.length; i++) {
          payRequestLineId.push(self.selections[i].payRequestLineId);
        }
        self.server.cancelAudit(payRequestLineId).then(response => {
          if (response.code == '0') {
            self.$Message.error(response.msg);
          } else {
            this.search();
            self.$Message.success('撤销审核成功');
            this.getSelections([]);
          }
        });
      }
    },
    // 获取选中数
    getSelections(selections) {
      // 获取选中数后首先判断是否全是已审核或者是未审核
      if (selections.length > 0) {
        let flag = false;
        for (let j = 0; j < selections.length; j++) {
          if (selections[0].auditStatus != selections[j].auditStatus) {
            flag = true;
            break;
          }
        }
        if (flag) {
          vm.$Message.info('勾选项的审核状态必须一致');
          vm.$refs.prepareAudit.tableData.forEach(function(item) {
            item._checked = false;
          });
          vm.selections.forEach(function(item) {
            try {
              vm.$refs.prepareAudit.tableData.forEach(function(auditItem) {
                if (item.payRequestLineId == auditItem.payRequestLineId) {
                  auditItem._checked = true;
                  throw new Error('EndForEach');
                }
                console.log(auditItem.payRequestLineId);
              });
            } catch (e) {
              if (e.message != 'EndForEach') throw e;
            }
          });
          return;
        }
      }
      const self = this;
      this.selections = selections;
      this.accountList = [];
      for (const i in this.payMentModeData.valueMap) {
        this.accountList.push({
          name: this.payMentModeData.valueMap[i],
          value: 0
        });
      }
      let payInfoGroupAmount = [];
      for (let m = 0; m < this.selections.length; m++) {
        payInfoGroupAmount = this.selections[m].payInfoGroupAmount.split(';');
        payInfoGroupAmount.forEach(function(item) {
          for (let n = 0; n < vm.accountList.length; n++) {
            if (vm.accountList[n].name == item.split(':')[0]) {
              vm.accountList[n].value += Number(item.split(':')[1]);
            }
          }
        });
      }
      let countAmount = 0;
      for (let k = 0; k < this.accountList.length; k++) {
        countAmount += Number(this.accountList[k].value);
      }
      if (countAmount > 0) {
        this.showPaymentInfo = true;
      } else {
        this.showPaymentInfo = false;
      }
      this.selectApplyAmount = `${accounting.formatNumber(countAmount, 2)}`;
      for (let n = 0; n < this.accountList.length; n++) {
        this.accountList[n].value = `${accounting.formatNumber(
          this.accountList[n].value,
          2
        )}`;
      }
      if (vm.selections.length > 0) {
        if (vm.selections[0].auditStatus == '0') {
          vm.auditDisabled = false;
          vm.cancelAuditDisabled = true;
        } else {
          vm.auditDisabled = true;
          vm.cancelAuditDisabled = false;
        }
      } else {
        vm.auditDisabled = true;
        vm.cancelAuditDisabled = true;
      }
    },
    showPaymentEdit(row) {
      // e.stopPropagation();
      this.payWayInfo.showAmount = vm.showAmount;
      this.payWayInfo.disabledFlag = false;
      this.payWayInfo.companyCode = row.ouCode;
      this.payWayInfo.payRequestLineId = row.payRequestLineId;
      this.payWayInfo.applyAmount = row.applyAmount;
      const refreshFun = this.search;
      this.$nextTick(() => {
        this.$refs.payWayInfo.showVendorBankTable(refreshFun, false, row.categoryCode);
      });
    },
    // 显示付款信息
    showPaymentInfoWin(e, row) {
      this.payWayInfo.showAmount = vm.showAmount;
      this.payWayInfo.disabledFlag = false;
      this.payWayInfo.companyCode = row.ouCode;
      this.payWayInfo.payRequestLineId = row.payRequestLineId;
      this.payWayInfo.applyAmount = row.applyAmount;
      this.$nextTick(() => {
        this.$refs.payWayInfo.showVendorBankTable(null, true);
      });
      // e.stopPropagation();
      // this.payWayInfo.payType = row.payType;
      // this.payWayInfo.payRequestLineId = row.payRequestLineId;
      // this.payWayInfo.applyAmount = row.applyAmount;
      // this.payWayInfo.buttonText = row.buttonText;
      // this.payWayInfo.ouCode = row.payRequestOuCode;
      // this.payWayInfo.claimId = row.payRequestClaimId;
      // this.$nextTick(() => {
      //   this.$refs["payWayInfo"].showPayWayInfoForm();
      // })
      // this.$nextTick(() => {
      //   this.$refs["payWayInfo"].showVendorBankTable();
      // });
    },
    dataSelectComponents(code, params, value) {
      if (params.row.auditStatus == '1') {
        return (
          <DataSelect
            disabled="true"
            transfer="true"
            code={code}
            style="width:120px"
            value={value}
          />
        );
      } else {
        return (
          <DataSelect
            transfer="true"
            code={code}
            style="width:120px"
            value={value}
          />
        );
      }
    },
    auditStatusCodeArray(data) {
      if (data != null) {
        this.auditStatusMap = data.valueMap;
      }
    },
    payStateCodeArray(data) {
      if (data != null) {
        this.payStateMap = data.valueMap;
      }
    },
    payWayCodeArray(data) {
      if (data != null) {
        this.payWayMap = data.valueMap;
        this.payMentModeData = data;
      }
    },
    loadedCapitalPlan(val) {
      this.capitalPlanData = val;
    },
    loadedTransfersType(val) {
      this.transfersTypeData = val;
    },
    currencyCodeArray(data) {
      if (data != null) {
        this.currencyMap = data.valueMap;
      }
    },
    vendorTypeCodeArray(data) {
      if (data != null) {
        this.vendorTypeMap = data.valueMap;
      }
    },
    changePageFun() {},
    async exportData() {
      this.exportLoad = true;
      // 返回结果
      const params = {
        page: { currentPage: 1, pageSize: 10, recordCount: 1 },
        params: this.form,
        sortDTO: { fieldName: '', orderBy: '' }
      };
      this.server.exportResult(params).then(res => {
        if (res.statusCode === '-1') {
          this.$Message.error('导出失败');
          this.exportLoad = false;
        } else {
          const date = new Date();
          const ExcelName = '申请审核' + miment(date).format('YYYYMMDDhhmmss');
          this.exportFile(ExcelName, res);
        }
      });
    },
    exportFile(fileNameStr, res) {
      if (res.statusCode === '-1') {
        this.$Message.error(res.msg);
        this.exportLoad = false;
      } else {
        const blob = new Blob([res.data]);
        const fileName = `${fileNameStr}.xls`;
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, fileName);
          this.exportLoad = false;
        } else {
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
          this.exportLoad = false;
        }
      }
    },
    openPayContractNo(data) {
      $store
        .dispatch('QueryProcessInfoByClaimNo', {
          claimNo: data.relatedContract
        })
        .then(response => {
          const dataResult = response.list[0];
          // 因为是查询出来的关联工单是已审批的，所以对应的状态一定是done
          dataResult.actionType = 'done';
          dataResult.source = 'other';
          util.openTaskFromBillOfAccount(dataResult);
        })
        .catch(error => {});
    },
    checkPaymentApplyDetail() {
      new this.$pageModal(
        EditPaymentInfo,
        {
          props: {
            title: '付款准备信息修改',
            companyList: this.companyList
          }
        },
        data => {

        }
      );
    },
    openFormPage(rowData) {
      util.openByClaimIdAndClaimNo(rowData);
    }
  },
  watch: {
    'form.amountRange': {
      handler() {
        const range = this.form.amountRange;
        this.form.leftAmount = range.start;
        this.form.rightAmount = range.end;
      },
      deep: true
    },
    'form.createTime': {
      handler() {
        const createTime = this.form.createTime;
        this.form.startCreateTime = createTime[0];
        this.form.endCreateTime = createTime[1];
      },
      deep: true
    },
    'form.auditTime': {
      handler() {
        const auditTime = this.form.auditTime;
        this.form.startAuditTime = auditTime[0];
        this.form.endAuditTime = auditTime[1];
      },
      deep: true
    }
  },
  directives: {}
};
</script>
<style lang="less" scoped>
.audit-form /deep/ .ivu-input, .audit-form /deep/ .ivu-input-wrapper {
  width: 100%;
}
</style>
