<template>
  <div>
    <EMSTableNew
      ref="paymentTable"
      :server="server"
      action="getPaymentTableDatas"
      :params="formSearchParams"
      :columnsFn="preparePaymentColumns"
      :highlight-row="true"
      :onSelectionChange="onSelectionChange"
    >
      <Form
        ref="formSearch"
        slot="search-bar"
        :model="formSearch"
        :rules="rule"
        :label-width="100"
      >
        <Row>
          <Col span="8">
          <Form-item
            prop="ouCode"
            label="归属公司"
          >
            <Select
              v-model="formSearch.ouCode"
              filterable
              transfer
              clearable
            >
              <Option
                v-for="item in ouCodeList"
                :key="item.companyCode"
                :value="item.companyCode"
              >
                {{ item.ouName }}
              </Option>
            </Select>
          </Form-item>
          </Col>

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

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

          <Col span="8">
          <Form-item
            prop="dueToDate"
            label="付款到期日起止"
          >
            <Date-picker
              v-model="formSearch.dueToDate"
              :editable="false"
              type="daterange"
              format="yyyy-MM-dd"
              transfer
              clearable
            >
            </Date-picker>
          </Form-item>
          </Col>

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

          <Col span="8">
          <Form-item
            prop="claimNo"
            label="付款申请单"
          >
            <Input
              v-model="formSearch.claimNo"
              type="text"
              clearable
            />
          </Form-item>
          </Col>

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

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

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

          <Col span="8">
          <Form-item
            prop="createdTime"
            label="创建时间起止"
          >
            <Date-picker
              v-model="formSearch.createdTime"
              :editable="false"
              type="daterange"
              format="yyyy-MM-dd"
              clearable
              transfer
            >
            </Date-picker>
          </Form-item>
          </Col>

          <Col span="8">
          <Form-item
            prop="paymentMethod"
            label="付款方式"
          >
            <DataSelect
              v-model="formSearch.paymentMethod"
              :value="formSearch.paymentMethod"
              code="PAYMENT_MODE"
              clearable
              @loadFinish="loadedPayMentMode"
            >
            </DataSelect>
          </Form-item>
          </Col>

          <Col span="8">
          <Form-item
            prop="auditDate"
            label="审批结束时间"
          >
            <Date-picker
              v-model="formSearch.auditDate"
              :editable="false"
              type="daterange"
              format="yyyy-MM-dd"
              clearable
              transfer
            ></Date-picker>
          </Form-item>
          </Col>

          <Col span="8">
          <Form-item
            prop="vendorType"
            label="供应商类型"
          >
            <DataSelect
              v-model="formSearch.vendorType"
              :value="formSearch.vendorType"
              code="vendorType"
              clearable
              @loadFinish="loadedVendorType"
            ></DataSelect>
          </Form-item>
          </Col>

          <Col span="8">
          <Form-item
            prop="applyAmount"
            label="申请金额"
          >
            <NumberRangeFix
              :startAmount="formSearch.minApplyAmount"
              :endAmount="formSearch.maxApplyAmount"
              placeholder=""
              clearable
              @inputStart="onInputStart"
              @inputEnd="onInputEnd"
            />
          </Form-item>
          </Col>

          <!-- <Form-item prop="draftAmount" label="汇票金额">
          <NumberRangeFix v-model="formSearch.draftAmount" :tofixed="2" placeholder="金额"  style="width:200px" />
        </Form-item> -->
          <Col span="8">
          <Form-item
            prop="categoryCode"
            label="申请类型"
          >
            <Select
              v-model="formSearch.categoryCode"
              class="applyType"
              filterable
              clearable
              transfer
            >
              <Option
                v-for="item in applyTypeList"
                :key="item.categoryCode"
                :value="item.categoryCode"
              >
                {{ item.categoryName }}
              </Option>
            </Select>
          </Form-item>
          </Col>

          <Col span="8">
          <Form-item
            prop="status"
            label="申请状态"
          >
            <DataSelect
              v-model="formSearch.status"
              :value="formSearch.status"
              code="PAY_CREATE_STATUS"
              clearable
            ></DataSelect>
          </Form-item>
          </Col>

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

          <Col span="8">
          <Form-item
            prop="currency"
            label="币种"
          >
            <DataSelect
              v-model="formSearch.currency"
              :value="formSearch.currency"
              code="currency"
              clearable
              @loadFinish="loadedCurrency"
            ></DataSelect>
          </Form-item>
          </Col>

          <Col span="8">
          <Form-item
            prop="priority"
            label="优先级"
          >
            <DataSelect
              v-model="formSearch.priority"
              :value="formSearch.priority"
              code="PRIORITY"
              clearable
              @loadFinish="loadedPriority"
            ></DataSelect>
          </Form-item>
          </Col>

          <Col span="8">
          <Form-item
            v-show="false"
            prop="payWay"
            label="付款类型"
          >
            <DataSelect
              v-model="formSearch.payWay"
              :value="formSearch.payWay"
              code="payWay"
              clearable
              @loadFinish="loadedPayWay"
            >
            </DataSelect>
          </Form-item>
          </Col>

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

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

          <Col
            v-show="showMore"
            span="8"
          >
          <div class="search_btns ivu-form-item">
            <a @click="changeShowMore">{{ $t('隐藏条件') }}</a>
            <Button
              class="ems-btn-medium ems-btn-type3"
              style="padding: 0 18px;"
              @click.native="reset"
            >
              {{ $t("重置") }}
            </Button>
            <Button
              type="warning"
              class="ems-btn-medium ems-btn-type1"
              style="padding: 0 18px;"
              @click.native="search"
            >
              {{ $t("查询") }}
            </Button>
          </div>
          </Col>
          <div
            v-if="showPaymentInfo"
            class="v-summary-tips"
          >
            <Icon type="android-bulb"></Icon>
            <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"
        >
          付款申请单查询
        </Button>
        <Button
          type="info"
          icon="loop"
          @click.native="reset"
        >
          {{ $t('重置') }}
        </Button>
      </div> -->

      <div slot="table-bar">
        <Button
          type="warning"
          :loading="createPaymentBtnLoading"
          icon="ios-plus-empty"
          :disabled="createPaymentDisabled"
          @click="createPayment"
        >
          创建付款准备批
        </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"
    />
    <DataSelect
      v-show="false"
      v-model="formSearch.payStatusData"
      code="payState"
      @loadFinish="loadedpayStatus"
    />
  </div>
