import React, { PureComponent } from "react";
import { connect } from "dva";
import { Link, routerRedux } from "dva/router";
import {
  Icon,
  Checkbox,
  Select,
  Input,
  DatePicker,
  Radio,
  Button,
  Tabs,
  Popconfirm,
  notification
} from "antd";
import moment from "moment";
import styles from "./index.less";
import CartListComp from "@/components/MyAccList/index.js";
class AccountBalance extends PureComponent {
  constructor(props) {
    super(props);
    const tabIndex =
      this.props.match.params && this.props.match.params.tabIndex;
    this.state = {
      tabIndex: tabIndex || 1,
      startTime: moment().format("YYYY-MM-01"),
      endTime: moment().format(),
      tabloading: false,
      financeOrgId: ""
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    // 清空付款通知单信息
    dispatch({
      type: "paymentNotice/paymentNoticeListData",
      paymentNoticeListData: []
    });
    // 获取组织
    dispatch({
      type: "myAccount/getsuppliersJurisdiction",
      payload: null
    }).finally(() => {
      // 获取财务组织
      const { organizations } = this.props;
      const saleOrg = [];
      for (let i = 0; i < organizations.length; i++) {
        if (organizations[i].saleOrganizationId) {
          saleOrg.push(organizations[i].saleOrganizationId);
        }
      }
      dispatch({
        // type: "myAccount/getFinanorgsBySaleorgs",
        type: "myAccount/getFinanorgsBySaleorgsDistinct",
        payload: saleOrg
      });
    });
    // 当前预付款余额
    this.AccountBalanceFn();
  }

  componentDidMount() {
    this.pageChange(0, 10, this.state.tabIndex);
  }

  // 当前预付款余额
  AccountBalanceFn(value) {
    const { dispatch } = this.props;
    dispatch({
      type: "myAccount/getAccountBalance",
      payload: {
        financeOrgId: value ? value : this.state.financeOrgId
      }
    });
  }
  pageChange(page = 0, pageSize = 10, key = 1) {
    const { dispatch } = this.props;
    const searchConditions = {
      page: page,
      size: pageSize
    };
    if (this.state.startTime && this.state.endTime) {
      searchConditions.search_GTE_creationTime_date = new Date(
        this.state.startTime
      ).getTime();
      searchConditions.search_LT_creationTime_date = new Date(
        this.state.endTime
      ).getTime();
    }
    if (key == 1) {
      // 查询余额变动
      dispatch({
        type: "myAccount/getAccountChange",
        payload: searchConditions
      }).finally(() => {
        this.setState({
          tabloading: false
        });
      });
    } else if (key == 3) {
      // 查询付款通知单
      dispatch({
        type: "paymentNotice/getPaymentNoticeListData",
        payload: searchConditions
      }).finally(() => {
        this.setState({
          tabloading: false
        });
      });
    }
  }
  // 组织切换
  financialOrgChange(value) {
    this.AccountBalanceFn(value);
  }
  // 时间change
  orderDateChange(dates, dateStrings) {
    this.state.startTime = dateStrings[0];
    this.state.endTime = dateStrings[1];
    this.setState({
      startTime: dateStrings[0],
      endTime: dateStrings[1]
    });
    this.pageChange(0, 10, this.state.tabIndex);
  }
  // tab
  tabsCallback(key) {
    this.pageChange(0, 10, key);
    this.setState({
      tabIndex: key
    });
  }
  // 操作付款单登记
  operationPaymentHandle(id, type) {
    const { dispatch } = this.props;
    // 删除 或 编辑
    if (type == "del" || type == "submit") {
      dispatch({
        type: "paymentNotice/operationPayment",
        payload: {
          id: id,
          type: type
        }
      }).finally(() => {
        const { operationResult } = this.props;
        if (
          operationResult &&
          operationResult.result &&
          operationResult.result == "Success"
        ) {
          notification.success({
            message: "提示",
            description: type == "submit" ? "提交成功" : "删除成功",
            duration: 2
          });
          // 刷新页面
          this.pageChange(0, 10, this.state.tabIndex);
        } else {
          notification.error({
            message: type == "submit" ? "提交失败" : "删除失败",
            description: `操作失败：${operationResult.message || ""}`,
            duration: 2
          });
        }
      });
    } else if (type == "edit" || type == "detail") {
      dispatch(
        routerRedux.push({
          pathname: "/buyer/paymentNoticeEdit",
          query: {
            id: id,
            type: type
          }
        })
      );
    }
  }
  render() {
    const {
      goodsData,
      organizations,
      accountBalance,
      accountChange,
      paymentNoticeListData,
      // finanorgsBySaleorgs,
      finanorgsBySaleorgsDistinct
    } = this.props;
    let moduleKey = this.props.moduleKey;
    const { tabloading, tabIndex } = this.state;
    let getButtons = record => {
      return null;
    };
    const getPaymentActionButton = record => {
      const status = record.billClaimState;
      if (status == "1" || status == "7" || status == "5") {
        return (
          <div className={styles.operationBox}>
            <Popconfirm
              title="确认删除付款单？"
              onConfirm={this.operationPaymentHandle.bind(
                this,
                record.id,
                "del"
              )}
            >
              <span className={styles.operationBtn}>删除</span>
            </Popconfirm>
            <span
              className={styles.operationBtn}
              onClick={this.operationPaymentHandle.bind(
                this,
                record.id,
                "edit"
              )}
            >
              编辑
            </span>
            <span
              className={styles.operationBtn}
              style={{ display: (status == "7" || status == "1") ? "inline-block" : "none" }}
              onClick={this.operationPaymentHandle.bind(
                this,
                record.id,
                "submit"
              )}
            >
              提交
            </span>
          </div>
        );
      } else if (status == "02") {
        return (
          <div className={styles.operationBox}>
            <span
              className={styles.operationBtn}
              onClick={this.operationPaymentHandle.bind(
                this,
                record.id,
                "detail"
              )}
            >
              查看
            </span>
          </div>
        );
      }
    };
    let tableData = accountChange;
    if (tabIndex == "3") {
      tableData = paymentNoticeListData;
      moduleKey = "PaymentNotice";
      getButtons = getPaymentActionButton;
    }
    const dateFormat = "YYYY-MM-DD";
    return (
      <div className={styles.cartListBox}>
        {/* 余额 */}
        <div className={styles.baiance}>
          <div className={styles.baianceBox}>
            <div className={styles.searchSelect}>
              <span className={styles.searchName}>应收组织</span>
              <Select
                onChange={this.financialOrgChange.bind(this)}
                defaultValue="全部"
                style={{ width: 260, height: 28 }}
              >
                {finanorgsBySaleorgsDistinct &&
                  finanorgsBySaleorgsDistinct.length &&
                  finanorgsBySaleorgsDistinct.map((data, index) => {
                    return (
                      <Select.Option
                        value={data.finanOrgId}
                        key={data.finanOrgId}
                      >
                        {data.finanOrgName}
                      </Select.Option>
                    );
                  })}
              </Select>
            </div>
            <div className={styles.baianceBoxLeft}>
              <p className={styles.baiacneName}>当前预付款余额：</p>
              <p className={styles.baiacneMoney}>￥{accountBalance}</p>
            </div>
            <div className={styles.conditionBtn}>
              {/* <Button>在线支付</Button> */}
              {/* <Link to="/buyer/paymentNoticeEdit">
                <Button>付款单登记</Button>
              </Link> */}
            </div>
          </div>
          <p className={styles.dashed} />
        </div>
        {/* teb菜单 */}
        <Tabs
          activeKey={this.state.tabIndex}
          onChange={this.tabsCallback.bind(this)}
          tabPosition="top"
          className={styles.tabsTabPane}
          tabBarGutter={0}
        >
          <Tabs.TabPane tab="余额变动明细" key="1" />
          {/* <Tabs.TabPane tab="在线支付记录" key="2" /> */}
          <Tabs.TabPane tab="付款登记记录" key="3" />
        </Tabs>
        <div className={styles.datePicker}>
          <span className={styles.searchName}>日期范围：</span>
          <DatePicker.RangePicker
            className={styles.searchData}
            onChange={this.orderDateChange.bind(this)}
            defaultValue={[
              moment(this.state.startTime, dateFormat),
              moment(this.state.endTime, dateFormat)
            ]}
            format={dateFormat}
          />
        </div>
        {/* 列表 */}
        <CartListComp
          goodsData={tableData}
          getButtons={getButtons}
          // {...this.props}
          pageChange={this.pageChange.bind(this)}
          moduleKey={moduleKey}
        />
        {/* 列表 结束 */}
      </div>
    );
  }
}

export default connect(state => ({
  goodsData: state.goodsPurchase.goodsData,
  organizations: state.myAccount.suppliersJurisdiction,
  // finanorgsBySaleorgs: state.myAccount.finanorgsBySaleorgs,
  finanorgsBySaleorgsDistinct: state.myAccount.finanorgsBySaleorgsDistinct,
  accountBalance: state.myAccount.accountBalance,
  accountChange: state.myAccount.accountChange,
  paymentNoticeListData: state.paymentNotice.paymentNoticeListData,
  operationResult: state.paymentNotice.operationResult,
  moduleKey: "AccountBalance" // 区分模块
}))(AccountBalance);
