<template>
  <div class="jg-page-wrap collectionPaymentNew-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="collectionPaymentNew-back" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <span style="margin-right:30px;color: #000;font-size: 14px;font-weight: 600;">客户：{{ $route.params.name!='undefined'?$route.params.name: '--' }}</span>
          <a-button id="collectionPayEdit-back-btn" type="link" @click="handleBack" class="button-default"> <a-icon type="rollback" /> 返回列表</a-button>
        </template>
        <template slot="extra" v-if="$hasPermissions('B_cPayment_printAndExport')">
          <div style="margin-top: 5px;">
            <PrintPanel ref="printBox" @handlePrint="handlePrint">
              <div style="padding:10px;" slot="extendCons">
                <a-checkbox v-model="remarksFlag" id="salesQuery-remarksFlag">打印备注</a-checkbox>
                <!-- <a-checkbox v-model="printTotalKs" :checked="printTotalKs" id="salesQuery-printTotalKs">打印总款数</a-checkbox> -->
                <!-- <a-checkbox v-model="printTotalNums" :checked="printTotalNums" id="salesQuery-printTotalNums">打印总数量</a-checkbox> -->
              </div>
            </PrintPanel>
            <a-divider type="vertical" />
            <a-button id="scollectionPayEdit-del-btn" class="button-default" type="link" @click="handleOk([])"><a-icon type="close" />清空单据</a-button>
            <a-divider type="vertical" />
            <a-button id="scollectionPayEdit-add-btn" type="link" @click="openModal=true"><a-icon type="plus" />选择单据</a-button>
          </div>
        </template>
      </a-page-header>
      <!-- 已选单据 -->
      <a-card size="small" :bordered="false" class="collectionPaymentNew-cont">
        <div class="table-operator">
          <div class="alert-message">
            共 <strong>{{ chooseLoadData.length }}</strong>条明细 ，
            金额合计<strong>{{ toThousands(totalAmount) }}</strong> ，
            余额合计<strong>{{ toThousands(totalBalance) }}</strong> ，
            本次结算金额合计<strong>{{ toThousands(currentTotalBalance) }}</strong>
          </div>
        </div>
        <!-- 列表 -->
        <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="'collectionPaymentNew-settleAmount-'+record.id"
              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="'collectionPaymentNew-del-'+record.id">移除</a-button>
          </template>
        </a-table>
      </a-card>
      <a-card size="small" :bordered="false" class="collectionPaymentNew-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="收付款信息">
            <a-form-model
              id="collectionPaymentNew-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="collectionPaymentNew-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="collectionPaymentNew-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="collectionPaymentNew-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="collectionPaymentNew-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="collectionPaymentNew-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="collectionPaymentNew-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="collectionPaymentNew-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'
import PrintPanel from '@/views/common/printPanel.vue'
export default {
  name: 'CollectionPaymentDetail',
  components: { STable, VSelect, chooseBillModal, Print, settleAccount, rangeDate, PrintPanel },
  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: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单据类型', dataIndex: 'bizTypeDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '关联单据创建时间', dataIndex: 'bizCreateDate', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditTime', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '总款数', dataIndex: 'bizTotalCategory', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总数量', dataIndex: 'bizTotalQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? 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: '12%', 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, // 结算方式sn
        settleClientName: '', // 客户名称
        settleAccountSn: undefined, // 结算账户sn
        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, // 结算账户是否开启
      printTotalKs: false, // 打印原创编码
      printTotalNums: false, // 打印全部名称
      remarksFlag: 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 = ''
      if (type == 'export') { //  导出
        url = settleUnitExport
      } else {
        url = settleUnitPrint
        // 打印
        // params.printTotalKs = params.printTotalKs ? 1 : 0
        // params.printTotalNums = params.printTotalNums ? 1 : 0
        params.remarksFlag = this.remarksFlag ? 1 : 0
      }
      // 打印或导出
      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) {
      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
          }
        }
        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) {
      if (selectedRows.length) {
        this.chooseLoadData = this.chooseLoadData.concat(selectedRows).sort((a, b) => {
          const at = new Date(a.auditTime).getTime()
          const bt = new Date(b.auditTime).getTime()
          return at - bt
        })
      } else {
        this.chooseLoadData = selectedRows
      }
      // 计算结算金额
      this.amountSettledChange()
    },
    // 返回列表
    handleBack () {
      this.$router.push({ name: `companyReceivablePayableNewList` })
    },
    // 关闭
    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 () {
      const vm = this
      vm.$nextTick(() => {
        vm.chooseLoadData = []
        vm.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" scoped>
  .collectionPaymentNew-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .collectionPaymentNew-cont{
      margin-top: 6px;
      .green{
        color: #19be6b;
      }
      .red{
        color: #ed1c24;
      }
    }

  }
</style>
