<template>
  <a-modal
    :title="title"
    :width="modelStyle.width"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    :maskClosable="false"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="8">
                <a-form-item label="订单编号">
                  <a-input placeholder="请输入订单编号" v-model="queryParam.orderNumber"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item label="姓名">
                  <a-input placeholder="请输入姓名" v-model="queryParam.userName"></a-input>
                </a-form-item>
              </a-col>
              <template v-if="toggleSearchStatus">
                <a-col :md="6" :sm="8">
                  <a-form-item label="身份证号">
                    <a-input placeholder="请输入身份证号" v-model="queryParam.idcardNumber"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :md="8" :sm="8">
                  <a-form-item label="导入时间">
                    <a-range-picker
                      style="width: 100%"
                      v-model="queryParam.createTimeRange"
                      format="YYYY-MM-DD"
                      :placeholder="['开始时间', '结束时间']"
                      @change="onDateChange"
                      @ok="onDateOk"
                      :allowClear="allowClear"
                    />
                  </a-form-item>
                </a-col>
              </template>
              <a-col :md="6" :sm="8">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                  <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? '收起' : '展开' }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 查询区域-END -->

        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <!--<a-button @click="handlePayment" type="primary" icon="plus">付款</a-button>-->
        </div>

        <!-- table区域-begin -->
        <div>
          <!--<div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
            <!--<i class="anticon anticon-info-circle ant-alert-icon"></i> 选中金额:<a style="font-weight: 600">{{selectedPrice}}</a>-->
            <!--<a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
          <!--</div>-->

          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :loading="loading"
            :pagination="ipagination"
            @change="handleTableChange">
            <span slot="action1" slot-scope="text, record">
              <template v-if="record.status == 3">
                {{text}}&nbsp;&nbsp;<a @click="handleFailReason(record)">失败原因</a>&nbsp;&nbsp;<a @click="handleBackPay(record)">补发</a>
              </template>
              <template v-else>
                {{text}}
              </template>
            </span>

          </a-table>
        </div>
      </a-card>
    </a-spin>
    <hw-payment-back-modal ref="modalPayBackForm" @ok="modalFormOk"></hw-payment-back-modal>
  </a-modal>
</template>

