import React, { Component } from "react";
import { connect } from "dva";
import '../financialWallet.less';
import { withRouter } from 'dva/router';
import * as ajax from '../../../services/api';
import { SMS_OP_TRANSFER } from '../../../common/shortMessage';
import $modal from '../modal';
import { gup } from '../../../utils/utils';
import dff from '../../../assets/images/wallet/dff1.png';
import ffsb from '../../../assets/images/wallet/ffsb2.png';
import ffcg from '../../../assets/images/wallet/ffcg1.png';
import ffze from '../../../assets/images/wallet/ffze1.png';
import { Alert, Input, Button, Table, Form, Modal } from "antd";

@connect(state => ({
  profile: state.profile
}))
@withRouter
@Form.create()
export default class Messages extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      totalInfo: null,
      grantInfo: null,
      // 搜索部分
      searchData: {  // 表格数据请求参数
        comGrantId: gup('comGrantId'),
        keyword: '',  //关键字
        pageNumber: '1',  // 页	
        pageSize: '10'  //条目
      },
      keyword: '', //关键字
      // 表格部分
      tableList: [], // 表格数据
      pagination: {  //分页数据
        total: 1,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      canAddData: false,

      // 操作记录
      operationVisibale: false,
      operationPagination: {
        total: 1,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true
      },
      operationList: [],
    };
  }
  componentDidMount() {
    //获取薪资代发记录汇总
    ajax.selectGrantDetailTotalMap({ comGrantId: gup('comGrantId') }).then(res => {
      this.setState({
        totalInfo: res.data
      });
    });
    //【薪资代发】根据id获取薪资代发记录
    ajax.getComGrantInfoById({ comGrantId: gup('comGrantId') }).then(res => {
      this.setState({
        grantInfo: res.data
      });
    });
    this.getTable(this.state.searchData, list => {
      list.length == 0 && this.setState({
        canAddData: true
      });
    });
  }
  // 获取操作记录
  getOperationTable = (data, cb) => {
    ajax.getComOperRecordList(data).then(res => {
      this.setState({
        operationList: res.data,
        operationPagination: {
          ...this.state.operationPagination,
          total: res.data.total,
          current: res.data.pageNumber,
          pageSize: res.data.pageSize
        }
      }, () => {
        cb && cb(res.data.data);
      });
    });
  }
  // 获取表格信息
  getTable = (data, cb) => {
    ajax.pageFailComGrantDetailList(data).then(res => {
      this.setState({
        tableList: res.data.data,
        pagination: {
          ...this.state.pagination,
          total: res.data.total,
          current: res.data.pageNumber,
          pageSize: res.data.pageSize
        }
      }, () => {
        cb && cb(res.data.data);
      });
    });
  }
   // 操作记录表格渲染
   renderOperationList = () => {
    const columns = [
      {
        title: '时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '操作人',
        dataIndex: 'createUserName',
        key: 'createUserName'
      },
      {
        title: '操作功能',
        dataIndex: 'operGrantFuncType',
        key: 'operGrantFuncType'
      },
      {
        title: '操作结果',
        dataIndex: 'operResult',
        key: 'operResult'
      }
    ];
    return (
      <div>
        <Table
          dataSource={this.state.operationList}
          columns={columns}
          // pagination={this.state.operationPagination}
          onChange={(pagination) => {
            pagination.comGrantId = gup('comGrantId');
            this.setState({
              operationSearchData: {
                pageNumber: pagination.current,  // 页	
                pageSize: pagination.pageSize
              }
            }, () => {
              this.getOperationTable(pagination);
            });

          }}
        />
      </div>
    );
  };
  // 表格渲染
  renderOrderList = () => {
    const columns = [
      {
        title: '收款人姓名',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '身份证号码',
        dataIndex: 'idCardNo',
        key: 'idCardNo'
      },
      {
        title: '手机号码',
        dataIndex: 'mobilePhone',
        key: 'mobilePhone'
      },
      {
        title: '收款账户',
        dataIndex: 'walletAccountNo',
        key: 'walletAccountNo'
      },
      {
        title: '应发工资（元）',
        dataIndex: 'amount',
        key: 'amount'
      },
      {
        title: '状态',
        dataIndex: 'grantStatus',
        key: 'grantStatus',
        render: text => <span style={{color: 'red'}}>{text}</span>
      },
      {
        title: '失败原因',
        dataIndex: 'remark',
        key: 'remark',
        render: text => <span style={{color: 'red'}}>{text}</span>
      }
    ];
    return (
      <div>
        <Table
          dataSource={this.state.tableList}
          columns={columns}
          pagination={this.state.pagination}
          onChange={(pagination) => {
            const searchData = {  // 搜索数据
              ...this.state.searchData,
              pageNumber: pagination.current,  // 页	
              pageSize: pagination.pageSize
            };
            this.setState({
              searchData
            }, () => {
              this.getTable(searchData);
            });

          }}
        // rowSelection={{
        //   onChange: (selectedRowKeys, selectedRows) => {
        //     this.setState({
        //       selectedRows,
        //       selectedRowKeys
        //     });
        //   },
        //   selectedRowKeys: this.state.selectedRowKeys     
        // }}
        />
      </div>
    );
  };

  render() {
    return (
      <div style={{ paddingTop: '10px' }}>
        <div className="tab_inner">
        <section style={{marginBottom: 10}}>
            <Button
              style={{marginRight: 15}}
              onClick={() => {
                // this.props.history.goBack();
                this.props.history.push('/finance/salary-proxy');
              }}
            >返回列表</Button>
            {
              this.state.grantInfo &&
              <span>
                {this.state.grantInfo.title} （{gup('comGrantId')}）
              </span>
            }
          </section>
          <Alert
            message={<div>
              <span>1、发放工资：发放前请确认发放人数、发放总额、企业钱包余额是否充足，若不足，请<a onClick={() => {
                this.props.history.push('/finance/business-wallet');
              }}>充值</a>；</span><br />
              <span>2、未开通钱包服务的员工，请提醒其在APP端进行开通，否则无法向其发放工资。</span><br />
            </div>}
            type="warning"
            showIcon
            style={{ marginBottom: '15px' }}
          />

          {
            this.state.totalInfo &&
            <div className="statistics_container">
              <div
                className="statistics_uint"
                onClick={() => {
                  this.props.history.push(`/finance/salary-proxy-list?comGrantId=${gup('comGrantId')}`);
                }}  
              >
                <img src={dff} alt=""/>
                <div className="uint_info">
                  <p>待发放总额</p>
                  <p className="bold">{this.state.totalInfo.toTotalAmount}</p>
                  <p>待发放总笔数：{this.state.totalInfo.toTotalSize}</p>
                </div>
              </div>
              <div className="symbol bold">+</div>
              <div
                className="statistics_uint active_uint"
              >
                <img src={ffsb} alt=""/>
                <div className="uint_info">
                  <p>发放失败总额</p>
                  <p className="bold">{this.state.totalInfo.failTotalAmount}</p>
                  <p>发放总笔数：{this.state.totalInfo.failTotalSize}</p>
                </div>
              </div>
              <div className="symbol bold">+</div>
              <div
                className="statistics_uint"
                onClick={() => {
                  this.props.history.push(`/finance/salary-proxy-complete?comGrantId=${gup('comGrantId')}`);
                }}
              >
                <img src={ffcg} alt=""/>
                <div className="uint_info">
                  <p>发放成功总额</p>
                  <p className="bold">{this.state.totalInfo.successTotalAmount}</p>
                  <p>发放总笔数：{this.state.totalInfo.successTotalSize}</p>
                </div>
              </div>
              <div className="symbol bold">=</div>
              <div
              className="statistics_uint"
              style={{
                cursor: 'default'
              }}
                // className={
                //   (() => {
                //     if (this.state.listStatus == 3) {
                //       return 'active_uint statistics_uint';
                //     }
                //     return 'statistics_uint';
                //   })()
                // }
                // onClick={() => {
                //   this.setState({
                //     listStatus: 3
                //   });
                // }}
              >
                <img src={ffze} alt=""/>
                <div className="uint_info">
                  <p>发放总额</p>
                  <p className="bold">{this.state.totalInfo.totalAmount}</p>
                  <p>发放总笔数：{this.state.totalInfo.totalSize}</p>
                </div>
              </div>
            </div>
          }

          <div className="proxy_btns_container">
            <div>
              <label style={{ marginRight: 16 }}>
                关键字：
                <Input
                  value={this.state.keyword}
                  style={{ width: '214px' }}
                  placeholder="姓名/手机号码"
                  onChange={(e) => {
                    this.setState({
                      keyword: e.target.value
                    });
                  }}
                  maxLength={20}
                />
              </label>
              <Button
                style={{
                  marginRight: '16px',
                  padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px'
                }}
                type="primary"
                onClick={() => {
                  const data = {
                    ...this.state.searchData,
                    keyword: this.state.keyword
                  };
                  this.setState({
                    searchData: data
                  }, () => {
                    this.getTable(data);
                  });
                }}
              >
                搜索
              </Button>
              <Button
                onClick={() => {
                  this.setState({
                    keyword: '',
                    searchData: {
                      ...this.state.searchData,
                      keyword: '',  //关键字
                      pageNumber: '1',  // 页	
                      pageSize: '10'  //条目
                    }
                  }, () => {
                    this.getTable(this.state.searchData);
                  });
                }}
                style={{
                  padding: window && window.innerWidth <= 1366 ? '0 10px' : '0 15px'
                }}
              >
                重置
              </Button>
            </div>
            <div className="operation_btns">
              {
                this.state.canAddData && 

                <Button
                  type="primary"
                  onClick={() => {
                    ajax.readySalaryGrantTotal({
                      comGrantId: gup('comGrantId')
                    }).then(response => {
                      if(response.data) {
                        const { cantGrantTotal, canGrantTotal } = response.data;
                        $modal(
                          `即将向${canGrantTotal}人发工资，是否继续？`,
                          (<span style={{color: '#FF9900'}}>{
                            `系统会逐单向每个人员发放工资，发放人数越多，发放时间越长，请耐心等待。`
                            // `其中有${cantGrantTotal}人未开通钱包，本次不向其发放工资。系统会逐单向每个人员发放工资，发放人数越多，发放时间越长，请耐心等待。`
                          }</span>),
                          [
                            {
                              text: '继续',
                              type: 'primary',
                              onPress: () => {
                                ajax.getCanGrant({
                                  comGrantId: gup('comGrantId')
                                }).then(res => {
                                  // 下一步
                                  if(res.data == 0) {
                                    /** 从获取企业钱包账户资料接口中获取手机号*/
                                    ajax.getComWalletAccount().then(result => {
                                      const mobilePhone = result.data.mobilePhone + '';
                                      const mobilePhoneStr = mobilePhone.slice(0, 3) + '****' + mobilePhone.slice(-4);
                                      /**获取到手机号以后请求验证码 */
                                      ajax.sendVerifyCode({
                                        mobilePhone,
                                        smsType: SMS_OP_TRANSFER
                                      }).then(data => {
                                        let activeCode = '';
                                        $modal(
                                          '已向企业结算手机号发送验证码！',
                                          (
                                            <div>
                                              <p>{`系统已向 ${mobilePhoneStr} 发送短信验证码，请将接收到的短信验证码输入下框并验证。`}</p>
                                              <Input onChange={e => {
                                                activeCode = e.target.value;
                                              }} placeholder="请输入短信验证码" />
                                            </div>
                                          ),
                                          [
                                            {
                                              text: '继续',
                                              type: 'primary',
                                              onPress: () => {
                                                ajax.reSalaryGrant({
                                                  comGrantId: gup('comGrantId'),
                                                  activeCode
                                                }).then(grantRes => {
                                                  $modal(
                                                    '已提交薪资代发！',
                                                    '请返回薪资代发列表，等待本次发放结束后，再查看发放结果。',
                                                    [
                                                      {
                                                        text: '返回薪资代发列表',
                                                        type: 'primary',
                                                        onPress: () => {

                                                        }
                                                      }
                                                    ],
                                                    'success'
                                                  );
                                                });
                                              }
                                            },
                                            {
                                              text: '返回'
                                            }
                                          ],
                                          'warning'
                                        );
                                      });
                                    });
                                    // 余额不足
                                  }else {
                                    const { toTotalAmount, availableAmount, spreadAmount } = res.data;
                                    $modal(
                                      '您当前账户余额不足，请先充值！',
                                      (
                                        <div>
                                          <p>代发总额: <span style={{marginLeft: 5}}>{`${toTotalAmount}`}</span></p>
                                          <p>钱包余额: <span style={{marginLeft: 5}}>{`${availableAmount}`}</span></p>
                                          <p>还需充值: <span style={{marginLeft: 5}}>{`${spreadAmount}`}</span></p>
                                        </div>
                                      ),
                                      [
                                        {
                                          text: '去充值',
                                          type: 'primary',
                                          onPress: () => {
                                            this.props.history.push('/finance/business-wallet');
                                          }
                                        },
                                        {
                                          text: '返回'
                                        }
                                      ],
                                      'error'
                                    );
                                  }
                                });
                              }
                            },
                            {
                              text: '取消'
                            }
                          ],
                          'warning'
                        );
                      }
                    });
                  }}
                >重新发放</Button>
              }
              <Button onClick={() => {
                if (this.state.operationList.length == 0) {
                  this.getOperationTable({
                    comGrantId: gup('comGrantId'),
                    pageNumber: '1',
                    pageSize: '10'
                  });
                }
                this.setState({
                  operationVisibale: true
                });
              }} type="default">操作记录</Button>
            </div>
          </div>
        </div>
        <div className="table_container">
          {this.renderOrderList()}
        </div>

        {/* 操作记录 */}
        <Modal
          title="操作记录"
          className="modal_on_footer"
          width={720}
          onCancel={() => {
            this.setState({
              operationVisibale: false
            });
          }}
          visible={this.state.operationVisibale}
        >
          {this.renderOperationList()}
        </Modal>
      </div>
    );
  }
}
