<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!='undefined'?$route.params.name: '--' }}</p>
        </template>
        <template slot="extra" v-if="$hasPermissions('B_cPayment_printAndExport')">
          <Print :disabled="chooseLoadData.length==0||totalBalance==0" @handlePrint="handlePrint"></Print>
        </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>{{ toThousands(totalAmount) }}</strong> ，
                余额合计<strong>{{ toThousands(totalBalance) }}</strong> ，
                本次结算金额合计<strong>{{ toThousands(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"
                  :max="record.unsettleAmount<0 ? 0 : record.unsettleAmount"
                  @change="amountSettledChange"
                  size="small"
                  placeholder="请输入"
                  style="width: 100%;" />
              </template>
              <!-- 操作 -->
              <template slot="action" slot-scope="text, record">
                <a-button size="small" type="link" 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="form.amountSettled"
                      @change="amountSettledTotalChange"
                      :precision="2"
                      placeholder=""
                      :max="maxAmountSettled"
                      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="form.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">
                    <v-select
                      code="SETTLE_STYLE"
                      id="collectionPayment-settleStyleSn"
                      v-model="form.settleStyleSn"
                      @change="settleStyleChange"
                      allowClear
                      placeholder="请选择结算方式"
                    ></v-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="12">
                  <a-form-model-item v-if="enableFundAccount" label="结算账户" prop="settleAccountSn">
                    <settleAccount
                      id="collectionPayment-settleAccountSn"
                      v-model="form.settleAccountSn"
                      :settleStyleSn="form.settleStyleSn"
                      @change="settleAccountChange"
                      placeholder="请选择结算账户">
                    </settleAccount>
                  </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
      ref="chooseBillModal"
      :openModal="openModal"
      :nowChoose="chooseLoadData"
      :settleClientType="$route.params.type"
      :settleClientSn="$route.params.sn"
      @ok="handleOk"
      @close="handleClose" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { mapActions } from 'vuex'
import debounce from 'lodash/debounce'
import { STable, VSelect } from '@/components'
import chooseBillModal from './chooseBillModal.vue'
import { settleUnitSave, settleUnitPrint, settleUnitExport, settleInfoAllList } from '@/api/settle'
import Print from '@/views/common/print.vue'
import settleAccount from '@/views/common/settleAccount'
import rangeDate from '@/views/common/rangeDate.vue'
import { hdPrint } from '@/libs/JGPrint'
export default {
  name: 'CollectionPaymentDetail',
  components: { STable, VSelect, chooseBillModal, Print, settleAccount, rangeDate },
  mixins: [commonMixin],
  data () {
    this.amountSettledChange = debounce(this.amountSettledChange, 800)
    this.amountSettledTotalChange = debounce(this.amountSettledTotalChange, 800)
    const _this = this
    return {
      disabled: false,
      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: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '关联单据创建时间', dataIndex: 'bizCreateDate', width: '20%', 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: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '余额', dataIndex: 'unsettleAmount', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } },
        { title: '本次结算金额', scopedSlots: { customRender: 'settleAmount' }, width: '15%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      chooseLoadData: [],
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      form: {
        amountSettled: 0,
        discountAmount: 0, //  折让金额
        settleStyleSn: undefined,
        settleClientName: '',
        settleAccountSn: undefined,
        settleAccountName: undefined,
        remark: ''
      },
      rules: {
        amountSettled: [{ required: true, message: '请输入本次结算金额，系统将自动分配到已选单据上', trigger: 'change' }],
        discountAmount: [{ required: true, message: '请输入折让金额', trigger: 'blur' }],
        settleStyleSn: [{ required: true, message: '请选择结算方式', trigger: 'change' }],
        settleAccountSn: [{ required: true, message: '请选择结算账户', trigger: 'change' }]
      },
      openModal: false, //  弹框
      isPositive: true, // 是否是正值
      isChangeAs: false,
      maxAmountSettled: 0,
      enableFundAccount: false
    }
  },
  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
    },
    // 实结算金额
    actualSettlementAmount () {
      const val = (this.form.amountSettled * 1000 - this.form.discountAmount * 1000) / 1000
      return val
    }
  },
  methods: {
    ...mapActions(['GetSettleAccountState']),
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      const params = _this.getParams()
      _this.spinning = true
      let url = settleUnitPrint
      if (type == 'export') { //  导出
        url = settleUnitExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '单位应收应付', function () {
        _this.spinning = false
      })
    },
    // 选择结算方式
    settleStyleChange (v, name) {
      this.form.settleStyleName = name.dispName
      if (this.form.settleAccountSn) {
        this.form.settleAccountSn = undefined
      }
    },
    settleAccountChange (v, name) {
      this.form.settleAccountName = name
    },
    // 应结算金额
    amountSettledChange () {
      console.log(this.isChangeAs)
      if (!this.isChangeAs) {
        let val = 0
        this.chooseLoadData.map(item => {
          val += (Number(item.settleAmount) * 1000)
        })
        val = val / 1000
        this.isPositive = val > 0
        this.form.amountSettled = Math.abs(val)
        this.maxAmountSettled = Math.abs(val)
      }
    },
    // 修改本次结算金额，自动分配
    amountSettledTotalChange (v) {
      console.log(this.isChangeAs, v, this.totalBalance, this.isPositive)
      if (v <= Math.abs(this.totalBalance)) {
        this.isChangeAs = true
        const sa = v
        const list = this.chooseLoadData
        // 恢复初始值
        list.map((item, index) => {
          item.settleAmount = item.unsettleAmount
        })
        this.maxAmountSettled = Math.abs(this.totalBalance)
        // 开始计算
        let temp = 0
        let ti = 0
        for (let i = 0; i < list.length; i++) {
          temp = temp + list[i].settleAmount * (this.isPositive ? 1 : -1)
          if (temp >= sa) {
            ti = i
            break
          }
        }
        console.log(ti, temp, sa)
        list[ti].settleAmount = (list[ti].settleAmount - (temp - sa) * (this.isPositive ? 1 : -1)).toFixed(2)
        // ti 之后的都改成0
        for (let i = ti + 1; i < list.length; i++) {
          list[i].settleAmount = 0
        }
        list.splice()
        this.isChangeAs = false
      }
    },
    // 选择单据
    handleChoose () {
      this.openModal = true
    },
    //  移除
    handleDel (record) {
      const ind = this.chooseLoadData.findIndex(item => item.id == record.id)
      this.chooseLoadData.splice(ind, 1)
      this.amountSettledChange()
    },
    getParams () {
      const _this = this
      const form = _this.form
      form.settleClientName = _this.$route.params.name
      form.settleClientSn = _this.$route.params.sn || undefined
      form.settleClientType = _this.chooseLoadData[0].settleClientType
      form.settleType = _this.isPositive ? 'R' : 'P'
      form.settleAmount = _this.form.amountSettled
      form.realSettleAmount = _this.actualSettlementAmount
      form.detailList = []
      _this.chooseLoadData.map(item => {
        form.detailList.push({
          bizSn: item.bizSn,
          settleAmount: item.settleAmount,
          prFlag: item.prFlag
        })
      })
      return form
    },
    // 提交
    handleSubmit () {
      const _this = this
      if (_this.chooseLoadData.length == 0) {
        _this.$message.warning('请选择单据后再提交信息')
        return
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.spinning = true
          const form = this.getParams()
          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.sort((a, b) => {
        const at = new Date(a.auditTime).getTime()
        const bt = new Date(b.auditTime).getTime()
        return at - bt
      })
      // this.chooseLoadData = selectedRows.reverse()
      this.amountSettledChange()
    },
    // 返回列表
    handleBack () {
      this.$router.push({ path: `/financialManagement/companyReceivablePayable/list` })
    },
    // 关闭
    handleClose () {
      this.openModal = false
    },
    // 默认获取所有单据
    getsettleInfoAllList () {
      this.loading = true
      this.disabled = true
      settleInfoAllList({ settleClientSn: this.$route.params.sn, settleClientType: this.$route.params.type, notEqZero: 1 }).then(res => {
        res.data.map(item => {
          item.settleAmount = item.unsettleAmount
        })
        this.chooseLoadData = res.data || []
        this.loading = false
        this.disabled = false
        this.amountSettledChange()
      })
    },
    pageInit () {
      this.chooseLoadData = []
      this.getsettleInfoAllList()
    },
    // 重置
    resetSearchForm () {
      this.getsettleInfoAllList()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
    // 结算账户状态查询
    if (this.$hasPermissions('M_fundAccountList') && this.$hasPermissions('B_fundAccountEnable')) {
      this.GetSettleAccountState().then(res => {
        if (res.status == 200) {
          this.enableFundAccount = res.data.functionEnableFlag == 1
        }
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

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