<template>
  <div class="app-container">
    <div class="filter-container">
    <el-form inline>
      <el-form-item label="客户名称">
        <el-input v-model="baseInfo.clientName" class="input-with-select" disabled>
        <el-button slot="append" @click="handleChoose">选择客户</el-button></el-input>
      </el-form-item>
      <el-form-item label="余额">
        <el-input :value="baseInfo.balanceMoney" disabled></el-input>
      </el-form-item>
      <el-button type="primary" @click="distribute">金额分配</el-button>
      <el-button @click="multiChargeSure">确定冲抵</el-button>
      <el-tooltip effect="dark" content="刷新" placement="top">
        <el-button size="mini" circle icon="el-icon-refresh" @click="getList"/>
      </el-tooltip>
    </el-form>
    </div>
    <el-table
      :data="tableData"
      ref="chargeList"
      border
      size="mini"
      @selection-change="multiSelectionChange"
      show-summary
      :summary-method="getSummaries">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="订单编号" prop="orderCode"></el-table-column>
      <el-table-column label="订单名称" prop="orderName"></el-table-column>
      <el-table-column label="客户名称" prop="clientName"></el-table-column>
      <!--              <el-table-column label="发货单号" prop="orderName"></el-table-column>-->
      <!--              <el-table-column label="物流货号" prop="orderName"></el-table-column>-->
      <el-table-column label="付款方式" width="430">
        <template slot-scope="{row}">
          <template v-if="row.orderPayKind">
          <template v-for="payKind in (row.orderPayKind.split('+'))">
              <template v-if="payKind.split(':')[1] == '担保人'">
                <span>{{ payKind.split(':')[1] }} ---- {{payKind.split(':')[2]}}---- {{payKind.split(':')[3]}};</span>
              </template>
              <template v-else>
                <span>{{ payKind.split(':')[1] }} ---- {{payKind.split(':')[2]}};</span>
              </template>
          </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="应收" prop="chargeMoney"></el-table-column>
      <el-table-column label="当前收款" prop="payMoney">
        <template slot-scope="{row}">
          <el-input type="number" v-model="row.receivableMoney" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="折扣" prop="agioMoney">
        <template slot-scope="{row}">
          <el-input type="number" v-model="row.agioMoney" size="mini"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <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>
    <el-dialog title="选择客户" :close-on-click-modal="false" :visible.sync="clientDialog" width="800px">
      <client-money :is-choose="true" @chooseClient = 'chooseClient'></client-money>
    </el-dialog>
  </div>

</template>

