<template>
  <div class="run-mod-box">
    <EMSTable
      ref="paymentTable"
      :server="server"
      action="getPaymentTableDatas"
      :params="formSearchParams"
      :columnsFn="preparePaymentColumns"
      :highlight-row="true"
      :onSelectionChange="onSelectionChange"
    >
      <Form
        ref="formSearch"
        slot="search-bar"
        :model="formSearch"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <Form-item
          prop="payRequestOuCode"
          label="归属公司"
        >
          <Select
            v-model="formSearch.payRequestOuCode"
            filterable
            transfer
            clearable
          >
            <Option
              v-for="item in companyList"
              :key="item.companyCode"
              :value="item.companyCode"
            >
              {{ item.ouName }}
            </Option>
          </Select>
        </Form-item>
        <Form-item
          prop="vendorName"
          label="供应商"
        >
          <Input
            v-model="formSearch.vendorName"
            type="text"
            maxlength="30"
            clearable
          />
        </Form-item>
        <Form-item
          prop="dueToDate"
          label="付款到期日起止"
        >
          <DatePicker
            v-model="formSearch.dueToDate"
            :editable="false"
            type="daterange"
            format="yyyy-MM-dd"
            :clearable="false"
            transfer
            @on-change="(val)=>{setFormSearchRangeDate(val, 'startDueToDate', 'endDueToDate')}"
          >
          </DatePicker>
        </Form-item>
        <Form-item
          prop="applyDept"
          label="申请部门"
        >
          <Input
            v-model="formSearch.applyDept"
            type="text"
            maxlength="30"
            clearable
          />
        </Form-item>
        <Form-item
          prop="invoiceClaimNo"
          label="关联报账单号"
        >
          <Input
            v-model="formSearch.invoiceClaimNo"
            type="text"
            maxlength="30"
            clearable
          ></Input>
        </Form-item>
        <Form-item
          prop="payRequestClaimNo"
          label="付款申请单"
        >
          <Input
            v-model="formSearch.payRequestClaimNo"
            type="text"
            clearable
          />
        </Form-item>
        <Form-item
          prop="applyEmployeeName"
          label="付款申请人"
        >
          <Input
            v-model="formSearch.applyEmployeeName"
            type="text"
            maxlength="30"
            clearable
          />
        </Form-item>
        <Form-item
          prop="createTime"
          label="创建时间起止"
        >
          <DatePicker
            v-model="formSearch.createTime"
            :editable="false"
            type="daterange"
            format="yyyy-MM-dd"
            :clearable="false"
            clearable
            @on-change="(val)=>{setFormSearchRangeDate(val, 'startCreateTime', 'endCreateTime')}"
          >
          </DatePicker>
        </Form-item>
        <Form-item
          prop="payMentMode"
          label="付款方式"
        >
          <DataSelect
            v-model="formSearch.paymentMode"
            :value="formSearch.paymentMode"
            code="PAYMENT_MODE"
            clearable
            @loadFinish="loadedPayMentMode"
          >
          </DataSelect>
        </Form-item>

        <Form-item
          prop="auditDate"
          label="审批结束时间起止"
        >
          <DatePicker
            v-model="formSearch.auditDate"
            :editable="false"
            type="daterange"
            format="yyyy-MM-dd"
            :clearable="false"
            clearable
            @on-change="(val)=>{setFormSearchRangeDate(val, 'startApprovalDate', 'endApprovalDate')}"
          ></DatePicker>
        </Form-item>

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

        <Form-item
          prop="applyAmount"
          label="申请金额"
        >
          <NumberRangeFix
            :startAmount="formSearch.startApplyAmount"
            :endAmount="formSearch.endApplyAmount"
            :tofixed="2"
            placeholder=""
            clearable
            @inputStart="onInputStart"
            @inputEnd="onInputEnd"
          />
        </Form-item>

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

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

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

        <Form-item
          prop="currency"
          label="币种"
        >
          <DataSelect
            v-model="formSearch.currency"
            :value="formSearch.currency"
            code="currency"
            clearable
            @loadFinish="loadedCurrency"
          ></DataSelect>
        </Form-item>
        <Form-item
          prop="currency"
          label="优先级"
        >
          <DataSelect
            v-model="formSearch.priority"
            :value="formSearch.priority"
            code="priority"
            clearable
            @loadFinish="loadedPriority"
          ></DataSelect>
        </Form-item>

        <Form-item
          v-show="false"
          prop="payMentMode"
          label="请款类型"
        >
          <DataSelect
            v-model="formSearch.payWay"
            :value="formSearch.payWay"
            code="payWay"
            clearable
            @loadFinish="loadedPayWay"
          >
          </DataSelect>
        </Form-item>
        <Form-item
          v-show="false"
          prop="capitalPlan"
          label="资金计划"
        >
          <DataSelect
            v-model="capitalPlan"
            :value="capitalPlan"
            code="capitalPlan"
            clearable
            @loadFinish="loadedCapitalPlan"
          >
          </DataSelect>
        </Form-item>
        <Form-item
          v-show="false"
          prop="transfersType"
          label="付款通道"
        >
          <DataSelect
            v-model="transfersType"
            :value="transfersType"
            code="transfersType"
            clearable
            @loadFinish="loadedTransfersType"
          >
          </DataSelect>
        </Form-item>
        <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>
      </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"
          :loading="createPaymentBtnLoading"
          icon="ios-plus-empty"
          :disabled="createPaymentDisabled"
          @click="createPayment"
        >
          创建付款准备
        </Button>
      </div>
    </EMSTable>
    <PayWayInfo
      v-show="false"
      ref="payWayInfo"
      :payType="payWayInfo.payType"
      :payRequestLineIds="payWayInfo.payRequestLineIds"
      :buttonText="payWayInfo.buttonText"
      :ouCode="payWayInfo.ouCode"
      :claimId="payWayInfo.claimId"
    />
    <DataSelect
      v-show="false"
      v-model="formSearch.payStatusData"
      code="payState"
      @loadFinish="loadedpayStatus"
    />
  </div>
