import React, { Component } from 'react';
import st from 'styled-components';
import { connect } from 'dva';
import { withRouter } from 'dva/router';
import {
  Tabs,
  Alert,
  Input,
  Select,
  Button,
  Modal,
  Table,
  DatePicker,
  Upload,
  Icon,
  message,
  notification,
  Row,
  Col
} from 'antd';
import tablePage from '../../../../utils/hoc/tablePage';
import $nModal from '../../../../utils/modal/nModal';
import $modal from '../../../../utils/modal';
import $loading from '../../../../utils/loading';
import { gup } from '../../../../utils/utils';
import { formItemLayout1 } from '../../../../constants/formItemLayout';
// import ExcelButtonOline from "../../../../components/ExcelButtonOline";
import { taskComBhGrantImportOfflineGrantTemp, taskComBhGrantGetComBhGrantInfoById, taskComBhGrantExportOfflineGrantTemp, taskComBhGrantExportBankGrantTemp,taskComBhGrantGetBhGrantOperRecordList, taskComBhAccountGetComBhAccountAmount, taskComBhAccountGetComBhAccount, BhAccountSendVerifyCode, taskComBhGrantCommitGrantApply,taskComBhGrantSyncBhGrantResul,taskComBhGrantImportOfflineBankGrantTemp } from '../../../../services/api';
import {solveLackAccuracy} from '../../../../utils/utils';
import columnFun from './columns';
import moment from 'moment';

const { TabPane } = Tabs;
const { Option } = Select;
const warnColor = '#F59A23';
const okColor = '#4B7902';
const errColor = '#D9001B';

