import React, { PureComponent } from "react";
import { connect } from "dva";
import { Icon, Select, DatePicker, Table } from "antd";
import moment from 'moment';
import styles from "./index.less";
import CartListComp from "@/components/MyAccList/index.js";
import { getCustomer } from '@/utils/request';
import { amountPrecision } from "@/utils/utils";
class CostReconcile extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            startTime: moment().format('YYYY-MM-01'),
            endTime: moment().format(),
            financialOrgChange: '',
            tabloading: false
        };
    }
    componentWillMount() {
        const { dispatch } = this.props;
        // 获取销售组织
        dispatch({
            type: 'myAccount/getsuppliersJurisdiction',
            payload: null
        }).finally(() => {
            // 获取财务组织
            const { organizations } = this.props;
            if (!organizations) return;
            const saleOrg = [];
            for (let i = 0; i < organizations.length; i++) {
                saleOrg.push(organizations[i].saleOrganizationId);
            }
            // dispatch({
            //     type: 'myAccount/getFinanorgsBySaleorgs',
            //     payload: saleOrg
            // }).finally(() => {
            //     const { finanorgsBySaleorgs } = this.props;
            //     let castAccount = null;
            //     if (finanorgsBySaleorgs && finanorgsBySaleorgs.length > 0) {
            //         castAccount = {
            //             search_GTE_billDate_date: moment(this.state.startTime).format('X') * 1000,
            //             search_LT_billDate_date: Date.parse(this.state.endTime),
            //             search_IN_financeOrg: finanorgsBySaleorgs[0].finanOrgId,
            //             search_IN_customer: getCustomer().id,
            //             page: 0,
            //             size: 10,
            //         };
            //         this.setState({
            //             financialOrgChange: finanorgsBySaleorgs[0].finanOrgId
            //         }, () => {
            //           this.search();
            //         });
            //     }
            // });
            dispatch({
                type: 'myAccount/getFinanorgsBySaleorgsDistinct',
                payload: saleOrg
            }).finally(() => {
                const { finanorgsBySaleorgsDistinct } = this.props;
                let castAccount = null;
                if (finanorgsBySaleorgsDistinct && finanorgsBySaleorgsDistinct.length > 0) {
                    castAccount = {
                        search_GTE_billDate_date: moment(this.state.startTime).format('X') * 1000,
                        search_LT_billDate_date: Date.parse(this.state.endTime),
                        search_IN_financeOrg: finanorgsBySaleorgsDistinct[0].finanOrgId,
                        search_IN_customer: getCustomer().id,
                        page: 0,
                        size: 10,
                    };
                    this.setState({
                        financialOrgChange: finanorgsBySaleorgsDistinct[0].finanOrgId
                    }, () => {
                      this.search();
                    });
                }
            });
        });
    }
    // 获取费用
    getCastAccount(data) {
        const { dispatch } = this.props;
        this.setState({
            tabloading: true
        });
        dispatch({
            type: 'myAccount/getCastAccount',
            payload: data
        }).finally(() => {
            this.setState({
                tabloading: false
            });
        });
    }

    pageChange(page = 0, pageSize = 10) {
        const { dispatch } = this.props;
        const searchConditions = {
            page: page,
            size: pageSize,
            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.financialOrgChange,
            search_IN_customer: getCustomer().id
        };
        dispatch({
            type: "myAccount/getCastAccount",
            payload: searchConditions
        });
    }
    // 时间change
    orderDateChange(dates, dateStrings) {
        this.setState({
            startTime: dateStrings[0],
            endTime: dateStrings[1]
        });
        const castAccount = {
            search_GTE_billDate_date: moment(dateStrings[0]).format('X') * 1000,
            search_LT_billDate_date: moment(dateStrings[1]).format('X') * 1000,
            search_IN_financeOrg: this.state.financialOrgChange,
            search_IN_customer: getCustomer().id
        };
        // 获取费用
        this.getCastAccount(castAccount);
    }
    search() {
      const castAccount = {
        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.financialOrgChange,
        search_IN_customer: getCustomer().id
      };
      // 获取费用
      this.getCastAccount(castAccount);
    }
    // 应收组织切换
    financialOrgChange(value) {
        this.setState({
            financialOrgChange: value
        });
        const castAccount = {
            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: value,
            search_IN_customer: getCustomer().id
        };
        // 获取费用
        this.getCastAccount(castAccount);
    }
    render() {
        const { castAccount, moduleKey, finanorgsBySaleorgsDistinct } = this.props;
        const castAmount = castAccount ? [{
            castIncre: castAccount.castIncre,
            castReduce: castAccount.castReduce,
            endBalance: castAccount.endBalance,                     // 期末
            openBalance: castAccount.openBalance,                   // 期初
            addGoodssuptCast: castAccount.addGoodssuptCast,         // 货补增加
            addOffsetCast: castAccount.addOffsetCast,               // 票扣增加
            reduceGoodssupt: castAccount.reduceGoodssupt,           // 货补减少
            reduceFlush: castAccount.reduceFlush                    // 冲抵减少
        }] : [];
        const financialOrg = finanorgsBySaleorgsDistinct ? finanorgsBySaleorgsDistinct : [];
        const dateFormat = 'YYYY-MM-DD';
        const columns = [
            {
                title: '初期费用余额',
                align: 'left',
                width: '130px',
                dataIndex: 'openBalance',
                key: 'openBalance',
                render: (text, record, index) => {
                    return (
                        <span>
                            <em className={styles.font16_e14}>{amountPrecision(record.openBalance)}</em>
                        </span>
                    );
                }
            },
            {
                title: '票扣费用额增加',
                align: 'right',
                width: '180px',
                dataIndex: 'addOffsetCast',
                key: 'addOffsetCast',
                render: (text, record, index) => {
                    return (
                        <span>
                            <em className={styles.font16_e14}>{amountPrecision(record.addOffsetCast)}</em>
                        </span>
                    );
                }
            },
            {
                title: '货补费用增加',
                align: 'right',
                width: '220px',
                dataIndex: 'addGoodssuptCast',
                key: 'addGoodssuptCast',
                render: (text, record, index) => {
                    return (
                        <span>
                            <em className={styles.font16_e14}>{amountPrecision(record.addGoodssuptCast)}</em>
                        </span>
                    );
                }
            },
            {
                title: '订单冲抵减少额',
                align: 'right',
                width: '200px',
                dataIndex: 'reduceFlush',
                key: 'reduceFlush',
                render: (text, record, index) => {
                    return (
                        <span>
                            <em className={styles.font16_e14}>{amountPrecision(record.reduceFlush)}</em>
                        </span>
                    );
                }
            },
            {
              title: '货补兑付减少额',
              align: 'right',
              width: '200px',
              dataIndex: 'reduceGoodssupt',
              key: 'reduceGoodssupt',
              render: (text, record, index) => {
                  return (
                      <span>
                          <em className={styles.font16_e14}>{amountPrecision(record.reduceGoodssupt)}</em>
                      </span>
                  );
              }
            },
            {
                title: '末期余额',
                align: 'right',
                className: 'pr210',
                dataIndex: 'endBalance',
                key: 'endBalance',
                render: (text, record, index) => {
                    return (
                        <span>
                            <em className={styles.font16_e14}>{amountPrecision(record.endBalance)}</em>
                        </span>
                    );
                }
            }
        ];
        // 财务组织
        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>
                );
            }
        };
        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 style={{ width: "305px", marginRight: '15px' }}>
                            <span className={styles.searchName} style={{ width: "70px" }}>费用对账日</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>
                {/* 余额 */}
                <div>
                    <Table
                      className={styles.customerTable}
                      columns={columns}
                      dataSource={castAmount}
                      pagination={false}
                    />
                </div>
                {/* 列表 */}
                <CartListComp goodsData={castAccount ? castAccount.results : {}} {...this.props} tabloading={this.state.tabloading} paginationChange={this.pageChange.bind(this)} moduleKey={moduleKey} />
                {/* 列表 结束 */}
            </div>
        );
    }
}


export default connect(state => ({
    castAccount: state.myAccount.castAccount,                       // 列表
    organizations: state.myAccount.suppliersJurisdiction,           // 组织参照
    // finanorgsBySaleorgs: state.myAccount.finanorgsBySaleorgs,       // 财务组织
    finanorgsBySaleorgsDistinct: state.myAccount.finanorgsBySaleorgsDistinct,       // 排重后财务组织
    moduleKey: 'CostReconcile'         // 区分模块
}))(CostReconcile);