</template>
<script>
import {
  PayWayInfo,
  NumberRangeFix,
  PaymentInfoRead
} from '@paymentPlatformComps/index.js';
import Server from './server.js';
import util from '@paymentPlatformSrc/tools/util.js';
import accounting from 'accounting';
import { mapMutations } from 'vuex';
const server = new Server();
let vm;
export default {
  components: {
    PayWayInfo,
    NumberRangeFix
  },
  data() {
    return {
      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: {
        invoiceClaimNo: '',
        applyDept: '',
        priority: '',
        expCategoryCode: '',
        payRequestOuCode: '', // 归属公司
        vendorName: '', // 供应商
        startDueToDate: '', // 付款到期日起
        endDueToDate: '', // 付款到期日止
        payRequestClaimNo: '', // 付款申请单
        invoiceNo: '', // 发票编号
        applyEmployeeName: '', // 付款申请人
        startCreateTime: '', // 创建时间起
        endCreateTime: '', // 创建时间止
        paymentMode: '', // 付款类型
        auditDate: '', // 审批结束时间起止 辅助
        startApprovalDate: '', // 审批结束时间起止 Start
        endApprovalDate: '', // 审批结束时间起止 End
        vendorType: '', // 供应商类型
        applyAmount: '', // 申请金额 辅助
        startApplyAmount: '', // 申请金额 Start
        endApplyAmount: '', // 申请金额 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: ''
      },

      selection: [], // 多选结果
      createPaymentDisabled: true // 创建付款准备按钮是否可点击
    };
  },
  computed: {
    formSearchParams() {
      const formSearch = JSON.parse(JSON.stringify(this.formSearch));
      delete formSearch.dueToDate;
      delete formSearch.createTime;
      // delete formSearch.auditDate;
      console.log('formSearchParams', formSearch);
      return formSearch;
    },
    payRequestIds() {
      const ids = [];

      this.selection.map(item => {
        ids.push(item.payRequestLineId);
      });

      return ids;
    }
  },
  created: function() {
    vm = this;
  },
  beforeMount: function() {},
  mounted() {
    vm = this;
    const self = this;
    self.$nextTick(() => {
      self.queryAndSetValueSet('PAYMENT_MODE');
      self.queryAndSetValueSet('remittanceSpeed');
      self.queryAndSetValueSet('capitalPlan');
    });
    // 查询付款方式值集
    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;
      }
    });
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    ...mapMutations('createPaymentPreparation', ['setValueSet']),
    onInputStart(startVal) {
      this.formSearch.startApplyAmount = startVal;
    },
    onInputEnd(endVal) {
      this.formSearch.endApplyAmount = endVal;
    },
    queryAndSetValueSet(code) {
      if (!code) {
        return;
      }
      const self = this;
      self.server.QueryValueSetByCode({ code: code }).then(response => {
        self.codeValues[code] = response;
        self.$store.state.createPaymentPreparation.valueSet = self.codeValues;
        if (self.codeValues.length > 2) {
          self.setValueSet(self.codeValues);
        }
      });
    },
    // 创建付款准备
    createPayment() {
      const sel = this.selection[0];
      let data = null;

      data = {
        // ouCode: sel.payRequestOuCode,
        // ouName: sel.payRequestOuName,
        payRequestIds: this.payRequestIds
        // vendorType: sel.vendorType
      };
      this.openCreatePayment(data);
    },
    // 显示付款信息
    showPaymentInfoWin(row) {
      this.payWayInfo.payType = row.payType;
      this.payWayInfo.payRequestLineIds = [row.payRequestLineId];
      this.payWayInfo.buttonText = row.buttonText;
      this.payWayInfo.ouCode = row.payRequestOuCode;
      this.payWayInfo.claimId = row.payRequestClaimId;
      this.$nextTick(() => {
        this.$refs.payWayInfo.showPayWayInfoForm();
      });
    },
    // 表头字段定义
    preparePaymentColumns() {
      return [
        {
          title: '多选',
          type: 'selection',
          align: 'center',
          fixed: 'left',
          width: 60
        },
        {
          title: '付款申请单',
          align: 'left',
          key: 'payRequestClaimNo',
          sortable: 'custom',
          width: 150,
          render: (h, params) => {
            // return h('RowTools', {
            //   attrs: {
            //     title: params.row.payRequestClaimNo
            //   },
            //   props: {
            //     data: [
            //       {
            //         text: params.row.payRequestClaimNo,
            //         handle: () => {
            //           // 打开新页面查看明细
            //           vm.openPayRequest(params.row);
            //         }
            //       }
            //     ]
            //   }
            // });
            return h(
              'span',
              {
                attrs: {
                  title: params.row.payRequestClaimNo
                }
              },
              params.row.payRequestClaimNo
            );
          }
        },
        // {
        //   title: "关联报账单号",
        //   align: "left",
        //   key: "invoiceClaimNo",
        //   sortable: "custom",
        //   width: 200,
        //   render: (h, params) => {
        //     return h("div", [
        //       h(
        //         "span",
        //         {
        //           attrs: {
        //             title: params.row.invoiceClaimNo
        //           }
        //         },
        //         params.row.invoiceClaimNo
        //       )
        //     ]);
        //   }
        // },
        {
          title: '行号',
          align: 'left',
          key: 'payRequestLineId',
          sortable: 'custom',
          width: 60,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.payRequestLineId
                  }
                },
                params.row.payRequestLineId
              )
            ]);
          }
        },
        {
          title: '申请金额',
          align: 'left',
          key: 'applyAmount',
          sortable: 'custom',
          width: 100
        },
        {
          title: '付款信息',
          width: 80,
          sortable: 'custom',
          align: 'left',
          // key: "payWayAmountDescr",
          render: (h, params) => {
            // if (!params.row._disabled) {
            return (
              <PaymentInfoRead
                trigger="hover"
                placement="right-start"
                width="535"
                payRequestLineId={params.row.payRequestLineId}
                payMentModeData={vm.payMentModeData}
                capitalPlanData={vm.capitalPlanData}
                transfersTypeData={vm.transfersTypeData}
              >
                <a
                  href="javascript:;"
                  onClick={e => {
                    vm.showPaymentInfoWin(e);
                  }}
                >
                    查看
                </a>
              </PaymentInfoRead>
            );
          }
          // }
        },
        {
          title: '币种',
          width: 90,
          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: 90,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.categoryName
                  }
                },
                params.row.categoryName
              )
            ]);
          }
        },
        {
          title: '归属公司',
          align: 'left',
          key: 'payRequestOuName',
          sortable: 'custom',
          width: 140,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.payRequestOuName
                  }
                },
                params.row.payRequestOuName
              )
            ]);
          }
        },
        {
          title: '地点',
          align: 'left',
          key: 'vendorSite',
          sortable: 'custom',
          width: 140,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.vendorSite
                  }
                },
                params.row.vendorSite
              )
            ]);
          }
        },

        {
          title: '供应商',
          align: 'left',
          key: 'vendorName',
          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',
          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,
          align: 'left',
          sortable: 'custom',
          key: 'vendorAmountName',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.vendorAmountName
                  }
                },
                params.row.vendorAmountName
              )
            ]);
          }
        },
        {
          title: '收款账户',
          width: 140,
          align: 'left',
          sortable: 'custom',
          key: 'vendorAccountNo',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: `${params.row.vendorAccountNo - params.row.vendorAreaCode - params.row.vendorCbankCode - params.row.vendorBankId}`
                  }
                },
                params.row.vendorAccountNo
              )
            ]);
          }
        },
        {
          title: '优先级',
          width: 90,
          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,
          sortable: 'custom',
          align: 'left',
          key: 'applyEmployeeName',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.applyEmployeeName
                  }
                },
                params.row.applyEmployeeName
              )
            ]);
          }
        },
        {
          title: '申请部门',
          width: 90,
          sortable: 'custom',
          align: 'left',
          key: 'applyDept',
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.applyDept
                  }
                },
                params.row.applyDept
              )
            ]);
          }
        },
        {
          title: '创建日期',
          width: 90,
          sortable: 'custom',
          align: 'left',
          key: 'createTime',
          render: (h, params) => {
            // let createTimeArr = (params.row.createTime || "").split(" ");
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: params.row.createTime
                }
              },
              params.row.createTime
            );
          }
        },
        {
          title: '审批结束日期',
          width: 140,
          align: 'left',
          sortable: 'custom',
          key: 'workflowPassTime',
          render: (h, params) => {
            const lastUpdateTimeArr = (params.row.workflowPassTime || '').split(' ');
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell-ellipsis',
                  title: params.row.workflowPassTime
                }
              },
              params.row.workflowPassTime
            );
          }
        },
        // {
        //   title: "项目编码",
        //   width: 140,
        //   sortable: "custom",
        //   align: "left",
        //   key: "projectCode"
        // },
        // {
        //   title: "项目名称",
        //   width: 140,
        //   sortable: "custom",
        //   align: "left",
        //   key: "projectName"
        // },
        {
          title: '消息',
          align: 'left',
          key: 'message',
          sortable: 'custom',
          minWidth: 90,
          render: (h, params) => {
            return h('div', [
              h(
                'span',
                {
                  attrs: {
                    title: params.row.message
                  }
                },
                params.row.message
              )
            ]);
          }
        }
        // {
        //   title: "付款状态",
        //   width: 180,
        //   align: "left",
        //   key: "payState",
        //   render: (h, params) => {
        //     return h(
        //       "div",
        //       {
        //         attrs: {
        //           class: "ivu-table-cell-ellipsis",
        //           title: params.row.payState
        //         }
        //       },
        //       this.payStateMap[params.row.payState]
        //     );
        //   }
        // },
      ];
    },
    // 搜索
    search(page = 1) {
      const formSearchParams = this.formSearchParams;
      formSearchParams.applyAmount = undefined;
      formSearchParams.draftAmount = undefined;
      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 '';
      }
    },
    // 显示付款信息
    // showPaymentInfoWin(e) {
    //   e.stopPropagation();
    //   // this.payWayInfo.payType = row.payType;
    //   // this.payWayInfo.payRequestLineIds = [row.payRequestLineId];
    //   // 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();
    //   });
    // },
    // 搜索框内 时间起止 设值
    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.payRequestClaimId,
        claimNo: data.payRequestClaimNo,
        openFromPayPlatform: data.openFromPayPlatform,
        newWindow: newWindow
      };
      util.openByClaimIdAndClaimNo(params);
      // let origin = location.origin
      //   ? location.origin
      //   : location.href.split("/#")[0];
      // let params = {
      //   singlePage: "YES",
      //   claimId: data.payRequestClaimId,
      //   showPayment: false,
      //   editPaymentInfo: true,
      //   actionType: "todo",
      //   actId: "act_010"
      //   // crctoken: this.urlParams.crctoken,
      // };
      // window.open(
      //   `${origin}/#/blank?pageName=create-payment-apply&${qs.stringify(
      //     params
      //   )}&crctoken=${sessionStorage.crctoken}`
      // );
    },
    /**
     * 创建付款准备 校验并提示
     * 新增校验创建付款单方法
     *  @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 !== temp_selection.vendorType;
        }); // 对公对私
        if (bool_vendorType) {
          this.$Message.warning('请勾选相同【对公/对私】的行！');
          return true;
        }
        const bool_payRequestOuCode = selections.some(item => {
          return item.payRequestOuCode !== temp_selection.payRequestOuCode;
        }); // 同一归属公司
        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) {
      if (this.createPaymentValidate()) {
        return false;
      }
      this.createPaymentBtnLoading = true;
      server
        .queryCreatePayment(param)
        .then(response => {
          if (response.statusCode !== '-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.batchNo;
            const id = response.data.payBatchId;
            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.msg);
          }
        })
        .catch(error => {});
    }
  },
  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;
      }
      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 payWayAmountDescrArr = [];
      for (let m = 0; m < this.selections.length; m++) {
        payWayAmountDescrArr = this.selections[m].payWayAmountDescr.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.startApplyAmount = range.start;
    //     this.formSearch.endApplyAmount = range.end;
    //   },
    //   deep: true
    // },

    'formSearch.draftAmount': {
      handler() {
        const range = this.formSearch.draftAmount;
        this.formSearch.startDraftAmount = range.start;
        this.formSearch.endDraftAmount = range.end;
      },
      deep: true
    }
  },
  directives: {},
  filters: {}
};
</script>

<style scoped lang="less">
// .paymentInfo {
//   color: red;
//   text-align: right;

//   > span {
//     padding-left: 10px;
//   }
// }
// .ul-amount{
//   float: left;
// }
// .count-amount{
//   float: left;
// }
// .payWayInfo {
//   position: absolute;
//   z-index: -100;
//   left: -1000000px;
// }
</style>
