<template>
  <div class="page-header-index-wide">
    <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.paymentCode"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="付款企业">
                <a-input placeholder="请输入付款企业" v-model="queryParam.paymentCompany"></a-input>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">
              <a-col :md="6" :sm="8">
                <a-form-item label="状态">
                  <j-dict-select-tag :triggerChange="false" v-model="queryParam.status" placeholder="请选择状态查询"
                                     dictCode="payment_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 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 class="ant-btn ant-btn-primary" @click="handleImportExcel1()" icon="import" type="primary"
           v-has="'payment:import'">导入</a>
        <a class="ant-btn ant-btn-primary" @click="handleEditServiceFee()" type="primary"
           v-has="'payment:editServiceFee'">编辑服务费</a>
      </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">{{selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="deloading"
          :scroll="{ x: 1350}"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:getCheckboxProps}"
          @change="handleTableChange">

        <span slot="action1" slot-scope="text, record">
          <a @click="handleEdit(record)">{{record.paymentCode}}</a>
        </span>

          <span slot="action" slot-scope="text, record">
          <template v-if="record.status == 1">
            <template v-if="record.comAccountDetailCount>0">
              <a @click="handlePayment(record)" v-has="'payment:pay'">付款</a>
            </template>
            <template v-if="record.comAccountDetailCount<=0">
              <a @click="handleRecord(record)" v-has="'payment:come'">入账</a>
              <a-divider type="vertical" v-has="'payment:come'"/>
              <a @click="handleBack(record)" v-has="'payment:back'">打回</a>
              <a-divider type="vertical" v-has="'payment:back'"/>
              <a @click="handleDelete(record.id)" v-has="'payment:del'">删除</a>
            </template>
          </template>
          <template v-else-if="record.status == 0">
            <a @click="handleDelete(record.id)" v-has="'payment:del'">删除</a>
          </template>
          <template v-else>
            -
          </template>
        </span>

        </a-table>
      </div>

      <hwPayment-modal ref="modalForm" @ok="modalFormOk"></hwPayment-modal>
      <hw-payment-export-modal ref="modalSelectRequireForm" @ok="modalFormOk"></hw-payment-export-modal>
      <hw-payment-record-modal ref="modalRecordForm" @ok="modalFormOk"></hw-payment-record-modal>
      <hw-payment-edit-service-fee-modal ref="modalEditServiceFeeForm" @ok="modalFormOk"></hw-payment-edit-service-fee-modal>
    </a-card>
  </div>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import HwPaymentModal from './modules/HwPaymentModal'
  import { filterObj } from '@/utils/util'
  import { getAction, deleteAction, putAction, postAction } from '@/api/manage'
  import HwPaymentExportModal from './modules/HwPaymentExportModal'
  import HwPaymentRecordModal from './modules/HwPaymentRecordModal'
  import HwPaymentEditServiceFeeModal from './modules/HwPaymentEditServiceFeeModal'
  import qs from 'qs';
  const deletePayment = (params) => deleteAction('/hwpayment/hwPayment/delete', params)
  const bankPayment = (params) => putAction('/hwpayment/hwPayment/bankPayment', params)
  const hanpayment = (params) => putAction('/hwpayment/hwPaymentDetail/handPayment', params)
  const hanSupplementPayment = (params) => putAction('/hwpayment/hwPaymentDetail/handSupplementPayment', params)

  export default {
    name: 'HwPaymentList',
    mixins: [JeecgListMixin],
    components: {
      HwPaymentModal,
      HwPaymentExportModal,
      HwPaymentRecordModal,
      HwPaymentEditServiceFeeModal
    },
    data() {
      return {
        description: 'hw_payment管理页面',
        // 查询条件
        queryParam: {
          createTimeRange: []
        },
        // 表头
        columns: [
          {
            title: '付款单号',
            align: 'center',
            dataIndex: 'paymentCode',
            scopedSlots: { customRender: 'action1' }
          },
          {
            title: '付款企业',
            align: 'center',
            dataIndex: 'paymentCompany'
          },
          {
            title: '收款企业',
            align: 'center',
            dataIndex: '',
            customRender: function(value, record) {
              //A-B，通过平台
              if (record.subcontractType != null) {
                return "江苏开心工作科技有限公司";
              }
              return record.subName;
            }
          },
          {
            title: '项目金额',
            align: 'center',
            dataIndex: 'payment'
          },
          {
            title: '服务费',
            align: 'center',
            dataIndex: 'serviceFee'
          },
          {
            title: '总计',
            align: 'center',
            dataIndex: 'totalPayment'
          },
          {
            title: '导入时间',
            align: 'center',
            dataIndex: 'createTime'
          },
          {
            title: '导入人',
            align: 'center',
            dataIndex: 'createBy'
          },
          {
            title: '付款人',
            align: 'center',
            dataIndex: 'paymentBy'
          },
          {
            title: '状态',
            align: 'center',
            dataIndex: 'status_dictText'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 160,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: '/hwpayment/hwPayment/list',
          delete: '/hwpayment/hwPayment/delete',
          deleteBatch: '/hwpayment/hwPayment/deleteBatch',
          exportXlsUrl: '/hwpayment/hwPayment/exportXls',
          importExcelUrl: 'hwpayment/hwPayment/importExcel'
        },
        dictOptions: {},
        //自定义加载层
        deloading:{
          spinning:false,
          tip:''
        },
        allowClear:false,
      }
    },
    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
        delete param.createTimeRange // 时间参数不传递后台
        return filterObj(param)
      },
      initDictConfig() {
      },
      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)
      },
      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.deloading.spinning = true
        this.deloading.tip = '';
        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.deloading.spinning = false
        })
      },
      handleDelete(id) {
        let that = this
        const modal = that.$confirm({
          title: '删除付款',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '确定要删除该付款吗？',
          okText: '确定删除',
          cancelText: '取消',
          onOk: function() {
            deletePayment({ id: id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
              } else {
                that.$error({
                  title: '删除失败',
                  content: res.message,
                  okText: '确定'
                })
              }
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },
      handleBack(record) {
        let that = this
        const modal = that.$confirm({
          title: '打回付款',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '确定要打回该付款吗？',
          okText: '确定打回',
          cancelText: '取消',
          onOk: function() {
            bankPayment({ id: record.id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
              } else {
                that.$message.error(res.message)
              }
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },
      handleEdit(record) {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '付款详情'
        this.$refs.modalForm.disableSubmit = false
      },
      handleImportExcel1() {
        this.$refs.modalSelectRequireForm.edit()
        this.$refs.modalSelectRequireForm.title = '导入付款信息'
        this.$refs.modalSelectRequireForm.disableSubmit = false
      },
      //入账
      handleRecord(record) {
        this.$refs.modalRecordForm.edit(record)
        this.$refs.modalRecordForm.title = '入账'
        this.$refs.modalRecordForm.disableSubmit = false
      },
      //付款
      handlePayment(record) {
        let that = this
        //判断余额
        if(record.subAccountBalance < record.payment){
          that.$error({
            title: '错误提示',
            content: '企业账户余额不足，无法完成本次支付命令',
            okText: '确定',
            centered:true
          })
          return;
        }
        const modal = that.$confirm({
          title: '付款确认',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '确定要支付该付款单吗',
          okText: '确认付款',
          cancelText: '取消',
          centered:true,
          onOk: function() {
            that.deloading.spinning = true
            that.deloading.tip = '付款处理中，请稍后...';
            //param对象作为字符串接收时，要stringify转换，否则application/json默认为对象接收
            var param = { paymentId: record.id }
            hanpayment(qs.stringify(param)).then((res) => {
              if (res.success) {
                that.$success({
                  title: '提示',
                  content: res.message,
                  okText: '确定',
                  centered:true,
                  onOk: () => {
                    that.loadData(1)
                  }
                })
              } else {
                that.$error({
                  title: '错误提示',
                  content: res.message,
                  okText: '确定',
                  centered:true
                })
              }
              that.deloading.spinning = false
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })

      },
      //补发付款
      handleSupplementPayment(record){
        console.log("补发")
        let that = this
        const modal = that.$confirm({
          title: '确定付款',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '本次付款将扣除账户余额'+record.payment,
          okText: '确定付款',
          cancelText: '取消',
          centered:true,
          onOk: function() {
            that.deloading.spinning = true
            that.deloading.tip = '付款处理中，请稍后...';
            //param对象作为字符串接收时，要stringify转换，否则application/json默认为对象接收
            var param = { paymentId: record.id }
            hanSupplementPayment(qs.stringify(param)).then((res) => {
              if (res.success) {
                that.$success({
                  title: '提示',
                  content: res.message,
                  okText: '确定',
                  centered:true,
                  onOk: () => {
                    that.loadData(1)
                  }
                })
              } else {
                that.$error({
                  title: '错误提示',
                  content: res.message,
                  okText: '确定',
                  centered:true
                })
              }
              that.deloading.spinning = false
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },
      //监听checkbox属性
      getCheckboxProps(record) {
        return {
          props: {
            disabled: record.comAccountDetailCount<=0
          }
        }
      },
      //编辑服务费
      handleEditServiceFee(){
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return false;
        }
        if (this.selectedRowKeys.length > 1) {
          this.$message.warning('只能选择一条记录！');
          return false;
        }
        if(this.selectionRows[0].comAccountDetailCount<=0){
          this.$error({
            title: '错误提示',
            content: '付款单还没有入账，无法编辑服务费',
            okText: '确定'
          })
          return false;
        }
        this.$refs.modalEditServiceFeeForm.edit(this.selectionRows[0])
        this.$refs.modalEditServiceFeeForm.title = '编辑服务费'
        this.$refs.modalEditServiceFeeForm.disableSubmit = false
      },
      modalFormOk(){
        this.loadData(1);
        this.onClearSelected();
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>