<!-- 合同付款 -->
<template>
  <div class="container-wrap">
    <div class="bar-wrap">
      <div class="bar-title">
        <span style="font-size: 14px; font-weight: bold">付费统计</span>
        <span style="cursor: pointer" @click="$router.push('pay_history')"
          >查看历史付款记录>></span
        >
      </div>
      <div class="bar-2">
        <div
          :class="payTimeType == 1 ? 'active' : ''"
          @click="selectTime(1)"
          v-if="!isFirstMonth"
        >
          <Table :columns="columns1" :data="data1"></Table>
        </div>
        <div
          :class="payTimeType == 1.5 ? 'active' : ''"
          @click="selectTime(1.5)"
          style="width: 24%"
        >
          <Table :columns="columns2" :data="data2"></Table>
        </div>
        <div
          :class="payTimeType == 2 ? 'active' : ''"
          @click="selectTime(2)"
          v-if="isFirstMonth"
        >
          <Table :columns="columns1" :data="data1"></Table>
        </div>
        <div :class="payTimeType == 3 ? 'active' : ''" @click="selectTime(3)">
          <Table :columns="columns3" :data="data3"></Table>
        </div>
        <div :class="payTimeType == 4 ? 'active' : ''" @click="selectTime(4)">
          <Table :columns="columns4" :data="data4"></Table>
        </div>
        <div :class="payTimeType == 5 ? 'active' : ''" @click="selectTime(5)">
          <Table :columns="columns5" :data="data5"></Table>
        </div>
        <div :class="payTimeType == 6 ? 'active' : ''" @click="selectTime(6)">
          <Table :columns="columns6" :data="data6"></Table>
        </div>
      </div>
    </div>
    <div class="container">
      <div style="background: #fff; padding: 10px; margin-bottom: 10px">
        <Tabs v-model="salesVolumeCompanyTotalType" @on-click="tabsChange">
          <TabPane label="全部" name="1"></TabPane>
          <TabPane
            :label="
              (h) => {
                return h('div', [
                  h('span', '50万以上('),
                  h(
                    'span',
                    { style: { color: 'red' } },
                    salesVolumeCompanyTotal['50up']
                  ),
                  h('span', ')'),
                ]);
              }
            "
            name="2"
          ></TabPane>
          <TabPane
            :label="
              (h) => {
                return h('div', [
                  h('span', '20-50万('),
                  h(
                    'span',
                    { style: { color: 'red' } },
                    salesVolumeCompanyTotal['20-50']
                  ),
                  h('span', ')'),
                ]);
              }
            "
            name="3"
          ></TabPane>
          <TabPane
            :label="
              (h) => {
                return h('div', [
                  h('span', '10-20万('),
                  h(
                    'span',
                    { style: { color: 'red' } },
                    salesVolumeCompanyTotal['10-20']
                  ),
                  h('span', ')'),
                ]);
              }
            "
            name="4"
          ></TabPane>
          <TabPane
            :label="
              (h) => {
                return h('div', [
                  h('span', '5-10万('),
                  h(
                    'span',
                    { style: { color: 'red' } },
                    salesVolumeCompanyTotal['5-10']
                  ),
                  h('span', ')'),
                ]);
              }
            "
            name="5"
          ></TabPane>
          <TabPane
            :label="
              (h) => {
                return h('div', [
                  h('span', '5万以下('),
                  h(
                    'span',
                    { style: { color: 'red' } },
                    salesVolumeCompanyTotal['5down']
                  ),
                  h('span', ')'),
                ]);
              }
            "
            name="6"
          ></TabPane>
        </Tabs>
        <div>
          <Button
            style="margin: 0 10px 5px 0"
            :type="params.companySelectId == null ? 'primary' : 'default'"
            @click="changeCompany(null, 0)"
            >全部</Button
          >
          <Button
            style="margin: 0 10px 5px 0"
            @click="changeCompany(i.supplierId, index)"
            v-for="(i, index) in company"
            :type="
              params.companySelectId == i.supplierId ? 'primary' : 'default'
            "
            :key="i.supplierId"
            v-if="
              i.type == salesVolumeCompanyTotalType ||
              salesVolumeCompanyTotalType == '1'
            "
          >
            {{ i.supplierName
            }}<span
              :style="
                params.companySelectId == i.supplierId
                  ? 'color:#ffc107'
                  : 'color:red'
              "
            >
              ({{ i.total }})</span
            >
          </Button>
        </div>
      </div>
      <!-- 检索 -->
      <div class="table-filter" @keyup.enter="search">
        <div class="filter-item" style="border-right: 1px solid #dcdcdc">
          <RadioGroup v-model="params.payBillStatus" @on-change="statusChange">
            <Radio :label="0">
              <span>
                全部
                <span class="red">({{ unApprovalOrunCompleteCount }})</span>
              </span>
            </Radio>
            <Radio :label="1">
              <span>
                可发起
                <span class="red">({{ unApprovalCount }})</span>
              </span>
            </Radio>
            <Radio :label="2">
              <span>
                待补齐
                <span class="red">({{ unCompleteCount }})</span>
              </span>
            </Radio>
          </RadioGroup>
        </div>
        <div class="filter-item">
          <RadioGroup v-model="params.cycleType" @on-change="cycleTypeChange">
            <Radio :label="0">
              <span>
                全部
                <span class="red"
                  >({{
                    cycle.currentPeriod + cycle.upperCycle + cycle.nextCycle
                  }})</span
                >
              </span>
            </Radio>
            <Radio :label="1">
              <span>
                本周期
                <span class="red">({{ cycle.currentPeriod }})</span>
              </span>
            </Radio>
            <Radio :label="2">
              <span>
                上周期顺延
                <span class="red">({{ cycle.upperCycle }})</span>
              </span>
            </Radio>
            <Radio :label="3">
              <span>
                其他
                <span class="red">({{ cycle.nextCycle }})</span>
              </span>
            </Radio>
          </RadioGroup>
        </div>

        <div class="filter-item">
          <Input v-model="keyWord" placeholder="请输入关键字" clearable />
        </div>
        <div class="filter-item">
          <Button type="primary" style="width: 90px" @click="search"
            >查询</Button
          >
        </div>
        <div class="filter-item">
          <Button type="primary" style="width: 90px" @click="exportExcel"
            >导出Excel</Button
          >
        </div>
        <div class="filter-item">
          <Button type="primary" style="width: 90px" @click="toBill"
            >查看账单</Button
          >
        </div>
        <div class="filter-item" style="float: right">
          <Button type="error" @click="toDetail">审批本周期付款申请</Button>
        </div>
        <!--      <div class="filter-item" style="float: right;margin-right: 0">-->
        <!--        <Button type="primary" style="width: 90px;">打印详情</Button>-->
        <!--      </div>-->
      </div>
      <!-- 表格 -->
      <div class="table-content">
        <div class="list">
          <div class="item" v-for="(item, index) in showList" :key="index">
            <div class="item-left">
              <div class="row">
                <div class="col">
                  <div class="label">合同编码：</div>
                  <div class="value">
                    {{ item.purchaseBillNo }}
                  </div>
                </div>
                <div class="col">
                  <div class="label">供应商：</div>
                  <div class="value">
                    {{ item.supplierName }}
                  </div>
                </div>
                <div class="col">
                  <div class="label">付款期限：</div>

                  <div
                    class="value"
                    :style="
                      item.payTimeLimit.indexOf('超过') == -1
                        ? 'color:rgb(7, 201, 9)'
                        : 'color:red'
                    "
                  >
                    {{ item.payTimeLimit }}
                    <Poptip placement="bottom">
                      <Icon
                        type="ios-alert-outline"
                        size="20"
                        style="
                          margin: 0 10px 0 5px;
                          position: relative;
                          top: -2px;
                          color: #333;
                        "
                      />
                      <div
                        class="api"
                        slot="content"
                        style="padding: 10px; color: #333"
                      >
                        最后入库时间：{{ item.completeStockTime }}<br />
                        供应商账期：{{ item.accountDate }}天
                      </div>
                    </Poptip>
                  </div>
                </div>
                <div class="col" style="flex: 1">
                  <div class="label">实收发票：</div>
                  <div class="value">{{ item.invoiceAmount }}元</div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <div class="label">物料名称：</div>
                  <div class="value">
                    {{ item.materialName }}
                  </div>
                </div>
                <div class="col">
                  <div class="label">规格：</div>
                  <div class="value">{{ item.spec }}</div>
                </div>
                <div class="col">
                  <div class="label">采购数量：</div>
                  <div class="value">
                    {{ item.purchaseQty }}
                  </div>
                </div>
                <div class="col" style="flex: 1">
                  <div class="label">单价：</div>
                  <div class="value">{{ item.price }}</div>
                </div>
              </div>
              <div class="row">
                <div class="col">
                  <div class="label">合同金额：</div>
                  <div class="value">{{ item.contractAmount }}元</div>
                </div>
                <div class="col">
                  <div class="label">质检金额：</div>
                  <div class="value">{{ item.qtyCheckAmount }}元</div>
                </div>
                <div class="col">
                  <div class="label">已付金额：</div>
                  <div class="value">{{ item.hadPayAmount }}元</div>
                </div>
                <div class="col" style="flex: 1">
                  <Tooltip
                    placement="bottom"
                    @on-popper-show="getData(item)"
                    max-width="600"
                  >
                    <div class="label">
                      <span style="text-decoration:underline">未付金额：{{ item.unPayAmount }}元</span>
                    </div>
                    <div slot="content">
                      <div v-for="(itemPay, index) in paymentList" :key="index">
                        <span style="text-align: left; white-space: normal">
                          物料编码: {{ itemPay.materialcode }}
                        </span>
                        <span
                          style="
                            padding-left: 16px;
                            text-align: left;
                            white-space: normal;
                          "
                        >
                          合同批次: {{ itemPay.batchno }}
                        </span>
                        <span
                          style="
                            padding-left: 16px;
                            text-align: left;
                            white-space: normal;
                          "
                        >
                          退货日期: {{ itemPay.outDate }}
                        </span>
                        <span
                          style="
                            padding-left: 16px;
                            text-align: left;
                            white-space: normal;
                          "
                        >
                          退货数量: {{ itemPay.quantity }}
                        </span>
                        <span
                          style="
                            padding-left: 16px;
                            text-align: left;
                            white-space: normal;
                          "
                        >
                          单价: {{ itemPay.price }}
                        </span>
                        <span
                          style="
                            padding-left: 16px;
                            text-align: left;
                            white-space: normal;
                          "
                        >
                          金额: {{ itemPay.amount }}
                        </span>
                        <span
                          style="
                            padding-left: 16px;
                            text-align: left;
                            white-space: normal;
                          "
                        >
                          原因: {{ itemPay.applyreason }}
                        </span>
                      </div>
                    </div>
                  </Tooltip>
                </div>
              </div>
            </div>
            <div class="item-right">
              <div class="forms">
                <div class="row">
                  <div class="col">
                    <span class="text" @click="showForm(0, item)">申购单</span>
                    <Icon type="md-checkmark" color="#07C909" size="20" />
                  </div>
                  <div class="col">
                    <span class="text" @click="showForm(1, item)">入库单</span>
                    <Icon
                      v-if="item.hasInStock"
                      type="md-checkmark"
                      color="#07C909"
                      size="20"
                    />
                    <Icon v-else type="md-close" color="red" size="20" />
                  </div>
                  <div class="col">
                    <span class="text" @click="showForm(2, item)">质检单</span>
                    <Icon
                      v-if="item.hasQtyCheck"
                      type="md-checkmark"
                      color="#07C909"
                      size="20"
                    />
                    <Icon v-else type="md-close" color="red" size="20" />
                  </div>
                  <div class="col">
                    <span class="text" @click="showForm(3, item)">合同</span>
                    <Icon
                      v-if="item.hasContractFile"
                      type="md-checkmark"
                      color="#07C909"
                      size="20"
                    />
                    <Icon v-else type="md-close" color="red" size="20" />
                  </div>
                  <div class="col">
                    <span class="text" @click="showForm(4, item)">发票</span>
                    <Icon
                      v-if="item.hasGreaterCheckAmt"
                      type="md-checkmark"
                      color="#07C909"
                      size="20"
                    />
                    <Icon v-else type="md-close" color="red" size="20" />
                  </div>
                </div>
                <div class="row">
                  <div
                    class="col"
                    style="justify-content: flex-start; padding: 0"
                  >
                    <span
                      class="text"
                      style="text-decoration: none; cursor: auto"
                      >质检金额&lt;=发票金额</span
                    >
                    <Icon
                      v-if="item.hasGreaterCheckAmt"
                      type="md-checkmark"
                      color="#07C909"
                      size="20"
                    />
                    <Icon v-else type="md-close" color="red" size="20" />
                  </div>
                  <div
                    class="col"
                    v-if="
                      ['supervisor', 'purchase'].includes(access) &&
                      item.canApplyPay === 2 &&
                      item.inApprovalAmount
                    "
                  >
                    <span>审批中：{{ item.inApprovalAmount }}元</span>
                  </div>
                </div>
              </div>
              <!-- 总监操作 -->
              <div v-if="['supervisor', 'purchase'].includes(access)">
                <div class="btn" v-if="item.canApplyPay === 0">
                  <Button
                    type="primary"
                    style="width: 92px; background-color: #62bceb; border: none"
                    @click="pass(item)"
                    >发起预付款</Button
                  >
                </div>
                <div class="btn" v-if="item.canApplyPay === 1">
                  <Button
                    type="primary"
                    style="width: 92px; border: none"
                    @click="pass(item)"
                    >发起申请</Button
                  >
                </div>
                <div class="btn" v-if="item.canApplyPay === 2">
                  <Button
                    type="primary"
                    disabled
                    style="width: 92px; border: none"
                    >发起申请</Button
                  >
                </div>
                <div
                  class="btn"
                  v-if="item.canApplyPay === 3"
                  style="width: 92px"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <div class="table-page">
        <Page
          :current="params.pageIndex"
          :total="params.total"
          :page-size="params.pageSize"
          :show-total="true"
          show-elevator
          @on-change="changePage"
        />
      </div>
    </div>
    <pass-modal
      v-model="passShow"
      :data="currentItem"
      @getlist="getList"
    ></pass-modal>
    <my-form-pay
      v-model="payShow"
      type="form"
      :data="currentItem"
      :showSider="false"
    ></my-form-pay>
    <store-in-form v-model="storeInShow" :data="currentItem"></store-in-form>
    <quality-form v-model="qualityShow" :data="qualityData"></quality-form>
    <invoice-form
      v-model="invoiceShow"
      :data="currentItem"
      @getlist="getList"
    ></invoice-form>
    <contract-form
      v-model="contractShow"
      :data="currentItem"
      @getlist="getList"
    ></contract-form>
    <apply-form
      v-model="applyShow"
      :data="currentItem"
      @getlist="getList"
    ></apply-form>
  </div>
