<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="6" :sm="8">
                  <a-form-item label="状态">
                    <j-dict-select-tag :triggerChange="false" v-model="queryParam.status" placeholder="请选择状态查询"
                                       dictCode="pay_status" v-decorator="['status', {}]"/>
                  </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 ghost type='primary' @click="searchQuery" icon="search">查询</a-button>
                  <a-button ghost 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 type="primary" icon="download" @click="handleExportXls('付款明细表')">导出</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"
            class="j-table-force-nowrap"
            @change="handleTableChange">

            <span slot="status" slot-scope="text, record">
              {{text}}
              <a type="link" v-if="record.status === 4" style="margin-left: 8px" @click="checkCause(record)"> 原因</a>
            </span>

          </a-table>
        </div>
      </a-card>
    </a-spin>

  </a-modal>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { httpAction, getAction,putAction,downFile } 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 JEllipsis from '@/components/jeecg/JEllipsis'

  export default {
    name: 'HwPaymentModal',
    mixins: [JeecgListMixin],
    components: {
      JDate,
      JEllipsis
    },
    data() {
      return {
        description: 'hw_payment_detail管理页面',
        allowClear:false,
        bodyStyle: {
          padding: '0',
          height: (window.innerHeight * 0.66) + 'px',
          'overflow-y': 'auto'
        },
        modelStyle: {
          width: '80%',
          style: { top: '20px' },
          fullScreen: false
        },
        // 查询条件
        queryParam: {
          createTimeRange: [],
        },
        // 表头
        columns: [
          {
            title:'姓名',
            align:"left",
            dataIndex: 'userName'
          },
          {
            title:'身份证号',
            align:"left",
            dataIndex: 'idcardNumber'
          },
          {
            title:'银行卡号',
            align:"left",
            dataIndex: 'cardNumber'
          },
          {
            title:'银行名称',
            align:"left",
            dataIndex: 'eacbnk',
            customRender: function(text, record) {
              return record.bnkflg === 'Y' ? '招商银行' : text
            }
          },
          {
            title:'开户地',
            align:"left",
            dataIndex: 'rcveaa',
            customRender: function(text, record) {
              return text ? text : '--'
            }
          },
          {
            title:'支付状态',
            align:"left",
            dataIndex: 'status_dictText',
            scopedSlots: { customRender: 'status' }
          },
          {
            title:'付款金额',
            align:"left",
            dataIndex: 'payment'
          },
          {
            title:'到账金额',
            align:"left",
            dataIndex: 'netPayment'
          },
          {
            title: '返回结果时间',
            align: "left",
            dataIndex: 'paymentResultTime',
            customRender: function(text, record) {
              return text ? text : '--'
            }
          }
        ],
        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
        }
        if(!this.paymentId){
          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)
      },

      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
        this.selectedPrice=0;
      },
      checkCause(record) {
        this.$error({
          title: '失败原因',
          content: record.failureReason,
          okText: '确定',
          centered: true
        })
      },

      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;
      },
      handleExportXls(fileName){
        if(!fileName || typeof fileName != "string"){
          fileName = "导出文件"
        }
        let param = {...this.queryParam};
        if(this.selectedRowKeys && this.selectedRowKeys.length>0){
          param['selections'] = this.selectedRowKeys.join(",")
        }
        param.paymentId = this.paymentId;
        console.log("导出参数",param)
        downFile(this.url.exportXlsUrl,param).then((data)=>{
          console.log("导出参数",param)

          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls')
          }else{
            let url = window.URL.createObjectURL(new Blob([data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName+'.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  ::v-deep .ant-table-pagination{
    float: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>