<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { httpAction, getAction,putAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import { filterObj } from '@/utils/util'
  import qs from 'qs';
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import HwPaymentBackModal from './HwPaymentBackModal'
  const hanpayment = (params) => putAction('/hwpayment/hwPaymentDetail/handPayment', params)
  const hanbackpay = (params) => putAction('/hwpayment/hwPaymentDetail/handBackpay', params)

  export default {
    name: 'HwPaymentModal',
    mixins: [JeecgListMixin],
    components: {
      JDate,
      HwPaymentBackModal
    },
    data() {
      return {
        description: 'hw_payment_detail管理页面',
        allowClear:false,
        bodyStyle: {
          padding: '0',
          height: (window.innerHeight * 0.66) + 'px',
          'overflow-y': 'auto'
        },
        modelStyle: {
          width: '76%',
          style: { top: '20px' },
          fullScreen: false
        },
        // 查询条件
        queryParam: {
          createTimeRange: [],
        },
        // 表头
        columns: [
          {
            title: '订单编号',
            align: 'center',
            dataIndex: 'orderNumber'
          },
          {
            title: '姓名',
            align: 'center',
            dataIndex: 'userName'
          },
          {
            title: '银行卡号',
            align: 'center',
            dataIndex: 'cardNumber'
          },
          {
            title: '开户行',
            align: 'center',
            dataIndex: 'eacbnk',
            customRender: function(value, record) {
              if(value){
                return value;
              }
              return '招商银行';
            }
          },
          {
            title: '开户地',
            align: 'center',
            dataIndex: 'rcveaa',
            customRender: function(value, record) {
              if(value){
                return value;
              }
              return '-';
            }
          },
          {
            title: '实发金额',
            align: 'center',
            dataIndex: 'netPayment'
          },
          {
            title: '付款状态',
            align: 'center',
            dataIndex: 'status_dictText',
            scopedSlots: { customRender: 'action1' }
          },
          {
            title: '返回结果时间',
            align: 'center',
            dataIndex: 'paymentResultTime'
          }
        ],
        title: '操作',
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },

        confirmLoading: false,
        url: {
          list: '/hwpayment/hwPaymentDetail/list',
          delete: '/hwpayment/hwPaymentDetail/delete',
          deleteBatch: '/hwpayment/hwPaymentDetail/deleteBatch',
          exportXlsUrl: '/hwpayment/hwPaymentDetail/exportXls',
          importExcelUrl: 'hwpayment/hwPaymentDetail/importExcel',
        },
        dictOptions: {},
        selectedPrice:0,
        paymentId: 0,
      }
    },
    created() {
    },
    computed: {
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
      }
    },
    methods: {
      getQueryParams() {
        console.log(this.queryParam.createTimeRange)
        var param = Object.assign({}, this.queryParam, this.isorter)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        param.paymentId = this.paymentId;
        delete param.createTimeRange // 时间参数不传递后台
        return filterObj(param)
      },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams()//查询条件
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total;
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      initDictConfig() {
      },
      add() {
        this.edit({})
      },
      edit(record) {
        this.model = Object.assign({}, record)
        this.paymentId = record.id
        this.visible = true
        this.loadData(1)
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        this.$emit('ok')
        this.visible = false
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'paymentCode', 'payment', 'serviceFee', 'totalPayment', 'createTime', 'createBy', 'updateTime', 'updateBy', 'sysOrgCode', 'status', 'delFlag'))
      },
      onDateChange: function(value, dateString) {
        console.log(dateString[0], dateString[1])
        this.queryParam.createTime_begin = dateString[0] + ' 00:00:00'
        this.queryParam.createTime_end = dateString[1] + ' 23:59:59'
      },
      onDateOk(value) {
        console.log(value)
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
        console.log('selectionRows', selectionRows)
        var selectedPrice = 0;
        for(var i=0;i<selectionRows.length;i++){
          selectedPrice = this.numAdd(selectedPrice,selectionRows[i].payment)
        }
        this.selectedPrice = selectedPrice;
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
        this.selectedPrice=0;
      },
      //监听checkbox属性
      getCheckboxProps(record) {
        return {
          props: {
            disabled: record.status !=0,
          }
        }
      },
      //付款
      handlePayment(){
        let that = this
        if (that.selectedRowKeys.length <= 0) {
          that.$message.warning('请选择一条记录！');
          return;
        } else {
          var ids = "";
          for (var a = 0; a < that.selectedRowKeys.length; a++) {
            ids += that.selectedRowKeys[a] + ",";
          }

          const modal = that.$confirm({
            title: '确定付款',
            closable: true,
            keyboard: false,
            maskClosable: true,
            content: '确定付款吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: function() {
              that.loading = true
              //param对象作为字符串接收时，要stringify转换，否则application/json默认为对象接收
              var param={ids:ids}
              hanpayment(qs.stringify(param)).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData(1)
                  that.onClearSelected()
                } else {
                  that.$message.error(res.message)
                }
                that.loading = false
              })
            },
            onCancel(e) {
              modal.destroy()
            }
          })
        }
      },
      //失败原因
      handleFailReason(record){
        this.$error({
          title: '失败原因',
          content: record.failureReason,
          okText: '确定'
        })
      },
      //补发
      handleBackPay(record){
        let that = this
        that.$refs.modalPayBackForm.edit(record)
        that.$refs.modalPayBackForm.title = '修改用户信息'
        that.$refs.modalPayBackForm.disableSubmit = false
      },
      modalFormOk(){
        this.loadData(1)
      },
      /**
       * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
       * @param num1
       * @param num2
       * @returns {number}
       */
      numAdd(num1, num2) {
          var baseNum, baseNum1, baseNum2;
          try {
            baseNum1 = num1.toString().split(".")[1].length;
          } catch (e) {
            baseNum1 = 0;
          }
          try {
            baseNum2 = num2.toString().split(".")[1].length;
          } catch (e) {
            baseNum2 = 0;
          }
          baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
          return (num1 * baseNum + num2 * baseNum) / baseNum;
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>