</template>
<script>
import {
  // SelectProject,
  // PayWayInfo,
  PayInfo,
  NumberRangeFix,
  PaymentInfoRead
} from '@paymentPlatformComps/index.js';
import Server from './server.js';
import accounting from 'accounting';
import util from '@paymentPlatformSrc/tools/util.js';
import { mapMutations } from 'vuex';
const server = new Server();
let vm;
export default {
  components: {
    // SelectProject,
    // PayWayInfo,
    PayInfo,
    NumberRangeFix
  },
  props: {
    ouCodeList: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      showMore: false,
      // companyList:[],
      accountList: [],
      capitalPlan: '',
      transfersType: '',
      selectApplyAmount: 0,
      codeValues: {},
      applyTypeList: [],
      capitalPlanData: [],
      transfersTypeData: [],
      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,
      createPaymentBtnLoading: false,
      server,
      formSearch: {
        applyDeptName: '',
        priority: '',
        categoryCode: '',
        categoryName: '',
        ouCode: this.ouCodeList[0] ? this.ouCodeList[0].companyCode : '', // 归属公司
        vendorName: '', // 供应商
        startDueToDate: '', // 付款到期日起
        endDueToDate: '', // 付款到期日止
        claimNo: '', // 付款申请单
        invoiceNo: '', // 发票编号
        invoiceClaimNo: '',
        applyEmpName: '', // 付款申请人
        createdTime: '',
        startCreateTime: '', // 创建时间起
        endCreateTime: '', // 创建时间止
        paymentMethod: '', // 付款类型
        auditDate: '', // 审批结束时间起止 辅助
        startAuditTime: '', // 审批结束时间起止 Start
        endAuditTime: '', // 审批结束时间起止 End
        vendorType: '', // 供应商类型
        applyAmount: '', // 申请金额 辅助
        minApplyAmount: '', // 申请金额 Start
        maxApplyAmount: '', // 申请金额 End
        draftAmount: '', // 汇票金额 辅助
        startDraftAmount: '', // 汇票金额 Start
        endDraftAmount: '', // 汇票金额 End
        status: '2', // 申请状态 默认是待创建
        projectCode: '', // 项目编码
        currency: '' // 币种
      },
      paymentInfo: {
        applyAmount: 0,
        transferAmount: 0,
        draftAmount: 0,
        otherAmount: 0
      },
      showPaymentInfo: false, // 右上角显示 申请金额 等统计
      vendorTypeData: {}, // 供应商类型- 值集 数据
      currencyData: {}, // 币种- 值集 数据
      priorityData: {}, // 优先级- 值集 数据
      payMentModeData: {}, // 请款类型- 值集 数据
      payWayData: {},
      payStatusData: {}, // 付款状态 - 值集 数据
      payWayInfo: {
        payType: '',
        payRequestLineIds: '',
        buttonText: '',
        ouCode: '',
        payRequestLineId: '',
        companyCode: ''
      },
      rule: {
        ouCode: [
          {
            required: true,
            message: '请选择归属公司!',
            trigger: 'change'
          }
        ]
      },
      selection: [], // 多选结果
      createPaymentDisabled: true // 创建付款准备按钮是否可点击
    };
  },
  computed: {
    formSearchParams() {
      const formSearch = JSON.parse(JSON.stringify(this.formSearch));
      delete formSearch.dueToDate;
      delete formSearch.createdTime;
      // delete formSearch.auditDate;
      // console.log('formSearchParams', formSearch);
      return formSearch;
    },
    payRequestIds() {
      const ids = [];
      this.selection.map(item => {
        ids.push(item.payRequestLineId);
      });

      return ids;
    }
  },
  created() {
    vm = this;
    this.$emit('SetTitle', '新增付款准备批');
    this.$emit('SetPageSize', 1000);
  },
  beforeMount() {},
  mounted() {
    vm = this;
    this.$nextTick(() => {
      this.queryAndSetValueSet('PAYMENT_MODE');
      this.queryAndSetValueSet('remittanceSpeed');
      this.queryAndSetValueSet('capitalPlan');

      // const itemDoms = document.querySelectorAll('.run-mod-box .ivu-form-item-label');
      // for (let i = 0, l = itemDoms.length; i < l; ++i) {
      //   itemDoms[i].style.float = 'none';
      // }
    });
    // 查询付款方式值集
    this.server.queryApplySelect().then(response => {
      if (response.statusCode == '-1') {
        this.$Message.error(response.msg);
      } else {
        this.applyTypeList = response;
      }
    });
  },
  methods: {
    ...mapMutations('createPaymentPreparation', ['setValueSet']),
    changeShowMore() {
      this.showMore = !this.showMore;
      this.$refs.paymentTable.showMore();
    },
    onInputStart(startVal) {
      this.formSearch.minApplyAmount = startVal;
    },
    onInputEnd(endVal) {
      this.formSearch.maxApplyAmount = endVal;
    },
    queryAndSetValueSet(code) {
      if (!code) {
        return;
      }
      this.server.QueryValueSetByCode({ code: code }).then(response => {
        this.codeValues[code] = response;
        console.log('$store.state', $store.state);
        // $store.state.createPaymentPreparation.valueSet = self.codeValues;
        if (this.codeValues.length > 2) {
          this.setValueSet(this.codeValues);
        }
      });
    },
    // 创建付款准备
    createPayment() {
      // const sel = this.selection[0];
      const data = this.payRequestIds;
      this.openCreatePayment(data, this.selection[0]);
    },
    // 显示付款信息
    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);
      });
    },
    // 表头字段定义
    preparePaymentColumns() {
      return [
        {
          title: '多选',
          type: 'selection',
          align: 'center',
          fixed: 'left',
          width: 60
        },
        {
          title: '付款申请单',
          align: 'left',
          key: 'claimNo',
          sortable: 'custom',
          width: 150,
          resizable: true,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    text: params.row.claimNo,
                    handle: () => {
                      this.openFormPage(params.row);
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: '行号',
          align: 'left',
          key: 'lineNumber',
          sortable: 'custom',
          width: 60,
          resizable: true,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.lineNumber
                  }
                },
                params.row.lineNumber
              )
            ]);
          }
        },
        {
          title: '申请金额',
          align: 'left',
          key: 'applyAmount',
          sortable: 'custom',
          resizable: true,
          width: 100,
          render: (h, params) => {
            return h(
              'span',
              accounting.formatNumber(params.row.applyAmount, 2)
            );
          }
        },
        {
          title: '币种',
          width: 90,
          resizable: true,
          align: 'left',
          key: 'currency',
          sortable: 'custom',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: params.row.currency && vm.currencyData.valueMap[params.row.currency]
                }
              },
              // vm.currencyData.valueMap[params.row.currency]
              params.row.currency && vm.currencyData.valueMap[params.row.currency]
            );
          }
        },
        {
          title: '申请类型',
          align: 'left',
          key: 'categoryName',
          sortable: 'custom',
          minWidth: 100,
          resizable: true,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.categoryName
                  }
                },
                params.row.categoryName
              )
            ]);
          }
        },
        {
          title: '归属公司',
          align: 'left',
          key: 'ouName',
          resizable: true,
          sortable: 'custom',
          width: 140,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.ouName
                  }
                },
                params.row.ouName
              )
            ]);
          }
        },
        {
          title: '地点',
          align: 'left',
          // key: "vendorSite",
          key: 'receiVendorSite',
          sortable: 'custom',
          resizable: true,
          width: 140,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.vendorSite
                  }
                },
                params.row.vendorSite
              )
            ]);
          }
        },
        {
          title: '付款信息',
          width: 80,
          sortable: 'custom',
          align: 'left',
          resizable: true,
          // key: "payWayAmountDescr",
          render: (h, params) => {
            // if (!params.row._disabled) {
            return (
              <PaymentInfoRead
                trigger="hover"
                placement="right-start"
                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>
            );
          }
          // }
        },

        {
          title: '供应商',
          align: 'left',
          resizable: true,
          // key: "vendorName",
          key: 'receiVendorName',
          sortable: 'custom',
          width: 150,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.vendorName
                  }
                },
                params.row.vendorName
              )
            ]);
          }
        },

        {
          title: '供应商类型',
          align: 'left',
          key: 'vendorType',
          resizable: true,
          sortable: 'custom',
          width: 170,
          render: (h, params) => {
            let text = '';
            if (params.row.vendorType == 'EMPLOYEE') {
              text = '对私';
            } else {
              text = '对公';
            }
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: text
                }
              },
              text
            );
          }
        },
        {
          title: '收款方户名',
          width: 140,
          resizable: true,
          align: 'left',
          sortable: 'custom',
          key: 'receiVendorName',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.receiVendorName
                  }
                },
                params.row.receiVendorName
              )
            ]);
          }
        },
        {
          title: '收款账户',
          width: 140,
          resizable: true,
          align: 'left',
          sortable: 'custom',
          // key: "vendorAccountNo",
          key: 'receiVendorAccountNo',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.vendorAccountNo
                  }
                },
                params.row.vendorAccountNo
              )
            ]);
          }
        },
        {
          title: '优先级',
          width: 90,
          resizable: true,
          align: 'left',
          sortable: 'custom',
          key: 'priority',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: params.row.priority && vm.priorityData.valueMap[params.row.priority]
                }
              },
              params.row.priority && vm.priorityData.valueMap[params.row.priority]
            );
          }
        },
        {
          title: '申请人',
          width: 90,
          resizable: true,
          sortable: 'custom',
          align: 'left',
          key: 'applyEmpName',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.applyEmpName
                  }
                },
                params.row.applyEmpName
              )
            ]);
          }
        },
        {
          title: '申请部门',
          width: 90,
          resizable: true,
          sortable: 'custom',
          align: 'left',
          key: 'applyDeptName',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.applyDeptName
                  }
                },
                params.row.applyDeptName
              )
            ]);
          }
        },
        {
          title: '创建日期',
          width: 90,
          resizable: true,
          sortable: 'custom',
          align: 'left',
          key: 'createdTime',
          render: (h, params) => {
            // let createTimeArr = (params.row.createdTime || "").split(" ");
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: params.row.createdTime
                }
              },
              params.row.createdTime
            );
          }
        },
        {
          title: '审批结束日期',
          width: 140,
          resizable: true,
          align: 'left',
          sortable: 'custom',
          key: 'workflowPassTime'
        },
        {
          title: '消息',
          align: 'left',
          key: 'message',
          sortable: 'custom',
          width: 90,
          resizable: true,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.message,
                    canCopyFlag: '1'
                  }

                },
                params.row.message
              )
            ]);
          }
        }
      ];
    },
    // UTC时间转换成正常时间格式
    formatTime(date) {
      if (date) {
        const newDate = new Date(date).toJSON();
        return new Date(+new Date(newDate) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
      }
    },
    // 搜索
    search(page = 1) {
      const formSearchParams = this.formSearchParams; const newData = [];
      const startDate = this.formSearchParams.auditDate[0];
      const endDate = this.formSearchParams.auditDate[1];
      this.formSearchParams.startAuditTime = startDate ? this.formatTime(startDate).split(' ')[0] : '';
      this.formSearchParams.startCreateTime = this.formSearchParams.startCreateTime ? this.formatTime(this.formSearchParams.startCreateTime).split(' ')[0] : '';
      newData.push(this.formSearchParams.startAuditTime);
      this.formSearchParams.endAuditTime = endDate ? this.formatTime(endDate).split(' ')[0] : '';
      this.formSearchParams.endCreateTime = this.formSearchParams.endCreateTime ? this.formatTime(this.formSearchParams.endCreateTime).split(' ')[0] : '';
      newData.push(this.formSearchParams.endAuditTime);
      this.formSearchParams.auditDate = newData;
      formSearchParams.applyAmount = undefined;
      formSearchParams.draftAmount = undefined;
      formSearchParams.categoryCode = this.formSearch.categoryCode;
      this.$refs.paymentTable.load(formSearchParams, page);
      this.countPaymentAmount([]); // 重置 申请金额
    },
    // 重置
    reset() {
      const formSearch = this.formSearch;
      Object.keys(formSearch).map(key => {
        formSearch[key] = '';
      });
      this.$refs.formSearch.resetFields();
      this.search();
      this.countPaymentAmount([]); // 重置 申请金额
    },
    // 选择项目编码
    handleProjectCodeSelect(data) {
      console.log('ProjectCodeSelect', data);
      this.formSearch.projectCode = data.projectCode;
    },

    // 多选
    onSelectionChange(data) {
      this.selection = data;
      this.countPaymentAmount(data);
    },
    dataSelectComponents(code, params, value) {
      return (
        <DataSelect
          transfer="true"
          readonly
          code={code}
          style="width:120px"
          value={value}
        />
      );
    },
    // 计算 申请金额 = 转账金额 + 票据金额 + 其他金额
    countPaymentAmount(data) {
      const p = this.paymentInfo;

      Object.keys(p).map(item => {
        p[item] = '0.00';
      });

      if (data.length) {
        Object.keys(p).map(item => {
          p[item] = Number(p[item]);
        });
        data.map(item => {
          p.transferAmount += item.transAmount;
          p.draftAmount += item.draftAmount;
          p.otherAmount += item.otherAmount;
          p.applyAmount += item.applyAmount;
        });

        Object.keys(p).map(item => {
          p[item] = p[item].toFixed(2);
        });

        console.log('paymentInfo count', p);

        this.showPaymentInfo = true;
      }
    },

    // 供应商类型 valueList数据 反显值valueMap
    loadedVendorType(val) {
      this.vendorTypeData = val;
      console.log(this.vendorTypeData);
    },

    // 币值 valueList数据 反显值valueMap
    loadedCurrency(val) {
      this.currencyData = val;
    },
    // 优先级 valueList数据 反显值valueMap
    loadedPriority(val) {
      this.priorityData = val;
    },
    loadedCapitalPlan(val) {
      this.capitalPlanData = val;
    },
    loadedTransfersType(val) {
      this.transfersTypeData = val;
    },

    // 请款类型 valueList数据 反显值valueMap
    loadedPayMentMode(val) {
      this.payMentModeData = val;
    },
    // 付款方式 valueList数据 反显值valueMap
    loadedPayWay(val) {
      this.payWayData = val;
    },
    // 付款状态 valueList数据 反显值valueMap
    loadedpayStatus(val) {
      this.payStatusData = val;
    },

    // 返回值集的值
    showValueSetsVal(VS, key) {
      if (VS.valueMap) {
        return VS.valueMap[key];
      } else {
        return '';
      }
    },
    // 搜索框内 时间起止 设值
    setFormSearchRangeDate(val, start, end) {
      console.log('Date change', val);
      this.formSearch[start] = val[0] + ' 00:00:00';
      this.formSearch[end] = val[1] + ' 23:59:59';
    },

    // 付款申请单 打开新页面
    openPayRequest(data) {
      const newWindow = window.open();
      data.openFromPayPlatform = true;
      const params = {
        claimId: data.claimId,
        claimNo: data.claimNo,
        openFromPayPlatform: data.openFromPayPlatform,
        newWindow: newWindow
      };
      util.openByClaimIdAndClaimNo(params);
    },
    /**
     * 创建付款准备 校验并提示
     * 新增校验创建付款单方法
     *  @author changanmin1@crc.com.hk
     * 业务需求描述：
     *
     *  创建付款准备 需满足以下条件
        多项
          1.币种相同
          2.对公或对私 必须是同一种
          3.申请金额 需 大于等于0
            //  4.同一供应商  ： 经与产品沟通 去除
          4.同一归属公司
        单项
            判断申请金额 需大于等于0
     */
    createPaymentValidate() {
      const selections = this.selection;
      if (selections && selections.length > 1) {
        // 多项
        const temp_selection = selections[0];
        const bool_currency = selections.some(item => {
          return item.currency !== temp_selection.currency;
        }); // 币种
        if (bool_currency) {
          this.$Message.warning('请勾选相同【币种】的行！');
          return true;
        }
        const bool_vendorType = selections.some(item => {
          return (item.vendorType == 'EMPLOYEE' ? 'EMPLOYEE' : 'PROVIDER') !== (temp_selection.vendorType == 'EMPLOYEE' ? 'EMPLOYEE' : 'PROVIDER');
        }); // 对公对私
        if (bool_vendorType) {
          this.$Message.warning('请勾选相同【对公/对私】的行！');
          return true;
        }
        const bool_payRequestOuCode = selections.some(item => {
          return item.ouCode !== temp_selection.ouCode;
        }); // 同一归属公司
        if (bool_payRequestOuCode) {
          this.$Message.warning('请勾选相同【归属公司】的行！');
        }
        /**
         * @author changanmin1@crc.com.hk
         * 多项选择时
         * 原业务判断： 判断累积申请金额大于等于0就可以通过
         * 2018/8/10更新业务判断：根据同一供应商vendorName 分组，每一组的申请累加金额大于等于0 方可发起申请
         *
         */
        // start
        const temp_vendorCode = new Map();
        selections.forEach(element => {
          const vendor = temp_vendorCode.get(element.vendorCode) || {
            applyAmount: 0
          };
          temp_vendorCode.set(element.vendorCode, {
            applyAmount: vendor.applyAmount + +element.applyAmount,
            vendorName: element.vendorName
          });
        });
        for (const [key, value] of temp_vendorCode) {
          if (value.applyAmount < 0) {
            this.$Message.warning(
              `${value.vendorName}的总申请金额为负数，该付款申请不可进行创建`
            );
            return true;
          }
        }
        // end
        // start 2018/8/10 需求变更注释下面代码
        // let bool_applyAmount = ((+this.paymentInfo.applyAmount) < 0); //申请金额
        // if(bool_applyAmount){
        //    this.$Message.warning("含负数的付款申请不可进行创建！");
        //    return true;
        // }
        // end  2018/8/10 需求变更注释上面代码
      } else if (selections && selections.length === 1) {
        // 单项
        const bool_applyAmount = +this.paymentInfo.applyAmount < 0;
        if (bool_applyAmount) {
          this.$Message.warning(
            `${
              selections[0].vendorName
            }的总申请金额为负数，该付款申请不可进行创建`
          );
          return true;
        }
      }
      return false;
    },
    // 创建付款准备 打开新页面
    openCreatePayment(param, data) {
      if (this.createPaymentValidate()) {
        return false;
      }
      this.createPaymentBtnLoading = true;
      server
        .queryCreatePayment(param)
        .then(response => {
          if (response.data.code == '1') {
            // const origin = location.origin
            //   ? location.origin
            //   : `${location.protocol}//${location.host}`;
            // const url = `${origin}/createPaymentPreparation.html?batchNo=${response.data.batchNo}`;
            // window.open(url);
            this.createPaymentBtnLoading = false;
            this.search();
            const batchNo = response.data.obj.batchNo;
            const id = response.data.obj.payBatchId;

            let origin = '';
            if (location.origin) {
              if (location.origin != location.href.split('/#')[0]) {
                origin = location.href.split('/#')[0];
              } else {
                origin = location.origin;
              }
            }
            // else {
            //   `${location.protocol}//${location.host}`;
            // }
            // const origin = location.origin
            //   ? location.origin
            //   : `${location.protocol}//${location.host}`;
            const url = `${origin}/#/create-payment-preparation?pageName=create-payment-preparation&id=${id}&batchNo=${batchNo}&singlePage=YES&crctoken=${
              sessionStorage.crctoken
            }`;
            window.open(url);
          } else {
            this.$Message.error(response.data.msg || '创建失败');
          }
        })
        .catch(error => {});
    },
    openFormPage(rowData) {
      util.openByClaimIdAndClaimNo(rowData);
    }
  },
  watch: {
    selection(selections, oldVal) {
      /*
        @updateDate 2018/8/9 21:00
        @update Author changanmin1@crc.com.hk
        @desc 本次修改内容如下：
         选中的项需大于0 按钮可点击
         校验放在 点击按钮后进行校验 详见方法 createPaymentValidate
      */
      if (selections && selections.length > 0) {
        this.createPaymentBtnLoading = false;
        this.createPaymentDisabled = false;
      } else {
        this.createPaymentDisabled = true;
      }
      this.selections = selections;
      this.accountList = [];
      for (const i in this.payMentModeData.valueMap) {
        this.accountList.push({
          name: this.payMentModeData.valueMap[i],
          value: 0
        });
      }
      let payWayAmountDescrArr = [];
      for (let m = 0; m < this.selections.length; m++) {
        payWayAmountDescrArr = this.selections[m].payInfoGroupAmount.split(';');
        payWayAmountDescrArr.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);
      }
      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
        )}`;
      }
    },

    // 'formSearch.applyAmount': {
    //   handler() {
    //     const range = this.formSearch.applyAmount;
    //     this.formSearch.minApplyAmount = range.start;
    //     this.formSearch.maxApplyAmount = range.end;
    //   },
    //   deep: true
    // },

    'formSearch.draftAmount': {
      handler() {
        const range = this.formSearch.draftAmount;
        this.formSearch.startDraftAmount = range.start;
        this.formSearch.endDraftAmount = range.end;
      },
      deep: true
    },
    'formSearch.createdTime': {
      handler() {
        const createTime = this.formSearch.createdTime;
        this.formSearch.startCreateTime = createTime[0];
        this.formSearch.endCreateTime = createTime[1];
      },
      deep: true
    },
    'formSearch.dueToDate': {
      handler() {
        const dueToDate = this.formSearch.dueToDate;
        this.formSearch.startDueToDate = dueToDate[0];
        this.formSearch.endDueToDate = dueToDate[1];
      },
      deep: true
    },
    'formSearch.auditDate': {
      handler() {
        const auditDate = this.formSearch.auditDate;
        this.formSearch.startApprovalDate = auditDate[0];
        this.formSearch.endApprovalDate = auditDate[1];
      },
      deep: true
    }
  }
};
</script>

<style scoped lang="less">
/deep/ .ivu-form-item-required {
  .ivu-form-item-label {
    height:32px;
  }
}
</style>