@connect(state => ({
  global: state.global
}))
@withRouter
@tablePage()
export default class SalaryProxyOnlineList extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      comBhGrantId: props.location.state.comBhGrantId,
      grantYears: props.location.state.grantYears,
      remark: props.location.state.remark,
      // comBhGrantId: gup('comBhGrantId'),

      baseInfo: {}, //基础信息

      importInfo: {}, //导入线下数据接口返回的详情
      accountInfo: {},//资金
    };
  }
  componentWillMount() {
  }

  componentDidMount() {
    this._getPageInfo()
    this._getAccountAmount()
    this._getAccountInfo()
  }
  _getPageInfo = () => {
    taskComBhGrantGetComBhGrantInfoById({ comBhGrantId: this.state.comBhGrantId }).then(res => {
      this.setState({ baseInfo: res.data });
    });
  }
  //获取渤海银行的信息
  _getAccountInfo() {
    taskComBhAccountGetComBhAccount().then(res => {
      this.setState({
        mobilePhone: res.data.mobilePhone,
        bankCardNo: res.data.bankCardNo,
        comName: res.data.comName
      })
    })
  }
  //获取账户余额
  _getAccountAmount() {
    taskComBhAccountGetComBhAccountAmount().then(res => {
      this.setState({ accountInfo: res.data });
    });
  }
  // 表格渲染
  _renderOrderList = (commitStatus,grantType) => {
    const columns = columnFun.call(this, commitStatus,grantType);
    const { PageTable, isInit } = this.props;
    if (!isInit) return;
    return (
      <PageTable
        // style={{ marginTop: 20 }}
        columns={columns}
        url="taskComBhGrantPageComBhGrantDetailList"
        // scroll={{ x: '1500px' }}
        pagination={{ showTotal: total => `总共 ${total} 条` }}
        dateChange={(data) => {
          this.setState({
            total: data.total
          });
        }}
      />
    );
  };

  render() {
    const { SearchForm, Form } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { importInfo, baseInfo, comBhGrantId } = this.state;
    return (
      <div style={{ padding: '0 24px' }}>
        <Tabs defaultActiveKey="1" onChange={() => { }}>
          <TabPane tab={"在线薪资代发申请"} key="1" forceRender>
            <Alert
              message={<div style={{ color: '#333' }}>
                <span>1、发放工资：发放前请确认发放人数、发放总额、企业发薪账户余额是否充足，若不足，请<a onClick={() => { }}>充值</a>；</span> <br />
                <span>2、未开通保安员证联名卡的员工，请提醒其在APP端尽快申请开通，否则无法向其发放工资;</span> <br />
                <span style={{color:'red'}}>3、薪资代发申请提交后，需当日登录<a style={{color:'#1890ff'}} onClick={() => {
                  $nModal({
                    footer: null,
                    content: (<div style={{ textAlign: 'center' }}>
                      <img style={{ margin: '0 auto', maxWidth: '100%' }} src={require('../qrcode.jpg')} />
                    </div>)
                  });
                }}>渤海银行微信小程序</a>进行确认付款，否则逾期会导致发放失败。</span>
              </div>}
              type="warning"
              showIcon
              style={{ marginBottom: '15px' }}
            />

            <FlexContainer>
              <SearchForm
              // arrange={values => {
              //   console.log(values)
              //   return values;
              // }}
              >
                <>
                  <Form.Item label="代发id" style={{ display: 'none' }}>
                    {getFieldDecorator('comBhGrantId', {
                      initialValue: comBhGrantId
                    })(
                      <Input disabled maxLength={100} style={{ width: 200 }} placeholder="请输入姓名/手机号码/身份证号" />
                    )}
                  </Form.Item>
                  <Form.Item label="关键字">
                    {getFieldDecorator('keyword', {
                      initialValue: ''
                    })(
                      <Input maxLength={100} style={{ width: 200 }} placeholder="姓名/手机号码/身份证号" />
                    )}
                  </Form.Item>
                </>
              </SearchForm>
              <Btns>
                {/* 待提交 */}
                {
                  baseInfo.commitStatus === '0' &&
                  <>
                    <Button
                      type="primary"
                      onClick={() => {
                        this.setState({ addModal: true, importInfo: {} });
                      }}
                    >
                      添加发放数据
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        console.log(this.state.accountInfo)
                        $modal(`即将向${this.state.total}人发工资，是否继续？`, '', [
                          {
                            text: '继续', type: 'primary', onPress: () => {
                              if (baseInfo.sumAmount > this.state.accountInfo.availableAmount) {
                                // 余额不足
                                $modal(
                                  '您当前账户余额不足，请先充值',
                                  <>
                                    发放总额:<span style={{ color: warnColor }}>{baseInfo.sumAmount}</span><br />
                                    可用余额:<span style={{ color: warnColor }}>{this.state.accountInfo.availableAmount}</span><br />
                                    还需充值:<span style={{ color: warnColor }}>{solveLackAccuracy(baseInfo.sumAmount,this.state.accountInfo.availableAmount)}</span><br />
                                  </>,
                                  [
                                    {
                                      text: '去充值', type: 'primary', onPress: () => {
                                        console.log('充值');
                                        this.props.history.push("/salarypayment/salary-account")
                                      }
                                    },
                                    { text: '返回' }
                                  ],
                                  'error'
                                );
                              } else {
                                // 余额充足
                                let inputValue = '';
                                let remark = this.state.remark
                                const DATA = {
                                  mobilePhone: this.state.mobilePhone,
                                  transCode: 'DFXZTZ',
                                  bankCardNo: this.state.bankCardNo,
                                  comName: this.state.comName,
                                };
                                const _this = this
                                BhAccountSendVerifyCode(DATA).then(res => {
                                  if (res.retType == '0') {
                                    $modal(
                                      '已向企业绑定手机号发送验证码！',
                                      <>
                                        <span style={{ color: warnColor }}>
                                          系统已向 {_this.state.mobilePhone} 发送短信验证码，请将接收到的短信验证码输入下框并验证。
                                    </span><br />
                                      <Row style={{marginBottom:'5px'}}>
                                        <Col span={5} style={{lineHeight:'32px'}}>
                                          验证码：
                                        </Col>
                                        <Col span={19}>
                                          <Input placeholder="请输入验证码" maxLength={10} onChange={(e) => {
                                              inputValue = e.target.value.trim();
                                            }} />
                                        </Col>
                                      </Row>
                                      <Row >
                                        <Col span={5} style={{lineHeight:'32px'}}>
                                          备注：
                                        </Col>
                                        <Col span={19}>
                                          <Input placeholder="请输入备注" maxLength={50} value={remark} disabled />  
                                        </Col>
                                      </Row>
                                      </>,
                                      [
                                        {
                                          text: '继续', type: 'primary', onPress: () => {
                                            const data = {
                                              comBhGrantId: _this.state.comBhGrantId,
                                              activeCode: inputValue,
                                              remark
                                            }
                                            taskComBhGrantCommitGrantApply(data).then(res => {
                                              if (res.retType == '0') {
                                                _this._getPageInfo()
                                                // 提交验证码inputValue
                                                $modal(
                                                  '已提交薪资代发！',
                                                  <span style={{ color: errColor }}>请务必今日内登录渤海银行微信小程序进行确认付款，否则逾期会导致交易失败。</span>,
                                                  [
                                                    {
                                                      text: '返回薪资代发列表', type: 'primary', onPress: () => {
                                                        this.props.history.goBack()
                                                      }
                                                    }
                                                  ],
                                                  'success'
                                                );
                                              }
                                            })
                                          }
                                        },
                                        { text: '返回' }
                                      ]
                                    );
                                  }
                                })
                              }
                            }
                          },
                          {
                            text: '返回', type: 'default'
                          }
                        ]);
                      }}
                      disabled={!this.state.total > 0}
                    >
                      提交发放申请
                    </Button>
                  </>
                }
                {/* 已提交且还没同步过信息了，执行同步操作 */}
                {
                  baseInfo.commitStatus === '1' && baseInfo.isSyncBankResult == "0" &&
                  <>
                    {
                      <Button type="primary" onClick={() => {
                        taskComBhGrantSyncBhGrantResul({ comBhGrantId: this.state.comBhGrantId }).then(res => {
                          if(res.retType=='0'){
                            this.props.updateTable();
                          }
                        });
                      }}>查询发放结果</Button>
                    }
                  </>
                }
                 {/* 已提交且同步了 */}
                 {
                  baseInfo.commitStatus === '1' && baseInfo.isSyncBankResult == "1" &&
                  <>
                    <Button type="primary" onClick={() => {
                      // taskComBhGrantGetBhBankReceiptFileUrl({ comBhGrantId: this.state.comBhGrantId }).then(res=>{
                      //   if(res.retType=='0'&&res.data){
                      //     window.open(res.data);
                      //   }else{
                      //     Modal.warn({
                      //     title: '暂无发放结果',
                      //     content: (
                      //       <span style={{ color: 'red' }}>请登录渤海银行微信小程序进行确认付款，确认后请等待20分钟再查询结果；若查询仍无结果请10分钟后再试。</span>
                      //     ),
                      //     okText: '知道了'
                      //   });
                      //   }
                      // })
                      if(baseInfo.bankReceiptFileUrl){
                        window.open(baseInfo.bankReceiptFileUrl);
                      }else{
                        Modal.warn({
                          title: '暂无回单可下载',
                          okText: '知道了'
                        });
                      }
                    }}>下载发放回单</Button>
                  </>
                }
                <Button onClick={() => {
                  const columns = [
                    {
                      title: '时间',
                      dataIndex: 'createTime',
                      key: 'createTime',
                    },
                    {
                      title: '操作人',
                      dataIndex: 'createUserName',
                      key: 'createUserName',
                    },
                    {
                      title: '操作功能',
                      dataIndex: 'operGrantFuncType',
                      key: 'operGrantFuncType',
                    },
                    {
                      title: '操作结果',
                      dataIndex: 'operResult',
                      key: 'operResult',
                    },
                  ];
                  taskComBhGrantGetBhGrantOperRecordList({ comBhGrantId }).then(res => {
                    const dataSource = res.data;
                    $nModal({
                      title: '操作记录',
                      footer: null,
                      width: 800,
                      content: (
                        <Table dataSource={dataSource} columns={columns} />
                      )
                    });
                  })
                }}>操作记录</Button>
                <Button onClick={this.props.history.goBack}>返回</Button>
              </Btns>
            </FlexContainer>

            <p style={{ marginTop: 15 }}>
              {
                baseInfo.commitStatus === '0' &&
                <>
                  <span style={{ color: warnColor }}>待提交</span>  |  总笔数：<SpanErr>{baseInfo.grantCount}</SpanErr>笔   |   发放总额：<SpanErr>{baseInfo.sumAmount}</SpanErr>元
                </>
              }
              {
                baseInfo.commitStatus === '1' &&
                <>
                  <span style={{ color: okColor }}>已提交</span>  |  总笔数：<SpanErr>{baseInfo.grantCount}</SpanErr>笔   |   发放总额：<SpanErr>{baseInfo.sumAmount}</SpanErr>元  |  成功笔数：<SpanErr>{baseInfo.grantCount}</SpanErr>笔数  |  成功总额：<SpanErr>{baseInfo.sumAmount}</SpanErr>元  |  失败笔数：<SpanErr>{baseInfo.failGrantCount}</SpanErr>笔数  |  失败总额：<SpanErr>{baseInfo.failSumAmount}</SpanErr>元
                </>
              }
            </p>
            {this._renderOrderList(baseInfo.commitStatus,baseInfo.grantType)}
          </TabPane>
        </Tabs>

        {
          this.state.addModal &&
          <Modal
            visible={this.state.addModal}
            title="添加发放数据"
            okText="确定"
            cancelText="取消"
            footer={null}
            // onOk={() => {

            // }}
            onCancel={() => { this.setState({ addModal: false }); }}
          >
            <Form.Item {...formItemLayout1} label="数据来源">
              {getFieldDecorator('source', {
                // initialValue: '',
                rules: [
                  {
                    required: true,
                    message: '请选择数据来源'
                  }
                ]
              })(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                >
                  <Option
                    value={`1`}
                  >
                    线下导入
                  </Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item {...formItemLayout1} label="发薪月份">
              {getFieldDecorator('grantYears', {
                initialValue: this.state.grantYears ? moment(this.state.grantYears, 'YYYY-MM') : null,
                rules: [
                  {
                    required: true,
                    message: '选择年月'
                  }
                ]
              })(
                <DatePicker.MonthPicker style={{ width: '100%' }} month placeholder="请选择" disabled={!!this.state.grantYears} />
              )}
            </Form.Item>
            <Form.Item {...formItemLayout1} label="线下数据文件">
              <a onClick={() => {
                //发放类型是保安员证联名卡
                let apiUrlUpload=taskComBhGrantExportOfflineGrantTemp
                let updateName ='薪资代发数据模板.xls'
                //发放内容是渤海银行
                if(baseInfo.grantType == '4'){
                  apiUrlUpload=taskComBhGrantExportBankGrantTemp
                  updateName='薪资代发(银行卡)模板.xls'
                }
                apiUrlUpload().then(res => {
                  if (!res) {
                    return;
                  }
                  let url = window.URL.createObjectURL(res.data);
                  let link = document.createElement('a');
                  link.style.display = 'none';
                  link.href = url;
                  link.setAttribute(
                    'download',
                    updateName
                  );
                  document.body.appendChild(link);
                  link.click();
                });
              }}>{ baseInfo.grantType=='4'?'《薪资代发(银行卡)模板》下载':'《薪资代发数据模板》下载' }</a>
            </Form.Item>
            <Form.Item {...formItemLayout1} label=" " colon={false}>
              <Upload
                showUploadList={false}
                style={{ display: 'inline-block' }}
                beforeUpload={(file) => {
                  let canUpload = true;
                  if (!(file.name + '').toLocaleLowerCase().match(/(\.xls)|(\.xlsx)/)) {
                    message.error(`请上传拓展名为.xls或.xlsx的文件!`);
                    canUpload = false;
                    return false;
                  }
                  if(file.size/1024/1024 > 1.5){
                    message.error('请上传小于1.5M文件!');
                    canUpload= false;
                  }
                  return canUpload;
                }}
                customRequest={({ file }) => {
                  this.props.form.validateFields((err, values) => {
                    if (err) return;
                    // 提交values
                    const grantYears = moment(values.grantYears).format('YYYY-MM');
                    // this.setState({ addModal: false });
                    const formData = new FormData();
                    formData.append('xfile', file);
                    formData.append('grantYears', grantYears);
                    formData.append('comBhGrantId', comBhGrantId);
                    $loading.open('文件导入中,请稍后。。。');
                    //发放类型是保安员证联名卡的上传文件
                    let apiUrlUpload=taskComBhGrantImportOfflineGrantTemp
                    //发放内容是渤海银行的上传文件
                    if(baseInfo.grantType=='4'){
                      apiUrlUpload=taskComBhGrantImportOfflineBankGrantTemp
                    }
                    apiUrlUpload(formData, false).then(res => {
                      $loading.close();
                      // message.success('上传成功');
                      this.setState({
                        addModal: false,
                        grantYears
                      });
                      this.props.updateTable();
                      this._getPageInfo();
                    }).catch(ex => {
                      $loading.close();
                      this.setState({
                        importInfo: ex
                      });
                    });
                  });
                }}
              >
                <Button
                  style={{ marginLeft: 10 }}
                >
                  <Icon type="upload" />上传文件
                </Button>
              </Upload>
              <p>
                支持扩展名：.xls|.xlsx
              </p>
              {
                importInfo.data &&
                <a style={{ color: errColor }} href={importInfo.data}>下载失败文件</a>
              }
            </Form.Item>
          </Modal>
        }
      </div>
    );
  }
}

const Btns = st.div`
  margin-top: 15px;
  button {
    margin-right: 15px;
    &:last-child{
      margin: 0;
    }
  }
`;
const FlexContainer = st.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  button {
    margin-right: 15px;
  }
`;
const SpanErr = st.div`
  color: ${errColor};
  display:inline-block
`;