import React, { PureComponent } from "react";
import
  {
    Select, Row, Col, DatePicker, Input, Spin,
    Button, Icon, Popconfirm, Table, message, notification
  } from "antd";
import { connect } from "dva";
import { Link, routerRedux } from "dva/router";
import OrderListDialog from "@/components/OrderListDialog/index";
import moment from "moment";
import styles from "./index.less";
import { getDefaultCurrency, getCustomer } from "@/utils/request.js";
import { amountPrecision } from '@/utils/utils';

class PaymentNoticeEdit extends PureComponent {
  constructor(props) {
    super(props);
    const { location } = this.props;
    const query = location[`query`];
    this.columns = [
      {
        title: '订单编号',
        dataIndex: 'orderCode',
        key: 'orderCode',
        width: "33%",
        render: text => <span href="#">{text}</span>,
      },
      {
        title: '订单金额',
        dataIndex: 'money',
        key: 'money',
        className: "alignRight",
        width: "33%",
        render: text => <span href="#">{amountPrecision(text, "amount")}</span>,
      },
      // {
      //   title: '付款银行账户',
      //   dataIndex: 'payAccount',
      //   key: 'payAccount',
      //   render: text => <span href="#">{text}</span>,
      // }, {
      //   title: '收款银行账户',
      //   dataIndex: 'receiptAccount',
      //   key: 'receiptAccount',
      //   render: text => <span href="#">{text}</span>,
      // },
      {
        title: '操作',
        key: 'action',
        className: `alignCenter ${query && query.type == "detail" ? "hidden" : ""}`,
        width: "33%",
        render: (text, record) => (
          <div className={styles.operation}>
            <span onClick={this.delItemHandle.bind(this, record)}>删除</span>
          </div>
        ),
      }
    ];
    this.state = {
      loading: false,
      operationType: query && query.type ? query.type : "",
      claimTime: Date.now(),
      payAccountId: "", // 付款方
      payAccountAccountName: "",
      payAccountAccountNumber: "", // 付款方账号
      saleOrgId: "", // 供应商
      financeOrgId: "", // 收款方（财务组织）
      receiptAccountId: "", // 收款方账户
      billreceiptTypeId: "", // 收付款业务类型
      settleMethodId: "", // 结算方式
      productLineId: "",  // 产品线
      currencyName: getDefaultCurrency().name || "", // 币种名称
      money: 1
    };
  }
  componentWillMount() {
    const { dispatch, location } = this.props;
    // 防止有历史数据，先清空信息
    dispatch({
      type: "paymentNotice/paymentNoticeData",
      paymentNoticeData: null
    });
    dispatch({
      type: "paymentNotice/returnPaymentNoticeData",
      returnPaymentNoticeData: null
    });
    dispatch({
      type: "paymentNotice/billclaimDetailDto",
      billclaimDetailDto: []
    });
    const query = location[`query`];
    // 编辑 或 查看明细
    if (query && query.id && query.type) {
      dispatch({
        type: "paymentNotice/getPaymentNoticeById",
        payload: {
          id: query.id
        }
      }).finally(() => {
        const { paymentNoticeData } = this.props;
        if (paymentNoticeData && paymentNoticeData.id) {
          // 编辑时，如有
          if (paymentNoticeData.saleOrgId && paymentNoticeData.financeOrgId) {
            const saleOrg = [];
            saleOrg.push(paymentNoticeData.saleOrgId);
            dispatch({
              type: "paymentNotice/getFinanorgsBySaleorgData",
              payload: saleOrg
            });
            if (paymentNoticeData.receiptAccountId) {
              dispatch({
                type: "paymentNotice/getEnterpriseAccountsData",
                payload: {
                  "search_EQ_financeOrganization.id": paymentNoticeData.financeOrgId,
                  search_EQ_isEnable: 1,
                  size: 100,
                  page: 0,
                }
              });
            }
          }
          this.setState({
            payAccountId: paymentNoticeData.payAccountId, // 付款方
            payAccountAccountName: paymentNoticeData.payAccountAccountName,
            payAccountAccountNumber: paymentNoticeData.payAccountAccountNumber, // 付款方账号
            saleOrgId: paymentNoticeData.saleOrgId, // 供应商
            financeOrgId: paymentNoticeData.financeOrgId, // 收款方（财务组织）
            receiptAccountId: paymentNoticeData.receiptAccountId, // 收款方账户
            billreceiptTypeId: paymentNoticeData.billreceiptType, // 收付款业务类型
            settleMethodId: paymentNoticeData.settleMethodId, // 结算方式
            productLineId: paymentNoticeData.productLineId,  // 产品线
            money: paymentNoticeData.money
          });
          const billclaimDetailDto = paymentNoticeData.billclaimDetailDto;
          if (billclaimDetailDto && billclaimDetailDto.length > 0) {
            const newBillclaimDetailDto = billclaimDetailDto.filter(item => !!item.orderCode);
            dispatch({
              type: "paymentNotice/billclaimDetailDto",
              billclaimDetailDto: newBillclaimDetailDto
            });
          }
        }
      });
    }
  }
  componentDidMount() {
    const { dispatch } = this.props;
    // 获取付款方
    dispatch({
      type: "paymentNotice/getPayAccountData",
      payload: null
    });
    // 获取供应商
    dispatch({
      type: "paymentNotice/getSupplierData",
      payload: null
    });
    // 获取收款业务类型
    dispatch({
      type: "paymentNotice/getBillreceiptTypeData",
      payload: {
        search_EQ_isEnable: 1,
        page: 0,
        size: 100
      }
    });
    // 获取结算方式
    dispatch({
      type: "paymentNotice/getSettlementData",
      payload: null
    });
  }
  addItemsInfo(selectedRows) {
    const { billclaimDetailDto, dispatch } = this.props;
    let newBillclaimDetailDto = [];
    if (typeof billclaimDetailDto == "object") {
      newBillclaimDetailDto = billclaimDetailDto.concat([]);
    }
    // 判断添加的表体行是否重复
    selectedRows.forEach(addRow => {
      let repeat = false;
      newBillclaimDetailDto.forEach(item => {
        if (item.orderCode == addRow.orderCode) {
          repeat = true;
        }
      });
      if (!repeat) {
        const newAddRow = Object.assign({}, addRow);
        newAddRow.money = newAddRow.totalDealAmount;
        newAddRow.id = "";
        newBillclaimDetailDto = newBillclaimDetailDto.concat(newAddRow);
      }
    });
    dispatch({
      type: "paymentNotice/billclaimDetailDto",
      billclaimDetailDto: newBillclaimDetailDto
    });
    this.sumItemAmount(this.state.money, newBillclaimDetailDto);
  }
  cancelHandle() {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: "/buyer/paymentNoticeList",
      })
    );
  }
  delItemHandle(record) {
    const { billclaimDetailDto, dispatch } = this.props;
    const newBillclaimDetailDto = billclaimDetailDto.filter(item => item.orderCode != record.orderCode);
    dispatch({
      type: "paymentNotice/billclaimDetailDto",
      billclaimDetailDto: newBillclaimDetailDto
    });
    this.sumItemAmount(this.state.money, newBillclaimDetailDto);
  }
  saveHandle(type) {
    const { dispatch, paymentNoticeData = {}, billclaimDetailDto } = this.props;
    const {
      claimTime,
      payAccountId,
      payAccountAccountName,
      saleOrgId,
      financeOrgId,
      receiptAccountId,
      billreceiptTypeId,
      settleMethodId,
      productLineId,
      money
    } = this.state;
    const postData = {
      claimTime: claimTime,
      payAccountId: payAccountId, // 付款方
      payAccountAccountName: payAccountAccountName,
      saleOrgId: saleOrgId, // 供应商
      financeOrgId: financeOrgId,
      customerId: getCustomer().id,
      receiptAccountId: receiptAccountId, // 收款方账户
      // billreceiptTypeId: billreceiptTypeId, // 收付款业务类型
      billreceiptType: billreceiptTypeId,
      settleMethodId: settleMethodId, // 结算方式
      productLineId: productLineId,  // 产品线
      currencyId: getDefaultCurrency().id || "", // 币种
      money: money,
      cliamState: 1,
      dealObject: "1",
      claimFrom: "PORTAL",
      billClaimState: type == "submit" ? 2 : 7
    };
    // 表体数据处理
    let newBillclaimDetailDto = [];
    if (billclaimDetailDto && billclaimDetailDto.length > 0) {
      newBillclaimDetailDto = billclaimDetailDto.concat([]);
    }
    const sum = newBillclaimDetailDto.reduce((total, curr) => {
      return total + parseFloat(curr.money);
    }, 0);
    if (money < sum) {
      message.error("付款金额不能小于关联订单的合计金额！");
      return false;
    } else if (money > sum) {
      const newRow = {
        id: "",
        money: money - sum
      };
      newBillclaimDetailDto.push(newRow);
    }
    newBillclaimDetailDto.forEach((item, index) => {
      item.serialnum = `${index + 1}0`;
      item.persistStatus = item.id ? "upd" : "new";
      item.payAccountId = payAccountId;
      item.payAccountAccountName = payAccountAccountName,
      item.receiptAccountId = receiptAccountId;
      item.billreceiptTypeId = billreceiptTypeId;
      item.saleOrgId = saleOrgId;
      item.financeOrgId = financeOrgId;
      item.customerId = getCustomer().id;
      item.settleMethodId = settleMethodId,
      item.currencyId = getDefaultCurrency().id || "";
    });
    // 表头数据处理
    const newPaymentNoticeData = Object.assign({}, paymentNoticeData, postData);
    newPaymentNoticeData.billclaimDetailDto = newBillclaimDetailDto;
    // 表头状态标识
    if (newPaymentNoticeData.id) {
      newPaymentNoticeData.persistStatus = "upd";
    } else {
      newPaymentNoticeData.persistStatus = "new";
    }
    const msg = this.validSaveData(newPaymentNoticeData);
    if (msg) {
      message.error(msg);
      return false;
    }
    this.setState({
      loading: true
    });
    dispatch({
      type: "paymentNotice/savePaymentNotice",
      payload: newPaymentNoticeData
    }).finally(() => {
      this.setState({
        loading: false
      });
      const { dispatch, returnPaymentNoticeData } = this.props;
      if (returnPaymentNoticeData && returnPaymentNoticeData.id) {
        notification.success({
          message: type == "submit" ? "提交成功" : "保存成功",
          description: `付款单登记号为：${returnPaymentNoticeData.code},2秒后跳转到付款单登记列表页`,
          duration: 2
        });
        setTimeout(() => {
          dispatch(routerRedux.push("/buyer/paymentNoticeList"));
        }, 2000);
      } else {
        notification.error({
          message: type == "submit" ? "提交失败" : "保存失败",
          description: `保存失败：${returnPaymentNoticeData.message || ""}`,
          duration: 2
        });
      }
    });
  }
  validSaveData(data) {
    let msg = "";
    if (!data.saleOrgId) {
      msg += "供应商不能为空！";
    }
    if (parseFloat(data.money || "0") < 0) {
      msg += "付款金额不能小于0！";
    }
    return msg;
  }
  // 日期改变
  dateChange(field, date, datestring) {
    this.setState({
      [`${field}`]: datestring
    });
  }
  // 下拉框值改变
  selectChange(field, value) {
    this.setState({
      [`${field}`]: value
    });
    // 付款方发生变化时，自动带出付款方账号
    if (field == "payAccountId" && value) {
      this.payAccountLinkEvent(value);
    }
    // 供应商发生变化时，联动事件
    if (field == "saleOrgId" && value) {
      this.saleOrgLinkEvent(value);
    }
    // 收款方（财务组织)变化时，联动事件
    if (field == "financeOrgId" && value) {
      this.financeOrgLinkEvent(value);
    }
  }
  // 付款方发生变化时，自动带出付款方账号
  payAccountLinkEvent(value) {
    const { payAccountData } = this.props;
    if (payAccountData && value) {
      const findData = payAccountData.find(item => item.id == value);
      if (findData && findData.accountNumber) {
        this.setState({
          payAccountAccountNumber: findData.accountNumber
        });
      }
    }
  }
  // 供应商发生变化时，联动事件
  saleOrgLinkEvent(value) {
    const { dispatch } = this.props;
    // 先清空收款方（财务组织）、收款账号信息，表体信息
    dispatch({
      type: "paymentNotice/finanorgsBySaleorgData",
      finanorgsBySaleorgData: []
    });
    dispatch({
      type: "paymentNotice/receiptAccountData",
      receiptAccountData: []
    });
    dispatch({
      type: "paymentNotice/billclaimDetailDto",
      billclaimDetailDto: []
    });
    this.setState({
      financeOrgId: "",
      receiptAccountId: ""
    });
    // 根据供应商联查收款方（财务组织）
    const saleOrg = [];
    saleOrg.push(value);
    dispatch({
      type: "paymentNotice/getFinanorgsBySaleorgData",
      payload: saleOrg
    });
  }
  // 收款方（财务组织)变化时，联动事件
  financeOrgLinkEvent(value) {
    const { dispatch } = this.props;
    dispatch({
      type: "paymentNotice/receiptAccountData",
      receiptAccountData: []
    });
    this.setState({
      receiptAccountId: ""
    });
    // 根据收款方（财务组织）查询收款银行账号（企业银行账户）
    dispatch({
      type: "paymentNotice/getEnterpriseAccountsData",
      payload: {
        "search_EQ_financeOrganization.id": value,
        search_EQ_isEnable: 1,
        size: 100,
        page: 0,
      }
    });
  }
  // 字段值改变
  fieldChange(field, e) {
    this.setState({
      [`${field}`]: e.target.value
    });
  }
  // 金额发生变化
  moneyChange(e) {
    const { billclaimDetailDto } = this.props;
    this.sumItemAmount(e.target.value, billclaimDetailDto, true);
  }
  sumItemAmount(money, items, ifTip) {
    const account = parseFloat(money || "1");
    let sum = 0;
    if (items && items.length > 0) {
      sum = items.reduce((total, curr) => {
        return total + parseFloat(curr.money);
      }, 0);
    }
    if (account >= sum) {
      this.setState({
        money: ifTip ? account : sum
      });
    } else {
      if (ifTip) {
        message.error("付款金额不能小于关联订单的合计金额！");
      }
      this.setState({
        money: sum
      });
    }
  }
  showOrderDialog() {
    const { saleOrgId, payAccountId, receiptAccountId, payAccountAccountName } = this.state;
    // if (!saleOrgId) {
    //   message.info("请先维护供应商！");
    //   return false;
    // }
    // if (!payAccountAccountName) {
    //   message.info("请先维护付款方账号！");
    //   return false;
    // }
    // todo...
    // if (!payAccountId) {
    //   message.info("请先维护付款方账号！");
    //   return false;
    // }
    // if (!receiptAccountId) {
    //   message.info("请先维护收款方账号！");
    //   return false;
    // }
    this.props.dispatch({
      type: "global/orderListVisible",
      payload: true
    });
  }
  render() {
    let { paymentNoticeData } = this.props;
    const { payAccountAccountNumber } = this.state;
    paymentNoticeData = paymentNoticeData || {};
    const disabledDate = current => {
      return current && current.valueOf() <= Date.now() - 86400000;
    };
    // 拼接下拉框选项
    const selectOptionHtml = listData => {
      if (!listData||!listData[0] || listData.length < 1) return null;
      const optionHtmls = listData.map(item => (
        <Select.Option key={item.id} value={item.id}>
          {item.name}
        </Select.Option>
      ));
      return optionHtmls;
    };
    const iptDisabled = true;
    const pagination = false;
    const columns = this.columns;
    return (
      <div className={styles.paymentNoticeBox}>
        <Spin spinning={this.state.loading}>
          <div className={styles.paymentHeadBox}>
            <div className={styles.paymentItemBox}>
              <div className={styles.paymentItem}>
                <Row gutter={16}>
                  <Col span={6}>
                    <span className={styles.label}>付款单编号：</span>
                    <Input
                      className={styles.iptBox}
                      style={{ width: "180px" }}
                      value={paymentNoticeData.code || ""}
                      disabled={iptDisabled}
                    />
                  </Col>
                  <Col span={6}>
                    <span className={styles.label}>付款单日期：</span>
                    <DatePicker
                      className={styles.datePickerBox}
                      value={moment(this.state.claimTime)}
                      disabledDate={disabledDate}
                      onChange={this.dateChange.bind(this)}
                    />
                  </Col>
                  <Col span={12}>
                  </Col>
                </Row>
              </div>
            </div>
            <div className={styles.paymentItemBox}>
              <p className={styles.paymentItemBoxTitle}>付款方信息</p>
              <div className={styles.paymentItem}>
                <Row gutter={16}>
                  {/* todo... */}
                  <Col span={24}>
                    <span className={styles.label}>付款方账号：</span>
                    <Input
                      className={styles.iptLongBox}
                      value={this.state.payAccountAccountName}
                      onChange={this.fieldChange.bind(this, "payAccountAccountName")}
                    />
                  </Col>
                  {/* <Col span={6}>
                    <span className={styles.label}>付款方：</span>
                    <Select
                      className={styles.selectBox}
                      value={this.state.payAccountId}
                      onChange={this.selectChange.bind(this, "payAccountId")}
                    >
                      {selectOptionHtml(this.props.payAccountData)}
                    </Select>
                  </Col>
                  <Col span={18}>
                    <span className={styles.label}>付款方账号：</span>
                    <Input
                      className={styles.iptLongBox}
                      value={this.state.payAccountAccountNumber}
                      disabled={iptDisabled}
                    />
                  </Col> */}
                </Row>
              </div>
            </div>
            <div className={styles.paymentItemBox}>
              <p className={styles.paymentItemBoxTitle}>收款方信息</p>
              <div className={styles.paymentItem}>
                <Row gutter={16}>
                  <Col span={6}>
                    <span className={styles.label}>供应商：</span>
                    <Select
                      className={styles.selectBox}
                      value={this.state.saleOrgId}
                      onChange={this.selectChange.bind(this, "saleOrgId")}
                    >
                      {selectOptionHtml(this.props.supplierData)}
                    </Select>
                  </Col>
                  <Col span={6}>
                    <span className={styles.label}>收款方：</span>
                    <Select
                      className={styles.selectBox}
                      value={this.state.financeOrgId}
                      onChange={this.selectChange.bind(this, "financeOrgId")}
                    >
                      {selectOptionHtml(this.props.finanorgsBySaleorgData)}
                    </Select>
                  </Col>
                  <Col span={12}>
                  <span className={styles.label}>收款方账号：</span>
                    <Select
                      className={styles.selectLongBox}
                      value={this.state.receiptAccountId}
                      onChange={this.selectChange.bind(this, "receiptAccountId")}
                    >
                      {selectOptionHtml(this.props.receiptAccountData)}
                    </Select>
                  </Col>
                </Row>
              </div>
            </div>
            <div className={styles.paymentItemBox}>
              <p className={styles.paymentItemBoxTitle}>付款业务信息</p>
              <div className={styles.paymentItem}>
                <Row gutter={16}>
                  <Col span={6}>
                    <span className={styles.label}>收款业务类型：</span>
                    <Select
                      className={styles.selectBox}
                      value={this.state.billreceiptTypeId}
                      onChange={this.selectChange.bind(this, "billreceiptTypeId")}
                    >
                      {selectOptionHtml(this.props.billreceiptTypeData)}
                    </Select>
                  </Col>
                  <Col span={6}>
                    <span className={styles.label}>结算方式：</span>
                    <Select
                      className={styles.selectBox}
                      value={this.state.settleMethodId}
                      onChange={this.selectChange.bind(this, "settleMethodId")}
                    >
                      {selectOptionHtml(this.props.settlementData)}
                    </Select>
                  </Col>
                  {/* <Col span={6}>
                    <span className={styles.label}>产品线：</span>
                    <Select
                      className={styles.selectBox}
                      value={this.state.productLineId}
                      onChange={this.selectChange.bind(this, "productLineId")}
                    >
                      {selectOptionHtml(productLineData)}
                    </Select>
                  </Col> */}
                  <Col span={12}>
                    <span className={styles.label}>付款币种：</span>
                    <span>{paymentNoticeData.currencyName || this.state.currencyName}</span>
                  </Col>
                </Row>
                <Row>
                <Col span={24} style={{ marginTop: "15px" }}>
                    <span className={`${styles.label} ${styles.labelWeight}`}>付款金额：</span>
                    <Input
                      className={styles.iptBox}
                      placeholder="请输入付款金额"
                      value={parseFloat(this.state.money || 1).toFixed(getDefaultCurrency().currencyAmountScale)}
                      onChange={this.fieldChange.bind(this, "money")}
                      onBlur={this.moneyChange.bind(this)}
                    />
                </Col>
                </Row>
              </div>
            </div>
          </div>
          <div className={styles.paymentBodyBox}>
            <div className={styles.paymentItemBox} style={{ display: this.state.operationType == "detail" ? "none" : "block" }}>
              <Button
                className={styles.addOrderBtn}
                onClick={this.showOrderDialog.bind(this)}
              >
                <Icon type="plus" className={styles.icon} />添加关联订单
              </Button>
            </div>
            <div className={styles.paymentItemBox}>
              <Table
                style={{ width: "95%" }}
                columns={columns}
                dataSource={this.props.billclaimDetailDto}
                pagination={pagination}
              />
            </div>
          </div>
          <div className={styles.paymentFooterBox}>
            <div className={styles.paymentItemBox} style={{ display: this.state.operationType == "detail" ? "none" : "block" }}>
              <Popconfirm
                title="是否确定取消？"
                onConfirm={this.cancelHandle.bind(this)}
              >
                <Button className={styles.btn}>取消</Button>
              </Popconfirm>
              <Button
                className={styles.btn}
                onClick={this.saveHandle.bind(this, "save")}
              >
                暂存
              </Button>
              <Button
                className={styles.btn}
                onClick={this.saveHandle.bind(this, "submit")}
              >
                提交
              </Button>
            </div>
            <div className={styles.paymentItemBox} style={{ display: this.state.operationType == "detail" ? "block" : "none" }}>
              <Button
                className={styles.btn}
                onClick={this.cancelHandle.bind(this)}
              >
                返回
              </Button>
            </div>
          </div>
        </Spin>
        <OrderListDialog
          title="请选择关联订单"
          saleOrgId={this.state.saleOrgId} 
          currencyId={getDefaultCurrency().id}
          onConfirm={this.addItemsInfo.bind(this)}
        />
      </div>
    );
  }
}

export default connect(state => ({
  paymentNoticeData: state.paymentNotice.paymentNoticeData,
  payAccountData: state.paymentNotice.payAccountData,
  supplierData: state.paymentNotice.supplierData,
  finanorgsBySaleorgData: state.paymentNotice.finanorgsBySaleorgData,
  receiptAccountData: state.paymentNotice.receiptAccountData,
  billreceiptTypeData: state.paymentNotice.billreceiptTypeData,
  settlementData: state.paymentNotice.settlementData,
  productLineData: state.paymentNotice.productLineData,
  billclaimDetailDto: state.paymentNotice.billclaimDetailDto,
  returnPaymentNoticeData: state.paymentNotice.returnPaymentNoticeData
}))(PaymentNoticeEdit);
