<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" style="height: 100%;">
        <a-row :gutter="24">
          <a-col :md="8" :sm="12">
            <a-form-item label="">
              <a-select v-model="subcontractorKey" @change="chooseSubcontractor" placeholder="请选择服务商">
                <a-select-option v-for="(item,key) in Subcontractor" :key="key" :value="key">
                  {{item.name}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" style="float: right">
            <a-form-item label="账目余额">
              <span style="font-size: 18px;">{{balanceMoney}}元</span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域 -->
    <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.companyName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="9" :sm="12">
            <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>
          <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="ant-alert ant-alert-info" style="margin-bottom: 16px;">
      <a-row :gutter="24">
        <a-col :md="8" :sm="8">
          <div style="display: flex;flex-direction: column"><i class="anticon anticon-info-circle ant-alert-icon"></i> 充值合计 <a style="font-weight: 600">{{rechargeMoney}}元</a></div>
        </a-col>
        <a-col :md="8" :sm="8">
          <div style="display: flex;flex-direction: column;"><i class="anticon anticon-info-circle ant-alert-icon"></i> 服务费合计 <a style="font-weight: 600">{{serviceMoney}}元</a></div>
        </a-col>
        <a-col :md="8" :sm="8">
          <div style="display: flex;flex-direction: column;"><i class="anticon anticon-info-circle ant-alert-icon"></i> 付款合计 <a style="font-weight: 600">{{paymentMoney}}元</a></div>
        </a-col>
      </a-row>

    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('收支记录')" v-has="'accountDetail:export'">导出</a-button>
    </div>

    <!-- table区域-begin -->
    <div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :scroll="{ x: 2000 }"
        @change="handleTableChange">

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

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { Arithmetic } from '@/mixins/Arithmetic'
  import { getAction,downFile } from '@/api/manage'
  import { filterObj } from '@/utils/util';

  export default {
    name: "HlgAccountList",
    mixins:[JeecgListMixin,Arithmetic],
    components: {

    },
    data () {
      return {
        description: '账户信息表管理页面',
        allowClear:false,
        // 查询条件
        queryParam: {
          createTimeRange:[],
        },
        // 表头
        columns: [
          {
            title:'企业名称',
            align:"left",
            width: 200,
            dataIndex: 'companyName'
          },
          {
            title:'服务商',
            align:"left",
            width: 300,
            dataIndex: 'subcontractorName'
          },
          {
            title:'平台',
            align:"left",
            width: 200,
            dataIndex: 'platformName'
          },
          {
            title:'收支方向',
            align:"left",
            width: 150,
            dataIndex: 'type_dictText'
          },
          {
            title:'金额',
            align:"left",
            width: 150,
            dataIndex: 'amount',
            customRender: (value,record) => {
              if(record.isDrawback === 1){
                return value ? value +'(已退款)': value === 0 ? value+'(已退款)':'--'
              }
              return value ? value:value === 0 ? value:'--'
            }
          },
          {
            title:'服务费',
            align:"left",
            width: 150,
            dataIndex: 'serviceFee',
            customRender: (value,record) => {
              if(record.isDrawback === 1){
                return value ? value +'(已退款)': value === 0 ? value+'(已退款)':'--'
              }
              return value ? value:value===0 ? value:'--'

            }
          },
          {
            title:'备注',
            align:"left",
            dataIndex: 'remark',
            width: 500
          },
          {
            title:'业务时间',
            align:"left",
            width: 200,
            dataIndex: 'generateTime'
          },
          {
            title: '操作人',
            align: 'left',
            width: 150,
            dataIndex: 'generateBy',
          }
        ],
        url: {
          detailList: "/hlgaccount/hlgAccountDetail/allList",
          exportXlsUrl: "/hlgaccount/hlgAccountDetail/exportXlsNew",
          list: '/hlgsubcontractor/hlgSubcontractor/allList',
          balance: '/hlgaccount/hlgAccount/balance'
        },
        rechargeMoney: '0.00',
        paymentMoney: '0.00',
        serviceMoney: '0.00',
        Subcontractor: [],
        subcontractorId: 0,
        subcontractorKey: 0,
        subcontractorName: '',
        balanceMoney: '0.00',
        dictOptions:{
        }
      }
    },
    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);
      },
      //查询所有服务商
      loadData(){
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        var params = {};
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            if (res.result && res.result.length > 0) {
              this.subcontractorId = res.result[0].id
              this.subcontractorName = res.result[0].name
              this.subcontractorKey = 0
              this.getDetails(1)
              this.getBalance()
            }
            this.Subcontractor = res.result;
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
        })
      },
      getDetails(arg) {
        if(!this.url.detailList){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams();//查询条件
        params.subcontractorId = this.subcontractorId;
        this.loading = true;
        getAction(this.url.detailList, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records;
            this.ipagination.total = res.result.total;
            if(res.result.records.length > 0){
              this.rechargeMoney = this.returnFloat(res.result.records[0].rechargeMoney) || '0.00';
              this.paymentMoney = this.returnFloat(res.result.records[0].paymentMoney) || '0.00';
              this.serviceMoney = this.returnFloat(res.result.records[0].serviceMoney) || '0.00';
            }else{
              this.rechargeMoney = '0.00'
              this.paymentMoney = '0.00'
              this.serviceMoney = '0.00'
            }
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
          this.loading = false;
        })
      },
      handleDetail(record){
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = record.companyName
        this.$refs.modalForm.disableSubmit = false
      },
      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);
      },
      chooseSubcontractor(index){
        this.subcontractorId = this.Subcontractor[index].id
        this.subcontractorName = this.Subcontractor[index].name
        this.subcontractorKey = index
        this.getDetails(1)
        this.getBalance()
      },
      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.getDetails();
      },
      //获取账目余额
      getBalance(){
        if(!this.url.balance){
          this.$message.error("请设置url.balance属性!")
          return
        }
        var params = {};//查询条件
        params.subcontractorId = this.subcontractorId;
        getAction(this.url.balance, params).then((res) => {
          if (res.success) {
            this.balanceMoney = this.returnFloat(res.result) || '0.00';
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
        })
      },
      searchQuery(){
        this.getDetails(1);
      },
      searchReset() {
        this.queryParam = {}
        this.getDetails(1);
      },
      /* 导出 */
      handleExportXls(fileName){
        if(!fileName || typeof fileName != "string"){
          fileName = "导出文件"
        }
        let param = this.getQueryParams();
        param.subcontractorId = this.subcontractorId;
        if(this.selectedRowKeys && this.selectedRowKeys.length>0){
          param['selections'] = this.selectedRowKeys.join(",")
        }
        console.log("导出参数",param)
        downFile(this.url.exportXlsUrl,param).then((data)=>{
          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'
</style>