<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select filterable placeholder="物流" v-model="search.idLogisticsInfo" size="mini" @change="getList">
        <el-option
          v-for="item in logisticsList"
          :key="item.id"
          :value="item.id"
          :label="item.logisticName"></el-option>
      </el-select>
      <el-button size="mini" type="primary" @click="checkLogistic">核算</el-button>
      <el-select
        size="mini"
        filterable
        v-model="idAccount"
        placeholder="会计科目">
        <el-option
          v-for=" item in accountInfo"
          :key="item.id"
          :value="item.id"
          :label="item.accountCode+item.accountName">
          <span style="float: left">{{ item.accountName }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.accountCode }}</span>
        </el-option>
      </el-select>
      <el-date-picker
        size="mini"
        v-model="chargeDate"
        type="datetime"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择日期">
      </el-date-picker>
      <el-input size="mini" v-model="voucherCode" placeholder="凭证号" style="width: 180px;" class="filter-item"/>
      <el-button :size="sizeType" type="success" @click="multiCharge(1)">批量收款</el-button>
<!--      <el-button :size="sizeType" type="warning" @click="exportBtn">导出</el-button>-->
      <el-tag>您一共勾选了{{ multiSelected.length }}条 共计收款{{multiSelectedMoney}}元</el-tag>
      <el-card class="box-card" v-if="combinedQuery">
        <el-input :size="sizeType" v-model="search.clientName" placeholder="客户名称" style="width: 140px;"
                  class="filter-item"/>
        <el-input :size="sizeType" v-model="search.orderCode" placeholder="订单编号" style="width: 130px;"
                  class="filter-item"/>
        <el-input :size="sizeType" v-model="search.platformOrderID" placeholder="平台单号" style="width: 140px;"
                  class="filter-item"/>
        <el-select style="width: 110px" :size="sizeType" v-model="search.dataKind">
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>
        <el-select style="width: 100px" v-model="search.voidFlag" :size="sizeType">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="未作废" :value="0"></el-option>
        </el-select>
        <el-date-picker
          style="width: 225px"
          :size="sizeType"
          v-model="searchTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
        <el-input :size="sizeType" v-model="search.feedLogisticsName" placeholder="物流/配送" style="width: 130px;"
                  class="filter-item"/>
        <el-input :size="sizeType" v-model="search.feedLogisticsCode" placeholder="物流货号" style="width: 130px;"
                  class="filter-item"/>
        <el-input :size="sizeType" v-model="search.feedGuarantorName" placeholder="担保人" style="width: 130px;"
                  class="filter-item"/>
        <el-select style="width: 100px" placeholder="反馈类型" v-model="search.feedChargeKind" :size="sizeType">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="现金" :value="0"></el-option>
          <el-option label="物流代收" :value="1"></el-option>
          <el-option label="全额担保" :value="2"></el-option>
          <el-option label="预存" :value="3"></el-option>
        </el-select>
        <el-date-picker
          style="width: 225px"
          :size="sizeType"
          v-model="sendTime"
          type="daterange"
          range-separator="-"
          start-placeholder="发货开始日期"
          end-placeholder="发货结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
        <el-button :size="sizeType" type="primary" icon="el-icon-search" @click="searchData">
          搜索
        </el-button>
        <el-button :size="sizeType" type="danger" @click="resetForm">
          重置
        </el-button>
      </el-card>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="tableRefresh"/>
        </el-tooltip>
      </div>
    </div>
    <el-table
      :size="sizeType"
      :data="tableData"
      v-loading="listLoading"
      row-key="id"
      border
      style="margin-top: 10px"
      :cell-style="cellStyle"
      ref="orderTable"
      :row-style="customRowStyle"
      @row-click="handleClickTableRow"
      @selection-change="multiSelectionChange"
      :summary-method="getSummaries"
      :default-sort="{prop: 'date', order: 'descending'}"
      show-summary
      max-height="600"
      default-expand-all>
      <el-table-column
        type="selection"
        fixed="left"
        width="55"
        :reserve-selection="true">
      </el-table-column>
      <el-table-column
        label="序号"
        fixed
        align="center"
        width="50"
        type="index">
        <template slot-scope="scope">
          <span>{{ (listData.page - 1) * listData.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="orderCode"
        sortable
        label="订单编号"
        width="92">
        <template slot-scope="{row}">
          <a href="javascript:;" style="color: #20a0ff"
             @click.stop="(row.dataKind == 0||row.dataKind==1)?getOrderStep(row):''">{{ row.orderCode }}</a>
        </template>
      </el-table-column>
      <el-table-column
        prop="clientName"
        sortable
        show-overflow-tooltip
        label="客户名称"></el-table-column>
      <el-table-column
        prop="chargeMoney"
        sortable
        label="欠款"></el-table-column>
      <el-table-column
        prop="logisticsRecMoney"
        sortable
        label="代收金额"></el-table-column>
      <el-table-column label="订单收款">
        <template slot-scope="{row}">
          <el-input @click.native.stop size="mini" type="number" v-model="row.receivableMoney"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderPayKind"
        width="140"
        sortable
        show-overflow-tooltip
        label="付款方式"></el-table-column>
      <el-table-column
        prop="orderLogisticsCodes"
        show-overflow-tooltip
        sortable
        label="物流货号"></el-table-column> <el-table-column
      prop="orderLogisticsNames"
      show-overflow-tooltip
      sortable
      label="物流名称"></el-table-column>

      <el-table-column
        prop="orderSendDate"
        label="发货时间"
        sortable
        width="120">
        <template slot-scope="{row}">
          <span v-if="row.orderSendDate">{{ row.orderSendDate | getTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderCreateMan"
        sortable
        label="订单制单人"></el-table-column>
      <el-table-column
        prop="orderName"
        sortable
        show-overflow-tooltip
        label="印品名称">
        <template slot-scope="{row}">
          <a href="javascript:;" style="color: #20a0ff" @click="openDetail(row.idOrder)" class="ellipsis">
            {{ row.orderName }}</a>
        </template>
      </el-table-column>
      <el-table-column
        prop="billMoney"
        sortable
        width="100px"
        label="单据金额"></el-table-column>
      <el-table-column
        prop="orderCreateTime"
        label="订单制单日期"
        sortable
        width="120">
        <template slot-scope="{row}">
          <span v-if="row.orderCreateTime">{{ row.orderCreateTime | getTime }}</span>
        </template>
      </el-table-column>
    </el-table>
    <span v-show=" tableData.length>0" style="color: #606266">共 {{ tableData.length }} 条</span>
    <!--    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page" :limit.sync="listData.pageSize" @pagination="getList"/>-->
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
    <order-step ref="orderStep"></order-step>
    <el-drawer
      title="订单消息"
      :reverse="true"
      :visible.sync="memoDrawer"
      size="600px">
      <order-message ref="orderMessage"></order-message>
    </el-drawer>
    <el-dialog title="订单详情" :visible.sync="detailVisible" class="orderDetailDialog" width="1200px" top="10px">
      <order-detail ref="orderDetail"></order-detail>
    </el-dialog>

  </div>

</template>

<script>
import {
  getAccountInfoList,
  exportData
} from '@/api/orderCharge/orderCollection'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import orderMessage from '@/components/orderMessage/orderMessage'
import OrderDetail from '@/components/orderDetail/orderDetail'
import OrderStep from '@/components/orderStep/orderStep'
import {formatMoney} from "@/filters";
import {
  checkLogisticReceivable,
  getLogisticsInfoList,
  getOrderReceivableListNoPage, multiChargeDataAddLogistics
} from "@/api/orderCharge/logisticsCollection";
import {sum} from "@/utils";

var multiChargeData = {
  chargeDate: new Date(),
  payMan: '',
  idAccount: '',
  voucherCode: '',
  chargeKind: 0
}
export default {
  name: 'orderCollection',
  components: {
    OrderStep,
    OrderDetail,
    orderMessage, Cancledialog
  },
  data() {
    return {
      orderByString: '', // 排序
      combinedQuery: false,
      sizeType: 'mini',
      detailVisible: false,
      pluploadVisible: false,
      memoDrawer: false,
      orderStatus: '',
      voucherCode: '',
      search: {
        idLogisticsInfo: '',
      },
      idAccount: '',
      chargeDate: new Date(),
      searchTime: [],
      sendTime: [],
      drawer: false,
      stepList: [],
      timeString: '',

      stateOptions: [
        {
          label: '全部',
          value: -1
        },
        {
          label: '订单应收',
          value: 0
        },
        {
          label: '预收款应收',
          value: 1
        },
        {
          label: '其他应收',
          value: 2
        }
      ],
      tableData: [],
      collection: {},

      listLoading: false,
      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },
      voidVisible: false,
      sMemo: '',
      orderId: '',

      logisticsList: [],
      confirmdialog: false,
      accountInfo: [],
      multiSelected: [],
      multiSelectedMoney: 0
    }
  },
  mounted() {
    // this.getList()
    this.getAccountInfo()
    this.getLogisticsList()
  },
  watch: {
    multiSelected(value) {
      this.multiSelectedMoney = formatMoney(sum(value, 'receivableMoney'))
    }
  },
  methods: {
    getList() {
      var _that = this
      _that.listLoading = true
      _that.multiSelected = []
      _that.$refs.orderTable.clearSelection();
      // console.log(_that.search);
      // return
      var params = _that.search

      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      // var orderBy = _that.orderByString
      var data = {
        'params': JSON.stringify(params),
        // 'page': JSON.stringify(page),
        // 'orderBy': orderBy,
      }
      if (_that.listData.pageSize == 10) {
        _that.sizeType = 'medium'
      } else {
        _that.sizeType = 'mini'
      }
      // console.log(data);
      getOrderReceivableListNoPage(data).then(response => {
        // console.log(response)
        const data = response.data
        // //  组合表单数据
        data.forEach(item => {
          _that.$set(item, 'receivableMoney', item.logisticsRecMoney)
        })
        _that.tableData = data
        _that.listData.total = response.collection.orderCountSum
        _that.collection = response.collection
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },
    getSummaries(param) {
      var _that = this
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return
        }
        if (column.label == '单据金额') {
          // sums[index] = formatMoney(_that.collection.billMoneySum)
          sums[index] = formatMoney(sum(_that.tableData, 'billMoney'))
        } else if (column.label == '已收金额') {
          // sums[index] = formatMoney(_that.collection.payMoneySum)
          sums[index] = formatMoney(sum(_that.tableData, 'payMoney'))
        } else if (column.label == '欠款') {
          // sums[index] = formatMoney(_that.collection.chargeMoneySum)
          sums[index] = formatMoney(sum(_that.tableData, 'chargeMoney'))
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    cellStyle({row, column, rowIndex, columnIndex}) {
      if (column.label == '欠款') {
        return 'color: red;background:yellow;font-weight:700;font-size:18px'
      }
    },

    resetForm() {
      this.search = {
        clientName: '',
        financeCode: '',
        orderCode: '',
        voidFlag: 0,
        dataKind: -1,
        beginTime: '',
        endTime: '',
        platformOrderID: '',
        sendBeginTime: '',
        sendEndTime: '',
      }
      this.searchTime = []
      this.sendTime = []
    },

    // 核算
    checkLogistic() {
      const _that = this
      if (!_that.search.idLogisticsInfo){
        _that.$message.warning('请选择物流')
        return;
      }
      var data= {
        idLogisticsInfo: _that.search.idLogisticsInfo,
        logisticsName:_that.logisticsList.find(item => item.id == _that.search.idLogisticsInfo).logisticName,
      }
      console.log(data);
      // return;
      checkLogisticReceivable(data).then( res => {

      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 获取科目
    getAccountInfo() {
      var _that = this
      var data = {}
      getAccountInfoList(data).then(response => {
        console.log(response)
        _that.accountInfo = response.data
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 获取物流档案
    getLogisticsList() {
      var _that = this
      var data = {
        enable: 1
      }
      getLogisticsInfoList(data).then(response => {
        console.log(response)
        _that.logisticsList = response.data
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 搜索
    searchData() {
      this.listData.page = 1
      this.getList()
    },
    handleSelectionChange(val) {
      // console.log(val)
      this.choosedList = val
    },

    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.multiSelected = []
      this.$refs.orderTable.clearSelection()
      this.getList()
    },
    // 点击行内任何地方选中
    handleClickTableRow(row, event, column) {
      this.$refs.orderTable.toggleRowSelection(row)
    },
    openDetail(idOrder) {
      var _that = this
      _that.detailVisible = true
      _that.$nextTick(() => {
        _that.$refs.orderDetail.idOrder = idOrder
        _that.$refs.orderDetail.getInfo()
      })
    },

    // 订单消息
    openMessage(row) {
      var _that = this
      _that.memoDrawer = true
      _that.$nextTick(function () {
        // console.log(_that.$refs.orderMemo);
        _that.$refs.orderMessage.idOrder = row.idOrder
        _that.$refs.orderMessage.getList()
      })
    },
    // 获取脚印
    getOrderStep(row) {
      const _that = this
      _that.$refs.orderStep.idOrder = row.idOrder
      _that.$refs.orderStep.getOrderStep()
    },
    /**
     * 批量收款开始
     **/
    // 收款表格选中
    multiSelectionChange(val) {
      // console.log(val)
      var _that = this
      _that.multiSelected = val
    },
    // 确定批量收款
    multiCharge() {
      var _that = this
      if (!_that.idAccount) {
        _that.$message.warning('请选择会计科目')
        return;
      }
      for (let i = 0; i < _that.multiSelected.length; i++) {
        var item = _that.multiSelected[i]
        Object.assign(item, _that.multiChargeData)
        // console.log(item)
        if (item.receivableMoney == 0) {
          _that.multiSelected.splice(i, 1)
          i--
        }
        if (parseFloat(item.receivableMoney) > item.chargeMoney) {
          _that.$message.error('收款金额不得大于应收金额')
          return
        }
      }
      var rowData = []
      _that.multiSelected.forEach(row => {
        var rows = {
          idReceivable: row.id,
          idAccount: _that.idAccount,
          chargeKind: 1,
          receivableMoney: row.receivableMoney,
          chargeDate: _that.chargeDate,
          versionCode: row.versionCode,
          voucherCode:  _that.voucherCode
        }
        rowData.push(rows)
      })
      if (rowData.length <= 0) {
        _that.$message.warning('请输入金额')
        return;
      }
      var data = JSON.stringify(rowData)
      // console.log(rowData);
      // return
      multiChargeDataAddLogistics(data).then(response => {
        console.log(response)
        if (response.httpCode == 200) {
          _that.$message.success('收款成功')
          _that.tableRefresh()
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    /* 批量收款结束 */

    // 样式
    customRowStyle({row, rowIndex}) {
      if (row.orderVoidFlag == 1) {
        return {
          // color: '#F56C6C'
          background: '#f7b1b1'
        }
      }
    },

    // 导出
    exportBtn() {
      const _that = this
      var data = {
        code: 'OrderReceivalbe_Exporter',
        exportName: '订单应收导出',
        params: _that.search
      }
      exportData(data).then(res => {
        console.log(res);
        if (res.httpCode == 200) {
          _that.$message.success('导出成功，请前至系统管理-我的任务中进行查看和下载')
        }
      })
    }
  }
}
</script>
<style>
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
.el-drawer__body {
  overflow: auto;
}

.stepList .el-card__body {
  padding: 10px;
}

:focus {
  outline: 0;
}
</style>

<style lang="scss" scoped>
.filter-container {
  margin-bottom: 15px;

  .filter-item {
    padding: 5px 0;
  }
}

::v-deep input::-webkit-outer-spin-button,::v-deep input::-webkit-inner-spin-button{
  -webkit-appearance: none !important;
}
::v-deep input[type = 'number']{
  -moz-appearance: textfield !important;
}
</style>
