import React, { PureComponent } from "react";
import { connect } from "dva";
import { Icon, Checkbox, Select, Input, DatePicker, Radio, Button } from "antd";
import moment from 'moment';
import styles from "./index.less";
import CartListComp from "@/components/MyAccList/index.js";
import { getCustomer } from "@/utils/request";
class Cost extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            startTime: moment().format('YYYY-MM-01'),
            endTime: moment().format(),
            financialOrg: '',
            saleOrgChange: '',
            billStatus: '',
            billCode: '',
            paymentMethod: '',
            tabloading: false
        };
    }
    componentWillMount() {
      this.setState({
        tabloading: true
      });
    }
    componentDidMount() {
        const { dispatch } = this.props;
        this.pageChange(0, 10);
        // 获取销售组织
        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',
            //     payload: saleOrg
            // }).finally(() => {
            //     const { finanorgsBySaleorgs } = this.props;
            //     if (finanorgsBySaleorgs || finanorgsBySaleorgs.length > 0) {
            //         this.getSumCastBalance(finanorgsBySaleorgs[0].finanOrgId);
            //         this.setState({
            //           financialOrg: finanorgsBySaleorgs[0].finanOrgId
            //         });
            //     } else {
            //         this.getSumCastBalance();
            //     }
            // });
            //使用财务组织去重后的方法
            dispatch({
                // type: 'myAccount/getFinanorgsBySaleorgs',
                type: 'myAccount/getFinanorgsBySaleorgsDistinct',
                payload: saleOrg
            }).finally(() => {
                const { finanorgsBySaleorgsDistinct } = this.props;
                if (finanorgsBySaleorgsDistinct || finanorgsBySaleorgsDistinct.length > 0) {
                    this.getSumCastBalance(finanorgsBySaleorgsDistinct[0].finanOrgId);
                    this.setState({
                      financialOrg: finanorgsBySaleorgsDistinct[0].finanOrgId
                    });
                } else {
                    this.getSumCastBalance();
                }
            });
        });
        // 获取状态
        dispatch({
            type: 'myAccount/getCustDocDefs',
            payload: {
                'search_EQ_custDoc.id': "63cabe5c-1184-4e42-b506-a8c8806bccbd",
                search_EQ_isEnable: 1
            }
        });
        // 获取兑付方式
        dispatch({
            type: 'myAccount/getPaymentType',
            payload: {
                'search_EQ_custDoc.id': "7ddbcd90-8080-4be9-a6f2-df143e62b083",
                search_EQ_isEnable: 1
            }
        });
    }
    getSumCastBalance(value) {
        const { dispatch } = this.props;
        const searchData = {
            search_GTE_billDate_date: moment(this.state.startTime).format('X') * 1000,
            search_LT_billDate_date: Date.parse(this.state.endTime),
            search_EQ_financeOrg: this.state.financialOrg || value,
            search_EQ_customer: getCustomer().id
        };
        dispatch({
            type: 'myAccount/getSumCastBalance',
            payload: searchData
        });
    }
    pageChange(page = 0, pageSize = 10) {
        this.setState({
            tabloading: true
        }, () => {
          this.search(page, pageSize);
        });
    }
    // 时间change
    orderDateChange(dates, dateStrings) {
        this.setState({
            startTime: dateStrings[0],
            endTime: dateStrings[1]
        });
    }
    // 状态
    billStatusChange(value) {
        this.setState({
            billStatus: value,
        });
    }
    // 方式
    paymentMethod(value) {
        this.setState({
            paymentMethod: value,
        });
    }
    // 搜索
    searchBtn(value) {
        const { dispatch } = this.props;
        this.setState({
            billCode: value,
            tabloading: true
        }, () => {
          this.search();
        });
    }
    // 应收组织切换
    financialOrgChange(value) {
        this.setState({
            financialOrg: value,
            tabloading: true
        }, () => {
          this.search();
        });
    }
    search(page = 0, pageSize = 10) {
      const { dispatch } = this.props;
      const searchData = {
        page: page || 0,
        pageSize: pageSize || 10,
        search_GTE_billDate_date: moment(this.state.startTime).format('X') * 1000,
        search_LT_billDate_date: moment(this.state.endTime).format('X') * 1000,
        search_IN_financeOrg: this.state.financialOrg,
        search_IN_saleOrg: this.state.saleOrgChange,
        search_EQ_billStatus: this.state.billStatus,
        search_EQ_billCode: this.state.billCode,
        search_EQ_billType: this.state.paymentMethod,
        search_EQ_customer: getCustomer().id
      };
      dispatch({
          type: 'myAccount/getCastBalance',
          payload: searchData
      }).finally(() => {
          this.getSumCastBalance();
          this.setState({
              tabloading: false
          });
      });
    }
    // 销售组织切换
    saleOrgChange(value) {
        const { dispatch } = this.props;
        this.setState({
          saleOrgChange: value,
            tabloading: true,
        }, () => {
          this.search();
        });
    }
    render() {
        const {
            moduleKey,
            organizations,              // 销售组织
            sumCastBalance,
            custDocDefs,
            paymentType,
            sumCastFlushdetail,
            castBalance,
            // finanorgsBySaleorgs         // 财务组织
            finanorgsBySaleorgsDistinct         // 财务组织去重
        } = this.props;
        // 余额
        const piaokou = sumCastBalance ? sumCastBalance.票扣余额 ? sumCastBalance.票扣余额 : '0.00' : '0.00';
        const huobu = sumCastBalance ? sumCastBalance.货补余额 ? sumCastBalance.货补余额 : '0.00' : '0.00';
        const dateFormat = 'YYYY-MM-DD';
        let saleOrg = [], financialOrg = [];
        saleOrg = organizations ? organizations : [];
        // financialOrg = finanorgsBySaleorgs ? finanorgsBySaleorgs : [];
        financialOrg = finanorgsBySaleorgsDistinct ? finanorgsBySaleorgsDistinct : [];
        // 财务组织
        const financialOrgHtml = () => {
            if (financialOrg.length > 0) {
                return (
                    <Select
                      onChange={this.financialOrgChange.bind(this)}
                      defaultValue={financialOrg[0].finanOrgName}
                      style={{ width: 220, height: 28 }}
                    >
                        {financialOrg.map(data => {
                            return (
                            <Select.Option value={data.finanOrgId} key={data.finanOrgCode}>{data.finanOrgName}</Select.Option>
                            );
                        })}
                    </Select>
                );
            }
        };
        if (saleOrg && saleOrg.length > 0) {
            // 销售组织
            if (saleOrg[0].saleOrganizationName != "全部") {
                saleOrg.unshift({
                    saleOrganizationCode: '',
                    saleOrganizationId: '',
                    saleOrganizationName: '全部'
                });
            }
        }
        // 状态
        let custDocDefsList = [];
        if (custDocDefs && custDocDefs.content && custDocDefs.content.length > 0) {
            custDocDefsList = custDocDefs.content;
            if (custDocDefsList.length > 0 && custDocDefsList[0].name != "全部") {
                custDocDefsList.unshift({
                    code: '',
                    id: '',
                    name: '全部'
                });
            }
        }
        // 兑付方式
        let paymentTypeList = [];
        if (paymentType && paymentType.content && paymentType.content.length > 0) {
            paymentTypeList = paymentType.content;
            if (paymentTypeList.length > 0 && paymentTypeList[0].name != "全部") {
                paymentTypeList.unshift({
                    code: '',
                    id: '',
                    name: '全部'
                });
            }
        }

        return (
            <div className={styles.cartListBox}>
                {/* <div className={styles.classHead}>
                    <span className={styles.nameIndex}>首页</span>
                    <span className={styles.nameChild}>
                        <Icon type="right" className={styles.nameIcon} />账户中心
                    </span>
                    <span className={styles.nameChild}>
                        <Icon type="right" className={styles.nameIcon} />费用余额
                    </span>
                </div> */}
                {/* 搜索项 */}
                <div className={styles.searchCotent}>
                    <div className={styles.searchBox}>
                        <div>
                            <span className={styles.searchName}>应收组织</span>
                            <Select
                              onChange={this.financialOrgChange.bind(this)}
                              defaultValue="全部"
                              style={{ width: 220, height: 28, display: financialOrg.length > 0 ? 'none' : '' }}
                            >
                            </Select>
                            {financialOrgHtml()}
                        </div>
                        <div>
                            <span className={styles.searchName}>状态</span>
                            <Select
                              onChange={this.billStatusChange.bind(this)}
                              defaultValue="全部"
                              style={{ width: 220, height: 28 }}
                            >
                                {custDocDefsList.map(data => {
                                    return (
                                    <Select.Option value={data.code} key={data.code}>{data.name}</Select.Option>
                                    );
                                })}
                            </Select>
                        </div>
                        <div style={{ width: "305px", marginRight: '15px' }}>
                            <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>
                    </div>
                    <div className={styles.searchBox} style={{ marginTop: "20px" }}>
                        <div>
                            <span className={styles.searchName}>销售组织</span>
                            <Select
                              onChange={this.saleOrgChange.bind(this)}
                              defaultValue="全部"
                              style={{ width: 220, height: 28 }}
                            >
                                {saleOrg.map(data => {
                                    return (
                                    <Select.Option value={data.saleOrganizationId} key={data.saleOrganizationCode}>{data.saleOrganizationName}</Select.Option>
                                    );
                                })}
                            </Select>
                        </div>
                        <div style={{ width: "290px", marginRight: '45px' }}>
                            <span className={styles.searchName}>冲抵方式</span>
                            <Select
                              onChange={this.paymentMethod.bind(this)}
                              defaultValue="全部"
                              style={{ width: 220, height: 28 }}
                            >
                                {paymentTypeList.map(data => {
                                    return (
                                    <Select.Option value={data.code} key={data.code}>{data.name}</Select.Option>
                                    );
                                })}
                            </Select>
                        </div>
                        <div>
                            <Input.Search
                              placeholder="请输入单号"
                              enterButton="搜索"
                              onSearch={this.searchBtn.bind(this)}
                              className={styles.searchBtn}
                              style={{ width: 290 }}
                            />
                        </div>
                    </div>
                </div>
                {/* 余额 */}
                <div className={styles.baiance}>
                    <p className={styles.dashed}></p>
                    <div className={styles.baianceBox}>
                        <div className={styles.baianceBoxLeft}>
                            <p className={styles.baiacneName}>票扣余额：</p>
                            <p className={styles.baiacneMoney}>￥ { piaokou } </p>
                        </div>
                        <div className={styles.baianceBoxRight}>
                            <p className={styles.baiacneName}>货补余额：</p>
                            <p className={styles.baiacneMoney}>￥ { huobu } </p>
                        </div>
                    </div>
                    <p className={styles.dashed} style={{ marginBottom: "25px" }}></p>
                </div>
                {/* 列表 */}
                <CartListComp goodsData={castBalance || {}} {...this.props} tabloading={this.state.tabloading} paginationChange={this.pageChange.bind(this)} moduleKey={moduleKey} />
                {/* 列表 结束 */}
            </div>
        );
    }
}


export default connect(state => ({
    organizations: state.myAccount.suppliersJurisdiction,           // 组织参照
    finanorgsBySaleorgs: state.myAccount.finanorgsBySaleorgs,       // 财务组织
    finanorgsBySaleorgsDistinct: state.myAccount.finanorgsBySaleorgsDistinct,       // 财务组织去重
    sumCastBalance: state.myAccount.sumCastBalance,                 // 货补余额、票扣余额
    custDocDefs: state.myAccount.custDocDefs,                       // 状态
    paymentType: state.myAccount.paymentType,                       // 兑付方式
    sumCastFlushdetail: state.myAccount.sumCastFlushdetail,         // 费用详情
    castBalance: state.myAccount.castBalance,                       // 费用
    moduleKey: 'Cost'         // 区分模块
}))(Cost);
