<template>
  <div class="collectionPayment-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="collectionPayment-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="collectionPayment-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <p style=" display: inline-block;margin: 0 0 0 60px;color: #000;font-size: 16px;font-weight: 600;">客户：{{ $route.params.name || '--' }}</p>
        </template>
      </a-page-header>
      <!-- 已选单据 -->
      <a-card size="small" :bordered="false" class="collectionPayment-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1">
            <template slot="header">
              已选单据
              <a-button type="primary" size="small" class="button-error" id="collectionPayment-circle-btn" @click.stop="handleChoose">选择单据</a-button>
            </template>
            <!-- 总计 -->
            <a-alert type="info" style="margin-bottom:10px">
              <div slot="message">
                共 <strong>{{ chooseLoadData.length }}</strong>条明细 ，
                金额合计￥<strong>{{ totalAmount }}</strong> ，
                余额合计￥<strong>{{ totalBalance }}</strong> ，
                本次结算金额合计￥<strong>{{ currentTotalBalance }}</strong>
              </div>
            </a-alert>
            <!-- 列表 -->
            <a-table
              class="sTable"
              ref="chooseTable"
              size="small"
              :rowKey="(record) => record.id"
              :columns="chooseColumns"
              :dataSource="chooseLoadData"
              :scroll="{ y: 300 }"
              :loading="loading"
              :locale="{emptyText: '请先选择单据'}"
              :pagination="false"
              bordered>
              <!-- 序号 -->
              <template slot="no" slot-scope="text, record, index">
                {{ index+1 }}
              </template>
              <!-- 本次结算金额 -->
              <template slot="settleAmount" slot-scope="text, record">
                <a-input-number
                  id="collectionPayment-settleAmount"
                  v-model="record.settleAmount"
                  :precision="2"
                  :min="record.unsettleAmount<0 ? record.unsettleAmount : 0.01"
                  :max="record.unsettleAmount<0 ? -0.01 : record.unsettleAmount"
                  size="small"
                  placeholder="请输入"
                  style="width: 100%;" />
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="primary" class="button-error" @click="handleDel(record)" id="collectionPayment-del-btn">移除</a-button>
              </template>
            </a-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card size="small" :bordered="false" class="collectionPayment-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="收付款信息">
            <a-form-model
              id="collectionPayment-form"
              ref="ruleForm"
              :model="form"
              :rules="rules"
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol">
              <a-row :gutter="20">
                <a-col span="12">
                  <a-form-model-item prop="amountSettled">
                    <template slot="label">
                      应结算金额（<span :class="isPositive ? 'green':'red'">{{ isPositive ? '收款' : '付款' }}</span>）
                    </template>
                    <a-input-number
                      id="collectionPayment-amountSettled"
                      v-model="amountSettled"
                      disabled
                      :precision="2"
                      placeholder=""
                      style="width: 100%;" />
                  </a-form-model-item>
                </a-col>
                <a-col span="12">
                  <a-form-model-item label="折让金额" prop="discountAmount">
                    <a-input-number
                      id="collectionPayment-discountAmount"
                      v-model="form.discountAmount"
                      :precision="2"
                      :min="0"
                      :max="amountSettled"
                      placeholder="请输入"
                      style="width: 100%;"
                      allowClear />
                  </a-form-model-item>
                </a-col>
                <a-col span="12">
                  <a-form-model-item prop="actualSettlementAmount">
                    <template slot="label">
                      实结算金额（<span :class="isPositive ? 'green':'red'">{{ isPositive ? '收款' : '付款' }}</span>）
                    </template>
                    <a-input-number
                      id="collectionPayment-actualSettlementAmount"
                      v-model="actualSettlementAmount"
                      disabled
                      :precision="2"
                      placeholder=""
                      style="width: 100%;" />
                  </a-form-model-item>
                </a-col>
                <a-col span="12">
                  <a-form-model-item label="结算方式" prop="settleStyleSn">
                    <a-select id="collectionPayment-settleStyleSn" v-model="form.settleStyleSn" placeholder="请选择结算方式" allowClear>
                      <a-select-option v-for="item in settleStyleList" :value="item.settleStyleSn" :key="item.settleStyleSn">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="24">
                  <a-form-model-item label="备注" prop="remark" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
                    <a-textarea id="collectionPayment-remark" :maxLength="100" v-model="form.remark" placeholder="请输入备注(最多100个字符)" allowClear />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        id="collectionPayment-submit"
        size="large"
        :disabled="spinning"
        class="button-primary"
        @click="handleSubmit"
        style="padding: 0 60px;">提交</a-button>
    </div>
    <choose-bill-modal :openModal="openModal" :nowChoose="chooseLoadData" :settleClientSn="$route.params.sn" @ok="handleOk" @close="handleClose" />
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import chooseBillModal from './chooseBillModal.vue'
import { settleStyleQueryAll } from '@/api/settleStyle'
import { settleUnitSave } from '@/api/settle'
export default {
  components: { STable, VSelect, chooseBillModal },
  data () {
    return {
      spinning: false,
      loading: false, //  表格加载中
      chooseQueryParam: {
        productCode: '',
        productName: ''
      },
      // 表头
      chooseColumns: [
        { title: '序号', scopedSlots: { customRender: 'no' }, width: '5%', align: 'center' },
        { title: '单据号', dataIndex: 'bizNo', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditTime', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '金额', dataIndex: 'totalAmount', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '余额', dataIndex: 'unsettleAmount', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本次结算金额', scopedSlots: { customRender: 'settleAmount' }, width: '15%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      chooseLoadData: [],
      settleStyleList: [], //  结算方式
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      form: {
        discountAmount: 0, //  折让金额
        settleStyleSn: undefined,
        remark: ''
      },
      rules: {
        discountAmount: [{ required: true, message: '请输入折让金额', trigger: 'blur' }],
        settleStyleSn: [{ required: true, message: '请选择结算方式', trigger: 'change' }]
      },
      openModal: false, //  弹框
      isPositive: true // 是否是正值
    }
  },
  computed: {
    // 本次结算金额合计
    currentTotalBalance () {
      let val = 0
      this.chooseLoadData.map(item => {
        val += (Number(item.settleAmount) * 1000)
      })
      return val / 1000
    },
    // 金额合计
    totalAmount () {
      let val = 0
      this.chooseLoadData.map(item => {
        val += (Number(item.totalAmount) * 1000)
      })
      return val / 1000
    },
    // 余额合计
    totalBalance () {
      let val = 0
      this.chooseLoadData.map(item => {
        val += (Number(item.unsettleAmount) * 1000)
      })
      return val / 1000
    },
    // 应结算金额
    amountSettled () {
      let val = 0
      this.chooseLoadData.map(item => {
        val += (Number(item.settleAmount) * 1000)
      })
      val = val / 1000
      if (val < 0) {
        this.isPositive = false
      } else {
        this.isPositive = true
      }
      return Math.abs(val)
    },
    // 实结算金额
    actualSettlementAmount () {
      const val = (this.amountSettled * 1000 - this.form.discountAmount * 1000) / 1000
      return val
    }
  },
  methods: {
    // 选择单据
    handleChoose () {
      this.openModal = true
    },
    //  移除
    handleDel (record) {
      const ind = this.chooseLoadData.findIndex(item => item.id == record.id)
      this.chooseLoadData.splice(ind, 1)
    },
    // 提交
    handleSubmit () {
      const _this = this
      if (_this.chooseLoadData.length == 0) {
        _this.$message.warning('请选择单据后再提交信息')
        return
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = _this.form
          form.settleClientSn = _this.$route.params.sn || undefined
          form.settleClientType = _this.chooseLoadData[0].settleClientType
          form.settleType = _this.isPositive ? 'R' : 'P'
          form.settleAmount = _this.amountSettled
          form.realSettleAmount = _this.actualSettlementAmount
          form.detailList = []
          _this.chooseLoadData.map(item => {
            form.detailList.push({
              bizSn: item.bizSn,
              settleAmount: item.settleAmount,
              prFlag: item.prFlag
            })
          })
          _this.spinning = true
          settleUnitSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.handleBack()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleOk (selectedRows) {
      this.chooseLoadData = selectedRows
    },
    //  结算方式
    getSettleStyle () {
      settleStyleQueryAll({}).then(res => {
        if (res.status == 200) {
          this.settleStyleList = res.data
        } else {
          this.settleStyleList = []
        }
      })
    },
    // 返回列表
    handleBack () {
      this.$router.push({ path: `/financialManagement/companyReceivablePayable/list` })
    },
    // 关闭
    handleClose () {
      this.openModal = false
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.getSettleStyle()
      this.chooseLoadData = []
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.getSettleStyle()
      this.chooseLoadData = []
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .collectionPayment-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    margin-bottom: 10px;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    .collectionPayment-cont{
      margin-top: 10px;
      .green{
        color: #19be6b;
      }
      .red{
        color: #ed1c24;
      }
    }
  }
</style>