</template>

<script>
import { exportExcel } from "@/libs/util";
import {
  GetPurContractPayBill,
  GetContractPayBillTotal,
  ApprovalBillFlow,
  GetApplyPurchasePageList,
  GetContractQtyCheckBill,
  AddApplyPurchasePay,
  selectDetails,
} from "@/api/applyPurchase";
import MyTable from "_c/my-table/my-table";
import MyFormPay from "_c/my-modal-pay";
import PassModal from "./modals/pass-modal";
import StoreInForm from "./modals/store-in-form";
import QualityForm from "./modals/quality-form";
import InvoiceForm from "./modals/invoice-form";
import ContractForm from "./modals/contract-form";
import ApplyForm from "./modals/apply-form";
import { GetInStockBill } from "@/api/stock";
import axios from "axios";
// import { json } from 'stream/consumers'

export default {
  name: "material_pay",
  components: {
    MyTable,
    PassModal,
    MyFormPay,
    StoreInForm,
    QualityForm,
    InvoiceForm,
    ContractForm,
    ApplyForm,
  },
  data() {
    return {
      payTimeType: null,
      columns1: [],
      columns2: [],
      columns3: [],
      columns4: [],
      columns5: [],
      columns6: [],
      data1: [],
      data2: [],
      data3: [],
      data4: [],
      data5: [],
      data6: [],
      tabIndex: "",
      access: this.$store.state.user.access,
      applyShow: false,
      contractShow: false,
      invoiceShow: false,
      qualityShow: false,
      storeInShow: false,
      payShow: false, // 申购单
      passShow: false, // 驳回
      currentItem: {},
      payBillStatus: 0,
      keyWord: "",
      formData: {},
      qualityData: [],
      data: {},
      titleData: {
        curMonthPay: {
          firDateTime: "",
          firAmount: 0,
          secDateTime: "",
          secAmount: 0,
        },
        nextMonthPay: {
          firDateTime: "",
          firAmount: 0,
          secDateTime: "",
          secAmount: 0,
        },
        lastMonthPay: {
          firDateTime: "",
          firAmount: 0,
          secDateTime: "",
          secAmount: 0,
        },
      },
      params: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
        cycle: null,
        companySelectId: null,
        payBillStatus: 0,
        cycleType: 0,
        payTime: "",
      },
      isFirstMonth: true,
      company: [],
      companySelectId: null,
      companySelectIndex: null,
      showList: [],
      showListCopy: [],
      salesVolumeCompanyTotalType: "1",
      salesVolumeCompanyTotal: {
        "50up": 0,
        "20-50": 0,
        "10-20": 0,
        "5-10": 0,
        "5down": 0,
      },

      cycle: {
        upperCycle: 0,
        currentPeriod: 0,
        nextCycle: 0,
      },
      unApprovalCount: 0,
      unCompleteCount: 0,
      unApprovalOrunCompleteCount: 0,
      paymentList: [],
    };
  },
  methods: {
    tabsChange() {
      const v = this;
      v.params.companySelectId = null;
      v.searchFn();
    },
    selectTime(num) {
      if (this.payTimeType == num) {
        this.payTimeType = null;
        this.params.payTime = "";
        this.getList();
        return;
      } else {
        this.payTimeType = num;
      }
      const dateDayNum = new Date().getDate();
      const dateMonthNum = new Date().getMonth() + 1;
      const dateYearNum = new Date().getFullYear();
      if (num == 1) {
        this.params.payTime = dateYearNum + "-" + dateMonthNum + "-15 00:00:00";
      }
      if (num == 1.5) {
        if (dateDayNum <= 15) {
          this.params.payTime =
            dateYearNum + "-" + dateMonthNum + "-15 00:00:00";
        } else {
          this.params.payTime =
            dateYearNum +
            "-" +
            dateMonthNum +
            "-" +
            new Date(dateYearNum, dateMonthNum, 0).getDate() +
            " 00:00:00";
        }
      }
      if (num == 2) {
        this.params.payTime =
          dateYearNum +
          "-" +
          dateMonthNum +
          "-" +
          new Date(dateYearNum, dateMonthNum, 0).getDate() +
          " 00:00:00";
      }
      if (num == 3) {
        this.params.payTime =
          dateYearNum + "-" + (dateMonthNum * 1 + 1) + "-15 00:00:00";
      }
      if (num == 4) {
        this.params.payTime =
          dateYearNum +
          "-" +
          (dateMonthNum * 1 + 1) +
          "-" +
          new Date(dateYearNum, dateMonthNum * 1 + 1, 0).getDate() +
          " 00:00:00";
      }
      if (num == 5) {
        this.params.payTime =
          dateYearNum + "-" + (dateMonthNum * 1 + 2) + "-15 00:00:00";
      }
      if (num == 6) {
        this.params.payTime =
          dateYearNum +
          "-" +
          (dateMonthNum * 1 + 2) +
          "-" +
          new Date(dateYearNum, dateMonthNum * 1 + 2, 0).getDate() +
          " 00:00:00";
      }
      this.getList();
    },
    cycleTypeChange() {
      const v = this;
      v.params.pageIndex = 1;
      v.searchFn();
    },
    changeCompany(_id, index) {
      const v = this;
      v.params.pageIndex = 1;
      v.params.total = v.company[index].list.length;
      if (v.params.companySelectId == _id || _id == null) {
        // v.showList = v.showListCopy.slice(0,10)
        v.params.companySelectId = null;
      } else {
        v.params.companySelectId = _id;
        v.companySelectIndex = index;
      }
      v.searchFn();
    },
    changePage(pageIndex) {
      const v = this;
      this.params.pageIndex = pageIndex;
      v.searchFn();
    },
    searchFn() {
      const v = this;
      v.unApprovalCount = 0;
      v.unCompleteCount = 0;
      if (v.salesVolumeCompanyTotalType) {
      } else {
      }
      const list = JSON.parse(JSON.stringify(v.showListCopy));
      console.log(v.params.companySelectId);
      if (v.params.companySelectId) {
        for (let i = 0; i < list.length; i++) {
          const element = list[i];
          if (element.supplierId != v.params.companySelectId) {
            list.splice(i, 1);
            i--;
          }
        }
      }
      v.unApprovalOrunCompleteCount = list.length;
      for (let i = 0; i < list.length; i++) {
        const element = list[i];
        if (element.canApplyPay == 0 || element.canApplyPay == 1) {
          v.unApprovalCount++;
        }
        if (element.toBeComplete) {
          v.unCompleteCount++;
        }
      }
      if (!v.params.payBillStatus == 0) {
        for (let i = 0; i < list.length; i++) {
          const element = list[i];
          if (v.params.payBillStatus == 1) {
            if (element.canApplyPay != 0 && element.canApplyPay != 1) {
              list.splice(i, 1);
              i--;
              continue;
            } else {
            }
          }
          if (v.params.payBillStatus == 2) {
            if (!element.toBeComplete) {
              list.splice(i, 1);
              i--;
              continue;
            }
          }
        }
      }

      const dateDayNum = new Date().getDate();
      const dateMonthNum = new Date().getMonth() + 1;
      const dateYearNum = new Date().getFullYear();
      const zhangqiMo =
        dateDayNum <= 15
          ? new Date(dateYearNum + "-" + dateMonthNum + "-16").valueOf()
          : new Date(
              dateYearNum + "-" + (dateMonthNum * 1 + 1) + "-1"
            ).valueOf();
      const zhangqichu =
        dateDayNum <= 15
          ? new Date(dateYearNum + "-" + dateMonthNum + "-1").valueOf()
          : new Date(dateYearNum + "-" + dateMonthNum + "-16").valueOf();

      v.cycle = {
        upperCycle: 0,
        currentPeriod: 0,
        nextCycle: 0,
      };
      //计算账期数量
      for (let i = 0; i < list.length; i++) {
        const element = list[i];
        if (new Date(element.oldPayTime).valueOf() > zhangqiMo) {
          v.cycle.nextCycle++;
          element.cycleType = 3;
        } else if (new Date(element.oldPayTime).valueOf() < zhangqichu) {
          v.cycle.upperCycle++;
          element.cycleType = 2;
        } else if (new Date(element.oldPayTime).valueOf() > zhangqichu) {
          v.cycle.currentPeriod++;
          element.cycleType = 1;
        }
      }
      //删除不是的选项
      for (let i = 0; i < list.length; i++) {
        const element = list[i];
        if (
          v.params.cycleType != 0 &&
          v.params.cycleType != element.cycleType
        ) {
          list.splice(i, 1);
          i--;
        }
      }
      console.log(list);
      v.showList = JSON.parse(JSON.stringify(list)).slice(
        (v.params.pageIndex - 1) * 10,
        v.params.pageIndex * 10
      );
      v.params.total = list.length;
      this.$Spin.hide();
    },
    getList() {
      const v = this;
      this.$Spin.show();
      GetPurContractPayBill({
        pageIndex: 1,
        pageSize: 1000000,
        keyWord: this.keyWord,
        payBillStatus: this.params.payBillStatus,
        payTime: this.params.payTime,
      }).then((res) => {
        if (res.code === 0) {
          v.company = [];
          v.salesVolumeCompanyTotal = {
            "50up": 0,
            "20-50": 0,
            "10-20": 0,
            "5-10": 0,
            "5down": 0,
          };
          const handle2 = (contractAmount, qtyCheckAmount) => {
            return function (a, b) {
              const val1 =
                a[qtyCheckAmount] == 0 ? a[contractAmount] : a[qtyCheckAmount];
              const val2 =
                b[qtyCheckAmount] == 0 ? b[contractAmount] : b[qtyCheckAmount];
              return val2 - val1;
            };
          };
          res.result.payBillItems.sort(
            handle2("contractAmount", "qtyCheckAmount")
          );
          this.showListCopy = JSON.parse(
            JSON.stringify(res.result.payBillItems)
          );
          this.data = JSON.parse(JSON.stringify(res.result));
          this.showList = this.showListCopy.slice(0, 10);
          for (let i = 0; i < res.result.payBillItems.length; i++) {
            const element = res.result.payBillItems[i];
            const isCompany = false;
            for (let j = 0; j < v.company.length; j++) {
              const jelement = v.company[j];
              if (element.supplierId == jelement.supplierId) {
                isCompany = true;
                jelement.total =
                  element.qtyCheckAmount == 0
                    ? (jelement.total * 1000 + element.contractAmount * 1000) /
                      1000
                    : (jelement.total * 1000 + element.qtyCheckAmount * 1000) /
                      1000;
                jelement.list.push(element);
              }
            }
            //如果不存在就新建一条
            if (!isCompany) {
              v.company.push({
                list: [{ ...element }],
                total:
                  element.qtyCheckAmount == 0
                    ? element.contractAmount
                    : element.qtyCheckAmount,
                supplierId: element.supplierId,
                supplierName: element.supplierName,
              });
            }
          }

          for (let i = 0; i < v.company.length; i++) {
            const element = v.company[i];
            const totalkeyName =
              element.total < 50000
                ? "5down"
                : element.total >= 50000 && element.total < 100000
                ? "5-10"
                : element.total >= 100000 && element.total < 200000
                ? "10-20"
                : element.total >= 200000 && element.total < 500000
                ? "20-50"
                : element.total >= 500000
                ? "50up"
                : "";
            element.type =
              element.total < 50000
                ? "6"
                : element.total >= 50000 && element.total < 100000
                ? "5"
                : element.total >= 100000 && element.total < 200000
                ? "4"
                : element.total >= 200000 && element.total < 500000
                ? "3"
                : element.total >= 500000
                ? "2"
                : "";
            v.salesVolumeCompanyTotal[totalkeyName]++;
          }
          const handle = (property) => {
            return function (a, b) {
              const val1 = a[property];
              const val2 = b[property];
              return val2 - val1;
            };
          };
          v.company.sort(handle("total"));
          v.searchFn();
        }
      });
    },
    /* 获取顶部信息 */
    getContractPayTotal() {
      const v = this;
      GetContractPayBillTotal().then((res) => {
        if (res.code === 0) {
          this.titleData = res.result;
          var dateDayNum = new Date().getDate();
          if (dateDayNum > 15) {
            this.getContractPayment(
              (this.titleData.curMonthPay.secAmount * 1000 +
                this.titleData.curMonthPay.secPayAmount * 1000) /
                1000,
              this.titleData.curMonthPay.secAmount
            );
          } else {
            this.getContractPayment(
              (this.titleData.curMonthPay.firAmount * 1000 +
                this.titleData.curMonthPay.firPayAmount * 1000) /
                1000,
              this.titleData.curMonthPay.secAmount
            );
          }

          v.columns3 = [
            {
              title:
                new Date(v.titleData.nextMonthPay.firDateTime).getMonth() +
                1 +
                "月15号",
              key: "name",
            },
            { title: "应付", key: "yinfu" },
          ];
          v.columns4 = [
            {
              title:
                new Date(v.titleData.nextMonthPay.secDateTime).getMonth() +
                1 +
                "月" +
                new Date(v.titleData.nextMonthPay.secDateTime).getDate() +
                "号",
              key: "name",
            },
            { title: "应付", key: "yinfu" },
          ];
          v.columns5 = [
            {
              title:
                new Date(v.titleData.lastMonthPay.firDateTime).getMonth() +
                1 +
                "月15号",
              key: "name",
            },
            { title: "应付", key: "yinfu" },
          ];
          v.columns6 = [
            {
              title:
                new Date(v.titleData.lastMonthPay.secDateTime).getMonth() +
                1 +
                "月" +
                new Date(v.titleData.lastMonthPay.secDateTime).getDate() +
                "号",
              key: "name",
            },
            { title: "应付", key: "yinfu" },
          ];
          v.data3 = [
            { name: "合计", yinfu: v.titleData.nextMonthPay.firAmount },
            { name: "有账期", yinfu: v.titleData.nextMonthPay.firAmount },
            { name: "预付款", yinfu: 0 },
          ];
          v.data4 = [
            { name: "合计", yinfu: v.titleData.nextMonthPay.secAmount },
            { name: "有账期", yinfu: v.titleData.nextMonthPay.secAmount },
            { name: "预付款", yinfu: 0 },
          ];
          v.data5 = [
            { name: "合计", yinfu: v.titleData.lastMonthPay.firAmount },
            { name: "有账期", yinfu: v.titleData.lastMonthPay.firAmount },
            { name: "预付款", yinfu: 0 },
          ];
          v.data6 = [
            { name: "合计", yinfu: v.titleData.lastMonthPay.secAmount },
            { name: "有账期", yinfu: v.titleData.lastMonthPay.secAmount },
            { name: "预付款", yinfu: 0 },
          ];
        }
      });
    },
    getContractPayment(_total, _yinfuNum) {
      const v = this;
      axios.get("/javaApi/contractPayment", {}).then((res) => {
        console.log(res);
        var dateDayNum = new Date().getDate();
        var dateMonthNum = new Date().getMonth();
        const dateYearNum = new Date().getFullYear();
        console.log(dateDayNum);
        if (dateDayNum > 15) {
          v.isFirstMonth = false;
          v.columns1 = [
            { title: dateMonthNum + 1 + "月15号", key: "name" },
            { title: "已付", key: "yifu" },
          ];
          v.data1 = [];
          let total = 0;
          for (
            let i = 0;
            i < res.data.result.paidInLastAccountingPeriod.length;
            i++
          ) {
            const element = res.data.result.paidInLastAccountingPeriod[i];
            total = total + element["已付"] * 1;
            v.data1.unshift({
              name: element["类型"],
              yifu: element["已付"],
            });
          }
          v.data1.unshift({
            name: "合计",
            yifu: total,
          });
        } else {
          v.columns1 = [
            {
              title:
                dateMonthNum +
                1 +
                "月" +
                new Date(dateYearNum, dateMonthNum * 1 + 2, 0).getDate() +
                "号",
              key: "name",
            },
            { title: "应付", key: "yifu" },
          ];
          v.data1 = [
            {
              name: "合计",
              yifu: _yinfuNum,
            },
            {
              name: "有账期",
              yifu: _yinfuNum,
            },
            {
              name: "预付款",
              yifu: 0,
            },
          ];
        }
        v.columns2 = [
          {
            title:
              dateMonthNum +
              1 +
              "月" +
              (dateDayNum > 15
                ? new Date(dateYearNum, dateMonthNum * 1 + 2, 0).getDate()
                : "15") +
              "号",
            key: "name",
          },
          { title: "应付", key: "yinfu" },
          { title: "已付", key: "yifu" },
          { title: "未付", key: "weifu" },
        ];
        if (res.data.result.paid.length == 0) {
          res.data.result.paid = [
            {
              PayAmount: 0,
            },
            {
              PayAmount: 0,
            },
          ];
        }
        const msg = [
          {
            PayAmount: 0,
          },
          {
            PayAmount: 0,
          },
        ];
        for (let i = 0; i < res.data.result.paid.length; i++) {
          const element = res.data.result.paid[i];
          if (element.ApplyPayType == 0) {
            msg[0].ApplyPayType = element.ApplyPayType;
            msg[0].PayAmount = element.PayAmount;
          } else if (element.ApplyPayType == 1) {
            msg[1].ApplyPayType = element.ApplyPayType;
            msg[1].PayAmount = element.PayAmount;
          }
        }
        console.log(msg);
        res.data.result.paid = msg;
        v.data2 = [
          {
            name: "合计",
            yinfu: _total,
            yifu:
              res.data.result.paid[0].PayAmount +
              res.data.result.paid[1].PayAmount,
            weifu:
              (_total * 1000 -
                (res.data.result.paid[0].PayAmount * 1000 +
                  res.data.result.paid[1].PayAmount * 1000)) /
              1000,
          },
          {
            name: "有账期",
            yinfu: _total - res.data.result.currentAccountingPeriod,
            yifu: res.data.result.paid[0].PayAmount,
            weifu:
              (_total * 1000 -
                res.data.result.currentAccountingPeriod * 1000 -
                res.data.result.paid[0].PayAmount * 1000) /
              1000,
          },
          {
            name: "预付款",
            yinfu: res.data.result.currentAccountingPeriod,
            yifu: res.data.result.paid[1].PayAmount,
            weifu:
              (res.data.result.currentAccountingPeriod * 1000 -
                res.data.result.paid[1].PayAmount * 1000) /
              1000,
          },
        ];
        console.log(v.data2);
      });
    },

    dateClick(date, index) {
      if (this.tabIndex === index) {
        this.tabIndex = "";
        this.params.payTime = "";
        this.params.pageIndex = 1;
      } else {
        this.tabIndex = index;
        this.params.payTime = date;
        this.params.pageIndex = 1;
      }
      this.getList();
    },
    showForm(type, item) {
      this.currentItem = { ...item };
      switch (type) {
        // 申购单
        case 0:
          this.currentItem.id = this.currentItem.payBillId;
          GetApplyPurchasePageList({
            pageIndex: 1,
            pageSize: 1,
            purBillState: 1,
            keyWord: this.currentItem.applyBillNo,
          }).then((res) => {
            if (res.code === 0) {
              this.currentItem = {
                ...this.currentItem,
                ...res.result.list[0],
              };
              this.payShow = true;
              console.log(this.currentItem);
            }
          });
          break;
        case 1:
          GetInStockBill({
            inOutStorageNo: this.currentItem.inOutStorageNo,
            applyBillNo: this.currentItem.applyBillNo,
          }).then((res) => {
            if (res.code === 0) {
              this.currentItem = {
                ...this.currentItem,
                ...res.result,
              };
              this.storeInShow = true;
            }
          });
          break;
        case 2:
          GetContractQtyCheckBill({
            purchaseBillNo: this.currentItem.purchaseBillNo,
          }).then((res) => {
            if (res.code === 0) {
              this.qualityData = res.result;
              this.qualityShow = true;
            }
          });
          break;
        case 3:
          this.contractShow = true;
          break;
        case 4:
          this.invoiceShow = true;
          break;
      }
    },
    /* 审核 */
    pass(item) {
      // if (type === 0) {
      //   this.$MyModal.show({ text: '是否通过' }).$on('confirm', () => {
      //     this.cfm(type)
      //   })
      // } else {
      //   this.passShow = true
      // }
      AddApplyPurchasePay({
        purchaseBillNo: item.purchaseBillNo,
      }).then((res) => {
        if (res.code === 0) {
          this.currentItem = {
            ...res.result,
            bankMesList: res.result.bankMesList
              .filter((data) => data.bankAccoutName)
              .map((item) => {
                return {
                  bankAccout: item.bankAccout || "",
                  bankAccoutName: item.bankAccoutName || "",
                  openBank: item.openBank || "",
                };
              }),
            canApplyPay: item.canApplyPay,
            contractAmount: item.contractAmount,
          };
          this.applyShow = true;
        }
      });
    },
    /* 审批 */
    cfm(type) {
      ApprovalBillFlow({
        linkCheckId: [this.currentItem.flowCheckId],
        updateAction: type,
        suggestions: this.remark,
      }).then((res) => {
        if (res.code === 0) {
          this.$Message.info(res.msg || "操作成功！");
          this.currentItem = {};
          this.getList();
        }
      });
    },
    /* 查看账单 */
    toBill() {
      this.$router.push("material_bill");
    },
    /* 跳转订单详情 */
    toDetail(date, type) {
      // this.$router.push({
      //   name: 'material_pay_detail',
      //   query: {
      //     payDateTime: date,
      //     type
      //   }
      // })
      this.$router.push({
        name: "material_pay_detail",
      });
    },
    statusChange() {
      this.params.pageIndex = 1;
      this.keyWord = "";
      this.searchFn();
    },

    search() {
      this.params.pageIndex = 1;
      this.getList();
    },
    exportExcel() {
      GetPurContractPayBill({
        ...this.params,
        keyWord: this.keyWord,
        payBillStatus: this.payBillStatus,
        pageIndex: 1,
        pageSize: 99999,
      }).then((res) => {
        if (res.code === 0) {
          axios
            .post("/javaApi/selectDetails", { beginTime: this.params.payTime })
            .then((res2) => {
              for (let i = 0; i < res.result.payBillItems.length; i++) {
                const element = res.result.payBillItems[i];
                for (let j = 0; j < res2.data.result.length; j++) {
                  const jelement = res2.data.result[j];
                  if (element.purchaseBillNo == jelement.fromBillNo) {
                    element.completeStockTime = jelement.completeStockTime;
                    element.amount = jelement.amount;
                    element.payAmount = jelement.payAmount;
                    element.accountDate = jelement.accountDate;
                  }
                }
              }
              console.log(res.result.payBillItems);
              let columns = [
                { title: "合同编码", key: "purchaseBillNo" },
                { title: "供应商", key: "supplierName" },
                { title: "付款期限", key: "payTimeLimit" },
                { title: "单价", key: "price" },
                { title: "物料名称", key: "materialName" },
                { title: "规格", key: "spec" },
                { title: "采购数量", key: "purchaseQty" },
                { title: "合同金额", key: "contractAmount" },
                { title: "质检金额", key: "qtyCheckAmount" },
                { title: "已付金额", key: "hadPayAmount" },
                { title: "实收发票", key: "invoiceAmount" },
                { title: "未付金额", key: "unPayAmount" },
                {
                  title: "完成到货时间",
                  key: "completeStockTime",
                },
                { title: "退货冲抵", key: "amount" },
                { title: "代付冲抵", key: "payAmount" },
                { title: "本月已付", key: "pays" },
                { title: "账期", key: "accountDate" },
              ];
              let data = res.result.payBillItems;
              exportExcel(columns, data, "合同付款");
            });

          return;
          // for (let i = 0; i < array.length; i++) {
          //   const element = array[i];

          // }
        }
      });
    },
    getData(item) {
      this.paymentList = [];
      axios
        .post("/cloudApi/stockWater/contractPaymentList", {
          balancePurBillNo: item.purchaseBillNo,
        })
        .then((res) => {
          this.paymentList = res.data.data;
        });
    },
  },
  mounted() {
    //this.getList()
    this.selectTime(1.5);
    this.getContractPayTotal();
  },
};
</script>
<style>
.bar-2 .ivu-table-wrapper .ivu-table .ivu-table-tbody > :first-child {
  font-weight: bold;
}
.bar-2 .ivu-table-header tr > :first-child {
  color: #0077ff;
}
</style>
<style lang="less" scoped>
.bar-2 {
  overflow: hidden;
  margin-bottom: 20px;
  margin-top: 10px;
}