<script>
import {
  getOrderStepList
} from '@/api/order/orderList.js'
import { getOrderReceivableList, multiChargeDataAdd, getAccountInfoList } from '@/api/orderCharge/orderCollection'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import orderMessage from '@/components/orderMessage/orderMessage'
import OrderDetail from '@/components/orderDetail/orderDetail'
import ClientMoney from '@/views/orderCharge/clientMoney'
import {formatMoney} from "@/filters";
var multiChargeData = {
  chargeDate: new Date(),
  payMan: '',
  idAccount: '',
  voucherCode: '',
  chargeKind: 0
}
export default {
  name: 'OrderCollection',
  components: {
    ClientMoney,
    OrderDetail,
    orderMessage, Cancledialog
  },
  data() {
    return {
      sizeType: 'mini',
      detailVisible: false,
      pluploadVisible: false,
      memoDrawer: false,
      orderStatus: '',
      baseInfo: {
        clientName: '',
        balanceMoney: '',
        idClient: ''
      },
      clientDialog: false,
      search: {
        clientName: '',
        financeCode: '',
        orderCode: '',
        dataKind: -1,
        beginTime: '',
        endTime: ''
      },
      searchTime: [],
      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: '',


      // 批量收款
      choosedList: [], // 选中列表
      collectionsDialog: false,
      multiChargeData: Object.assign({}, multiChargeData),
      amountMoney: 0, // 收款金额
      accountInfo: [], // 科目
      multiSelected: [], // 选中

      // 单行收款
      collectionDialog: false,
      collectionData: {},

      confirmdialog: false
    }
  },
  methods: {
    // 选择客户
    handleChoose() {
      var _that = this
      _that.clientDialog = true
    },
    chooseClient(val) {
      console.log(val)
      var _that = this
      _that.clientDialog = false
      _that.baseInfo.clientName = val.clientName
      _that.baseInfo.balanceMoney = val.balanceMoney
      _that.baseInfo.idClient = val.id
      this.getList()
    },
    getList() {
      var _that = this
      if(!_that.baseInfo.idClient){
        _that.$message.warning('请选择客户名称')
        return
      }
      var params = {
        idClient: _that.baseInfo.idClient
      }
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      if (_that.listData.pageSize == 10) {
        _that.sizeType = 'medium'
      } else {
        _that.sizeType = 'mini'
      }
      // console.log(data);
      getOrderReceivableList(data).then(response => {
        console.log(response)
        const data = response.data
        var payKinds = []
        var payKind = []

        data.forEach((item) => {
          item['agioMoney'] = 0
          item['receivableMoney'] = 0
          item['idReceivable'] = item.id
        })
        // //  组合表单数据
        _that.tableData = data
        _that.collection = response.collection
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
        // _that.$nextTick(() => {
        //   _that.tableData.forEach((item) => {
        //     _that.$refs.chargeList.toggleRowSelection(item, true)
        //   })
        // })
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },

    getSummaries(param) {
      var _that = this
      const { columns, data } = param
      var agioMoneySum = 0 , receivableMoneySum = 0
      data.forEach(item => {
        agioMoneySum = parseInt(agioMoneySum) + parseInt(item.agioMoney)
        receivableMoneySum = parseInt(receivableMoneySum) + parseInt(item.receivableMoney)
      })
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return
        }
        if (column.label == '应收') {
          if(_that.collection.chargeMoneySum){
            sums[index] = formatMoney(_that.collection.chargeMoneySum)
          }
        }else if(column.label == '当前收款') {
          sums[index] = formatMoney(receivableMoneySum)
        }else if(column.label == '折扣') {
          sums[index] = formatMoney(agioMoneySum)
        }
      })
      return sums
    },
    // 点击行内任何地方选中
    handleClickTableRow(row, event, column) {
      this.$refs.orderTable.toggleRowSelection(row)
    },
    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getList()
    },
    // 金额分配
    distribute() {
      var _that = this
      var tempMoney = _that.baseInfo.balanceMoney
      if (_that.baseInfo.balanceMoney > 0) {
        _that.multiSelected.forEach((item) => {
          // console.log(item)
          if (item.agioMoney > 0) {
            if (item.agioMoney > item.chargeMoney) {
              _that.$message.error('折扣不能大于应收')
              return
            } else {
              if ((item.chargeMoney - item.agioMoney) <= tempMoney) {
                // console.log('item.receivableMoney', item.receivableMoney)
                item.receivableMoney = item.chargeMoney - item.agioMoney
                tempMoney = tempMoney - item.receivableMoney
                // console.log('tempMoney', tempMoney)
              } else if ((item.chargeMoney - item.agioMoney) > tempMoney) {
                item.receivableMoney = tempMoney
                tempMoney = 0
              }
            }
          } else {
            if (item.chargeMoney <= tempMoney) {
              item.receivableMoney = item.chargeMoney
              tempMoney = tempMoney - item.chargeMoney
            } else if (item.chargeMoney > tempMoney) {
              item.receivableMoney = tempMoney
              tempMoney = 0
            }
          }
        })
      }
    },
    // 收款表格选中
    multiSelectionChange(val) {
      // console.log(val)
      var _that = this
      _that.multiSelected = val
    },
    // 确定批量收款
    multiChargeSure() {
      var _that = this
      var chargeMoneySum = 0
      for (let i = 0; i < _that.multiSelected.length; i++) {
        var item = _that.multiSelected[i]
        console.log(item);
        // item = Object.assign(item, _that.multiChargeData)
        _that.$set(item, 'chargeDate', new Date())
        _that.$set(item, 'payMan', '')
        _that.$set(item, 'idAccount', '')
        _that.$set(item, 'voucherCode', '')
        _that.$set(item, 'chargeKind', '')
        if (item.receivableMoney == 0 && item.agioMoney == 0) {
          _that.multiSelected.splice(i, 1)
        }
        chargeMoneySum = parseFloat(chargeMoneySum)+parseFloat(item.receivableMoney)
        if (parseFloat(item.receivableMoney) + parseFloat(item.agioMoney) > item.chargeMoney) {
          _that.$message.error('收款金额与折扣之和不得大于应收金额')
          return
        }
      }
      // console.log('chargeMoneySum',chargeMoneySum);
      if(chargeMoneySum > _that.baseInfo.balanceMoney ){
        _that.$message.warning('冲抵金额不能高于余额')
        return;
      }
      // console.log(_that.multiSelected);
      if( _that.multiSelected.length <= 0){
        _that.$message.warning('请选择有效订单')
        return;
      }
      var rowData = []
      _that.multiSelected.forEach(row => {
        // console.log('row',row);
        var rows = {
          idReceivable: row.idReceivable,
          idAccount: row.idAccount,
          payMan: row.payMan,
          orderCode: row.orderCode,
          chargeKind: 2,
          idOrder: row.idOrder,
          receivableMoney: row.receivableMoney,
          agioMoney: row.agioMoney,
          versionCode: row.versionCode
        }
        rowData.push(rows)
      })
      var data = JSON.stringify(rowData)
      // console.log(rowData);
      // return
      multiChargeDataAdd(data).then(response => {
        console.log(response)
        if (response.httpCode == 200) {
          _that.$message.success('收款成功')
          var data = response.data
          var totalMoney = 0
          data.forEach(item => {
            totalMoney += item.receivableMoney
          })
          // console.log(totalMoney);
          _that.baseInfo.balanceMoney = _that.baseInfo.balanceMoney - totalMoney
          _that.getList()
        } else {
          _that.$message.error(response.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
  }
}
</script>
<style>
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
.el-drawer__body {
  overflow: auto;
}
.stepList .el-card__body{
  padding: 10px;
}
:focus{
  outline:0;
}
</style>

<style scoped>
.filter-container {
  margin-bottom: 15px;
}
</style>
