import React, { Component } from "react";
import ReactDOM from 'react-dom';
import moment from 'moment';
import "moment/locale/zh-cn";
import axios from 'axios';
import store from 'store';
import {
  DatePicker,
  Input,
  Select,
  Button,
  Table,
  Alert
} from 'antd';
// import ExcelButton from '../../../../components/ExcelButton';
const { Option } = Select;
const { RangePicker } = DatePicker;
import {
  host,
  getComWalletReconciliation,
  publicCommonDictGetDictByCodeTypes
} from '../../../../services/api';
export default class Reconciliation extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      tableList: [],
      searchData: {  // 表格数据请求参数
        startDate: moment().subtract(30, 'days').format('YYYYMMDD'),
        endDate: moment().format('YYYYMMDD'),
        fundFlowType: '1', //1收入 2支出 (资金流向)
        bankTradeType: '', //银行交易类型
        accountName: '', //对方账户
        pageNumber: '1',  // 页	
        pageSize: '10'  //条目
      },
      rangePickeValue: [moment().subtract(30, 'days'), moment()],
      pagination: {  //分页数据
        total: 1,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共搜索到${total}条记录`
      },
      tradeTypes: [],  //交易类型
      info: {
        TotalCount: 0,
        errorAmount: 0,
        errorCount: 0,
        processingAmount: 0,
        processingCount: 0,
        successAmount: 0,
        successCount: 0,
        sumAmount: 0,
      }
    };
  }
  componentDidMount() {
    // // test start
    // this.setState({
    //   tableList: [{
    //     "serviceType": "通用下账",
    //     "amount": "10.00",
    //     "accounts_deal_date": "2019-06-27 17:03:03",
    //     "flow_no": "01328943255678636117",
    //     "account_in": "",
    //     "memo": "",
    //     "trade_flow_no": "M0128946956654248027",
    //     "trade_date": "2019-06-27 17:17:46",
    //     "balance": "1602.00",
    //     "hand_status": "成功",
    //     "trade_type": "消费",
    //     "account_out": "3008001002356511000010",
    //     "create_date": "2019-06-27 17:17:46",
    //     "direction": "出账"
    //   }]
    // });
    // //test end
    this.__getTable();
    // 获取类型
    this.__getCodeTypes();
  }
  // 获取表格信息
  __getTable = () => {
    let { searchData } = this.state;
    getComWalletReconciliation(searchData).then(res => {
      const { pageInfo } = res.data;
      this.setState({
        tableList: pageInfo.data,
        pagination: {
          ...this.state.pagination,
          total: pageInfo.total,
          current: pageInfo.pageNumber,
          pageSize: pageInfo.pageSize
        },
        info: {
          totalCount: res.data.totalCount ? res.data.totalCount : 0,
          errorAmount: res.data.errorAmount ? res.data.errorAmount : 0,
          errorCount: res.data.errorCount ? res.data.errorCount : 0,
          processingAmount: res.data.processingAmount ? res.data.processingAmount : 0,
          processingCount: res.data.processingCount ? res.data.processingCount : 0,
          successAmount: res.data.successAmount ? res.data.successAmount : 0,
          successCount: res.data.successCount ? res.data.successCount : 0,
          sumAmount: res.data.sumAmount ? res.data.sumAmount : 0,
        }
      });
    });
  }
  //类型查询
  __getCodeTypes = () => {
    publicCommonDictGetDictByCodeTypes({ codeTypes: "bankTradeType" }).then((data) => {
      const tradeTypes = data.data.bankTradeType;
      tradeTypes.unshift({
        codeType: "bankTradeType",
        codeValue: "",
        label: "全部"
      });
      this.setState({ tradeTypes: data.data.bankTradeType });
    }, (err) => {
      console.log(err);
    });
  }
  render() {
    const columns = [
      {
        title: '交易流水号',
        dataIndex: 'tradeSerialNo',
        key: 'tradeSerialNo',
        fixed: 'left',
        width: 250,
        render: (text) => {
          return <div style={{width: 250}}>
            {text}
          </div>
        }
      },
      // {
      //   title: '业务类型',
      //   dataIndex: 'trade_flow_no',
      //   key: 'trade_flow_no'
      // },
      {
        title: '交易类型',
        dataIndex: 'bankTradeType',
        key: 'bankTradeType',
        render: (text) => {
          return <div style={{width: 100}}>
            {text}
          </div>
        }
      },
      {
        title: '交易状态',
        dataIndex: 'tradeStatus',
        key: 'tradeStatus',
        render: (text) => {
          return <div style={{width: 150}}>
            {text}
          </div>
        }
      },
      {
        title: '交易订单创建时间',
        dataIndex: 'tradeStartTime',
        key: 'tradeStartTime',
        render: (text) => {
          return <div style={{width: 150}}>
            {text}
          </div>
        }
      },
      {
        title: '交易金额',
        dataIndex: 'tradeAmount',
        key: 'tradeAmount',
        render: (text) => {
          return <div style={{width: 150}}>
            {text}
          </div>
        }
      },
      {
        title: '出账方户名',
        dataIndex: 'expendAccountName',
        key: 'expendAccountName',
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      },
      {
        title: '出账方账号',
        dataIndex: 'expendAccountNo',
        key: 'expendAccountNo',
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      },
      {
        title: '出账方银行简称',
        dataIndex: 'expendBank',
        key: 'expendBank',
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      },
      {
        title: '入账方户名',
        dataIndex: 'incomeAccountName',
        key: 'incomeAccountName',
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      },
      {
        title: '入账方账号',
        dataIndex: 'incomeAccountNo',
        key: 'incomeAccountNo',
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      },
      {
        title: '入账方银行简称',
        dataIndex: 'incomeBank',
        key: 'incomeBank',
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      },
      {
        title: '入账方证件号',
        dataIndex: 'incomeCerNo',
        key: 'incomeCerNo',
        width: 200,
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      },
      {
        title: '交易备注',
        dataIndex: 'remark',
        key: 'remark',
        render: (text) => {
          return <div style={{width: 200}}>
            {text}
          </div>
        }
      }
    ];
    return (
      <div>
        <Alert 
          message="对账数据生成：每天凌晨定时产生前一日的对账数据。"
          type="warning"
          showIcon 
          style={{marginBottom: 15}}
        />
        <label style={{ marginRight: '16px', display: 'inline-block' }}>
          交易类型：
          <Select value={this.state.searchData.bankTradeType} placeholder="请选择" style={{ width: 120 }} onChange={value => {
            this.setState({
              searchData: {
                ...this.state.searchData,
                bankTradeType: value
              }
            });
          }}>
            {
              this.state.tradeTypes.map((item, index) => {
                return <Option key={index} value={item.codeValue}>{item.label}</Option>;
              })
            }
          </Select>
        </label>
        <label style={{ marginRight: '16px', display: 'inline-block' }}>
          交易时间：
          <RangePicker
            format='YYYY-MM-DD'
            value={this.state.rangePickeValue}
            onChange={(date, dateString) => {
              this.setState({
                rangePickeValue: date,
                searchData: {
                  ...this.state.searchData,
                  startDate: dateString[0].replace(/-/g, ''),
                  endDate: dateString[1].replace(/-/g, '')
                }
              });
            }}
            style={{ marginBottom: '10px' }}
          />
        </label>
        <br />
        <label style={{ marginRight: '16px', display: 'inline-block' }}>
          资金流向：
          <Select placeholder="请选择" value={this.state.searchData.fundFlowType} style={{ width: 120 }} onChange={value => {
            this.setState({
              searchData: {
                ...this.state.searchData,
                fundFlowType: value
              }
            });
          }}>
            <Option value="1">收入</Option>
            <Option value="2">支出</Option>
          </Select>
        </label>
        <label style={{ marginRight: '16px', display: 'inline-block' }}>
          对方户名：
          <Input value={this.state.searchData.accountName} style={{ display: 'inline', width: 333 }} placeholder="请输入" onChange={e => {
            this.setState({
              searchData: {
                ...this.state.searchData,
                accountName: e.target.value
              }
            });
          }} />
        </label>
        <Button
          style={{
            marginRight: '16px',
            marginBottom: '16px',
            padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px'
          }}
          type="primary"
          onClick={() => {
            this.__getTable();
          }}
        >
          搜索
        </Button>
        <Button
          style={{
            marginRight: '16px',
            marginBottom: '16px',
            padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px'
          }}
          onClick={() => {
            this.setState({
              searchData: {  // 表格数据请求参数
                startDate: moment().subtract(30, 'days').format('YYYYMMDD'),
                endDate: moment().format('YYYYMMDD'),
                fundFlowType: '1',
                bankTradeType: '',
                accountName: '',
                pageNumber: '1',  // 页	
                pageSize: '10'  //条目
              },
              rangePickeValue: [moment().subtract(30, 'days'), moment()]
            }, () => {
              this.__getTable();
            });
          }}
        >
          重置
        </Button>
        <br />
        {/* <ExcelButton 
          fileName={'对账数据'}
          table={ReactDOM.findDOMNode(this.refs.table)}
        >
          导出为excel文件
        </ExcelButton> */}
        <Button
          type="primary"
          onClick={() => {
            const queryData = { ...this.state.searchData };
            delete queryData.pageNumber;
            delete queryData.pageSize;
            const queryString = Object.keys(queryData).reduce((a, b) => {
              return `${a}&${b}=${queryData[b]}`;
            }, '').slice(1);
            axios({
              method: 'get',
              url: `${host}/task/com/wallet/export-com-wallet-reconciliation?${queryString}`, //后台请求地址
              responseType: 'blob',
              headers: {
                access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

              }
            }).then(data => {
              if (!data) {
                return;
              }
              const { fundFlowType, startDate, endDate } = this.state.searchData;
              const fundFlowTypeStr = fundFlowType == 1? '收入': '支出';
              let url = window.URL.createObjectURL(data.data);
              let link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.setAttribute('download', `${fundFlowTypeStr}_对账数据_${startDate}~${endDate}.xls`);
              document.body.appendChild(link);
              link.click();
            });
          }}
        >
          导出为excel文件
        </Button>
        <div style={{fontSize: 16, margin: '10px 0'}}>
          <span style={{ margin: '0 10px'}}>
            总笔数：{this.state.info.totalCount}笔 
          </span>
          | 
          <span style={{ margin: '0 10px'}}>
            总金额：{this.state.info.sumAmount}元 
          </span>
          |
          <span style={{color: 'green', margin: '0 10px'}}>成功笔数：{this.state.info.successCount}笔 </span>
          | 
          <span style={{color: 'green', margin: '0 10px'}}>
            成功金额：{this.state.info.successAmount}元 
          </span>
          | 
          <span style={{color: 'red', margin: '0 10px'}}>
            失败笔数：{this.state.info.errorCount}笔 
          </span>
          | 
          <span style={{color: 'red', margin: '0 10px'}}>
            失败金额：{this.state.info.errorAmount}元 
          </span>
          | 
          <span style={{color: 'orange', margin: '0 10px'}}>
            处理中笔数：{this.state.info.processingCount}笔 
          </span>
          | 
          <span style={{color: 'orange', margin: '0 10px'}}>
            处理中金额：{this.state.info.processingAmount}元
          </span>
        </div>
        <Table
          dataSource={this.state.tableList}
          columns={columns}
          pagination={this.state.pagination}
          scroll={{ x: 800 }}
          onChange={(pagination) => {
            const searchData = {  // 搜索数据
              ...this.state.searchData,
              pageNumber: pagination.current,  // 页	
              pageSize: pagination.pageSize
            };
            this.setState({
              searchData
            }, () => {
              this.__getTable();
            });
          }}
        />
      </div>
    );
  }
}