.bar-2 .active {
  border: 3px solid #3f92f9;
}
.bar-2 .ivu-table-cell {
  padding-left: 9px !important;
  padding-right: 9px !important;
}
.bar-2 > div {
  margin: 0 0.5%;
  float: left;
  width: 14%;
}
.container-wrap {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .bar-wrap {
    margin-bottom: 10px;
    background: #ffffff;
    border-radius: 3px;
    .bar-title {
      padding: 5px 10px;
      border-radius: 3px 3px 0 0;
      background: #dcdee2;
      font-weight: bold;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .bar {
      padding: 10px 20px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      .item {
        flex: 1;
        margin-right: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 5px;
        background-color: #ffffff;
        .left,
        .center,
        .right {
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
          text-align: center;
          border: 1px solid #e6e6e6;
          margin-right: -1px;
          &.active {
            border: 1px solid #3f92f9;
            margin-right: 0;
          }
          .number {
            margin: 5px 0;
            font-size: 16px;
            font-weight: bold;
            color: #3f92f9;
            white-space: nowrap;
          }
          .red {
            color: #db0020;
          }
        }
        .left {
          flex: 4;
          font-size: 16px;
          font-weight: bold;
        }
        .center {
          flex: 5;
          padding: 10px 0;
          cursor: pointer;
        }
        .right {
          flex: 5;
          cursor: pointer;
        }
      }
    }
  }
  .container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .table-filter {
      padding-bottom: 10px;
      height: 42px;
      line-height: 32px;
      overflow: hidden;
      .filter-item {
        margin-right: 10px;
        float: left;
        //&:last-child {
        //  margin-right: 0;
        //}
      }
    }
    .table-content {
      flex: 1;
      overflow: hidden;
      .row {
        margin-bottom: 5px;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        &:last-child {
          margin-bottom: 0;
        }
        .col {
          padding: 0 5px;
          flex: 2;
          overflow: hidden;
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          .value {
            flex: 1;
            overflow: hidden;
            word-break: break-all;
          }
        }
      }
      .list {
        height: 100%;
        overflow: auto;
        .item {
          margin-bottom: 10px;
          padding: 10px;
          border: 1px solid #d7d7d7;
          border-radius: 5px;
          background: #ffffff;
          display: flex;
          justify-content: space-between;
          align-items: center;
          &:last-child {
            margin-bottom: 0;
          }
          .item-left {
            padding: 0 10px;
            flex: 1;
            border-right: 1px solid #333333;
          }
          .item-right {
            display: flex;
            justify-content: space-between;
            align-items: center;
            .forms {
              padding: 0 10px;
              .col {
                align-items: center;
                margin-right: 10px;
                justify-content: flex-end;
                &:last-child {
                  margin-right: 0;
                }
                .text {
                  text-decoration: underline;
                  cursor: pointer;
                  white-space: nowrap;
                }
              }
            }
            .btn {
              display: flex;
              flex-direction: column;
            }
          }
        }
      }
    }
    .table-page {
      position: relative;
      padding-top: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 43px;
      overflow: hidden;
      .tabs {
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        .tab {
          padding: 5px 0;
          width: 100px;
          border-radius: 5px;
          text-align: center;
          background-color: #ffffff;
          cursor: pointer;
          &.active {
            color: #ffffff;
            background-color: #3f92f9e5;
          }
        }
      }
    }
  }
  .red {
    color: red;
  }
}
</style>
