import React, { Component } from "react";
import { withRouter } from 'dva/router';
import { connect } from "dva";
import TabInfo from './TabInfo';
import Invoicedrawer from './Invoicedrawer';
import ReadDrawer from './ReadDrawer';
import styles from './detail.less';
import { gup } from '../../../utils/utils';
import $modal from '../../../utils/modal';
import {
  getBizInvoiceMakeInfo,
  getBizInvoiceInfo,
  // systemComVaseInfoGet,
  confirmBizInvoiceInfo,
  updateBizInvoiceTax
} from '../../../services/api';
import {
  Alert,
  Breadcrumb,
  Button,
  notification
} from "antd";

@connect(state => ({
  global: state.global
}))
@withRouter
export default class Messages extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      forceUpdate: false,
      pageParm: {
        pageSize: '10',
        pageNumber: '1'
      },
      comBizInvoiceId: gup('comBizInvoiceId'),
      info: null, //上部分表格信息内容
      makeInfo: null, //开票信息（查看抽屉内容）
      tableInit: false,
      confirmStatus: true, //我方是否已确认
      invoiceVisible: false, //设置发票
      invoicedrawerBtnDisable: false, //设置发票确定按钮的disable
      subFun: null,
      readDrawerVisibale: false,  //查看发票
    };
  }
  componentDidMount() {
    // test_api({"trackid":"1","videostate":0});
    this._initPageInfo();
  }
  _initPageInfo = async () => {
    const { comBizInvoiceId } = this.state;
    // 获取开票信息（查看抽屉内容）
    const makeInfoRes = await getBizInvoiceMakeInfo({ comBizInvoiceId });
    const makeInfo = makeInfoRes.data || null;
    // （1，纸质普票，2纸质专票，3电子发票）
    if (makeInfo) {
      let type = '';
      switch (makeInfo.bizInvoiceMakeType + '') {
        case '1':
          type = '纸质普票';
          break;
        case '2':
          type = '纸质专票';
          break;
        case '3':
          type = '电子发票';
      }
      let makeStatusStr = '';
      switch (makeInfo.makeStatus) {
        case '0':
          makeStatusStr = '未开票';
          break;
        case '1':
          makeStatusStr = '已开票';
          break;
        case '2':
          makeStatusStr = '开票中';
      }
      makeInfo.bizInvoiceMakeTypeStr = type;
      makeInfo.makeStatusStr = makeStatusStr;
    }
    // 获取发票详情信息
    const InvoiceInfo = await getBizInvoiceInfo({ comBizInvoiceId });
    // 通过id和状态来区分我方开票状态
    const {
      bizInvoiceType,
      // drawerComId, 
      // receiverComId, 
      drawerConfirm,
      receiverConfirm
    } = InvoiceInfo.data;
    this.setState({
      info: InvoiceInfo.data,
      makeInfo
    });
    // let { comId } = this.props.global.companyInfo;
    // // 获取到公司id
    // if (!comId) {
    //   const comInfo = await systemComVaseInfoGet({});
    //   comId = comInfo.data.comId;
    // }
    // // 我方是否已经确认  false为未确认 true为已确认
    let confirmStatus = true;
    // switch (comId) {
    //   // 我方为开票方
    //   case drawerComId:
    //     if (drawerConfirm == '1') {
    //       confirmStatus = true;
    //     }
    //     break;
    //   // 我方为收票方
    //   case receiverComId:
    //     if (receiverConfirm == '1') {
    //       confirmStatus = true;
    //     }
    // }
    switch (bizInvoiceType) {  //1我方开， 2我方收
      // 我方为开票方
      case '1':
        confirmStatus = drawerConfirm == '1';
        break;
      case '2':
        confirmStatus = receiverConfirm == '1';
    }
    this.setState({
      confirmStatus
    });
  }
  _closeInvoice = () => {
    this.setState({
      invoiceVisible: false
    });
  }
  render() {
    const { info, makeInfo } = this.state;
    return (
      <div style={{ padding: '0 15px' }}>
        <Breadcrumb style={{ padding: '15px 0' }}>
          <Breadcrumb.Item>
            <a href="javascript:void(0)" onClick={() => { this.props.history.goBack() }}>业务开票</a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>开票明细</Breadcrumb.Item>
        </Breadcrumb>
        <Alert
          message={<div>
            <span>
              1、系统汇总交易月份内发生的企业收入或支出的所有业务数据；
            </span><br />
            <span>
              2、开票方确认发票数据后，收票方才能确认；双方确认即表示已核对对账数据及开票数据；
            </span><br />
            <span>
              3、重新计算税额：若您调整了企业税额，可对未确认的开票明细重新计算税额。
            </span>
          </div>}
          type="warning"
          showIcon
          style={{ marginBottom: '15px' }}
        />

        {
          this.state.info &&
          <table className={styles.invoice_info_table}>
            <tbody>
              <tr>
                <td className={styles.label}>交易月份</td>
                <td>{info.bizMonths}</td>
                <td className={styles.label}>类型</td>
                <td>{
                  info.bizInvoiceType == 1 ?
                    <span>我方应开</span> :
                    <span>我方应收</span>
                }</td>
                <td className={styles.label}>开票方确认</td>
                <td>{
                  info.drawerConfirm == 0 ?
                    <span style={{ color: 'red' }}>未确认</span> :
                    <span style={{ color: 'green' }}>已确认</span>
                }</td>
                <td className={styles.label}>收票方确认</td>
                <td>{
                  info.receiverConfirm == 0 ?
                    <span style={{ color: 'red' }}>未确认</span> :
                    <span style={{ color: 'green' }}>已确认</span>
                }</td>
              </tr>
              <tr>
                <td className={styles.label}>购方名称</td>
                <td>{info.receiver}</td>
                <td className={styles.label}>税号</td>
                <td>{info.receiverTFN}</td>
                <td className={styles.label}>商品名称</td>
                <td colSpan={3}>{info.product}</td>
              </tr>
              <tr>
                <td className={styles.label}>商品数量</td>
                <td>{info.counts}</td>
                <td className={styles.label}>单位</td>
                <td>{info.spec}</td>
                <td className={styles.label}>单价（元）</td>
                <td>{Number(info.atSingleAmount).toFixed(6)}</td>
                <td className={styles.label}>金额（元）</td>
                <td>{Number(info.atAmount).toFixed(2)}</td>
              </tr>
              <tr>
                <td className={styles.label}>税率</td>
                <td>{info.taxRate + '%'}</td>
                <td className={styles.label}>税额（元）</td>
                <td>{Number(info.taxAmount).toFixed(2)}</td>
                <td className={styles.label}>价税合计（元）</td>
                <td>{Number(info.sumAmount).toFixed(2)}</td>
                <td className={styles.label}>
                  {
                    makeInfo && makeInfo.bizInvoiceMakeTypeStr &&
                    '发票类型'
                  }
                </td>
                <td>
                  {
                    makeInfo && makeInfo.bizInvoiceMakeTypeStr &&
                    <div>
                      <span>
                        {
                          `${makeInfo.bizInvoiceMakeTypeStr}(${makeInfo.makeStatusStr})`
                        }
                      </span>
                      <a style={{ marginLeft: 10 }} href="javascript:void(0)" onClick={() => {
                        this.setState({
                          readDrawerVisibale: true
                        });
                      }}>
                        开票信息
                      </a>
                    </div>
                  }
                </td>
              </tr>
            </tbody>
          </table>
        }
        <div className={styles.btn_wrap}>
          {/* 我方未确认的时候才能点击 */}
          <Button
            type="primary"
            size="small"
            disabled={this.state.confirmStatus}
            onClick={() => {
              const {
                bizInvoiceType, // 开票方： 1我方开
                drawerConfirm,  // 开票方确认： 1已确认
                // receiverConfirm   // 收票方：  1已确认
              } = info;
              // 我方为开票方
              if (bizInvoiceType == 1) {
                $modal(
                  '即将确认对账开票数据，确认后将无法撤销。',
                  '',
                  [
                    {
                      text: '继续',
                      type: 'primary',
                      onPress: () => {
                        const { comBizInvoiceId } = this.state;
                        confirmBizInvoiceInfo({ comBizInvoiceId }).then(res => {
                          this._initPageInfo();
                        });
                      }
                    },
                    {
                      text: '取消'
                    },
                  ]
                );
              } else { // 我方为收票方
                // 开票方是否已经确认
                if (drawerConfirm == 1) {  //已确认
                  this.setState({
                    invoiceVisible: true
                  });
                } else { //未确认
                  notification.warning({
                    message: '开票方未确认，无法确认。',
                  });
                }
              }
            }}
          >
            {this.state.confirmStatus ? '我方已确认' : '我方确认'}
          </Button>
          {
            // 我方应收的时候不展示计算税额的按钮
            this.state.info && this.state.info.bizInvoiceType == 1 &&
            <Button type="primary" size="small"
              disabled={this.state.confirmStatus}
              onClick={async () => {
                const { comBizInvoiceId } = this.state;
                // updateBizInvoiceTax({comBizInvoiceId}).then(res => {
                //   this._initPageInfo();
                // });
                const taxRes = await updateBizInvoiceTax({ comBizInvoiceId });
                if (taxRes.retType == 0) {
                  const InvoiceInfoRes = await getBizInvoiceInfo({ comBizInvoiceId });
                  notification.success({
                    message: taxRes.msg
                  });
                  this.setState({
                    info: InvoiceInfoRes.data
                  });
                }
              }}
            >重新计算税额</Button>
          }
        </div>
        <TabInfo comBizInvoiceId={this.state.comBizInvoiceId} />

        <Invoicedrawer
          comBizInvoiceId={this.state.comBizInvoiceId}
          visible={this.state.invoiceVisible}
          onClose={this._closeInvoice}
          onOk={(fun) => {
            this.setState({
              subFun: fun
            })
          }}
        >
          <Button onClick={this._closeInvoice} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button disabled={this.state.invoicedrawerBtnDisable} onClick={(e) => {
            this.setState({
              invoicedrawerBtnDisable: true
            });
            this.state.subFun && this.state.subFun(e, (value) => {
              this.setState({
                invoicedrawerBtnDisable: value
              });
            }, () => {
              this._initPageInfo();
              this.setState({
                invoiceVisible: false,
                invoicedrawerBtnDisable: false
              });
            });
          }} type="primary">
            确定
          </Button>
        </Invoicedrawer>

        <ReadDrawer
          comBizInvoiceId={this.state.comBizInvoiceId}
          invoiceInfo={makeInfo}
          bizInvoiceType={info ? info.bizInvoiceType : ''}
          visible={this.state.readDrawerVisibale}
          reload={this._initPageInfo}
          confirmStatus={this.state.confirmStatus}
          onClose={() => {
            this.setState({
              readDrawerVisibale: false
            });
          }}
        />
      </div>
    );
  }
}
