/**
 * 确认订单并支付
 */
import React, { Component } from "react";
import {
  Form,
  Tooltip,
  Button,
  Modal,
  message,
  Checkbox,
  Alert,
  Table,
  Input,
} from "antd";
import { withRouter } from "dva/router";
import "../../meeting.less";
import {
  checkProductCoupon,
  saveOrder,
  getPayPhone,
  sendPayVerifycode,
  checkOrder,
} from "../../../../services/api";
import { formatCurrency } from "../../../../utils/utils";
import { toUpper } from "lodash";
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 5 },
  },
  wrapperCol: {
    xs: { span: 12 },
    sm: { span: 13 },
  },
};
@Form.create()
@withRouter
export default class ConfirmOrder extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      mobilePhone: null, //企业钱包的手机号码
      mergeList: props.mergeList, //合并所有信息
      totalAmount: props.totalAmount, //总价
      actualTotalAmount: props.totalAmount, //应付
      discountWay: "", //优惠类型
      discountValue: "", //优惠金额
      couponsChecked: false, //是否选择了优惠卷
      couponsUsered: false,  //勾选了优惠卷是否确认使用
      coupons: "", //输入的优惠卷码
      sureCoupons: "", //最终确认使用的优惠卷码
      canPay: true, //应付金额是否大于总金额
      checkbox: false, //是否点击了同意按钮
      paymentStatus: false, //支付模态框状态
      verificationName: "获取验证码", //验证码按钮名称
      timer: null, // 验证码定时器
      time: 0, // 可发送验证码剩余时间
      activeCode: null, //输入的验证码值
      showReceivingAddress: false, //是否显示收货地址输入框（只有有硬件数据的时候，需要这个字段，osp需要存）
      deliveryAddress: null, //地址
    };
  }
  componentDidMount() {
    // this._getPayPhone();
    this.changeReceivingAddress(this.props.mergeList);
  }

  componentWillReceiveProps(nextProps) {
    //每次修改列表把所有和优惠卷相关的都重置
    this.setState({
      mergeList: nextProps.mergeList,
      totalAmount: nextProps.totalAmount,
      actualTotalAmount: nextProps.totalAmount,
    });
    if (this.state.couponsChecked) {
      if (this.state.discountWay!=='' && this.state.discountValue!=='') {
        let actualTotalAmount = nextProps.totalAmount
        this.setActualTotalAmount(actualTotalAmount)
        // switch (this.state.discountWay) {
        //   case "1":
        //     actualTotalAmount = actualTotalAmount - this.state.discountValue;
        //     if (actualTotalAmount <= 0) {
        //       console.log(actualTotalAmount)
        //       actualTotalAmount = 0
        //     }
        //     break;
        //   case "2":
        //     actualTotalAmount = this.state.discountValue;
        //     break;
        //   case "3":
        //     actualTotalAmount = actualTotalAmount * this.state.discountValue;
        //     break;
        // }
        this.setState({
          actualTotalAmount
        })
        if (actualTotalAmount > nextProps.totalAmount) {
          message.error("当前应付金额大于总金额，请更换优惠卷")
          this.setState({
            canPay: false
          })
        }
      }
    }
    //每次修改列表如果有硬件订单把所有和优惠卷相关的都重置
    let hasHardware = nextProps.mergeList.some(item=>item.productServiceType==="2" || item.productServiceType==="3")
    if(hasHardware){
      this.setState({
        actualTotalAmount: nextProps.totalAmount,
        discountWay: "",
      discountValue: "",
      couponsChecked: false,
      couponsUsered: "",
      coupons: "",
      sureCoupons: ""
      });
    }
    this.changeReceivingAddress(nextProps.mergeList);
  }
  //改变是否显示收货地址字段
  changeReceivingAddress(mergeList) {
    const showReceivingAddress =
      JSON.stringify(mergeList).indexOf('"productServiceType":"2"') > -1;
    this.setState({
      showReceivingAddress,
    });
  }
  //根据优惠卷获取应付金额
  setActualTotalAmount = (actualTotalAmount) => {
    let { coupons, totalAmount } = this.state;
    checkProductCoupon({ productCouponId: coupons, productCategoryType: 11 })
      .then(res => {
        switch (res.data.discountWay) {
          case "1":
            actualTotalAmount = totalAmount - res.data.discountValue;
            if (actualTotalAmount <= 0) {
              actualTotalAmount = 0
            }
            break;
          case "2":
            actualTotalAmount = res.data.discountValue;
            break;
          case "3":
            actualTotalAmount = totalAmount * res.data.discountValue;
            break;
        }
        this.setState({
          actualTotalAmount,
          canPay: true,
          discountWay: res.data.discountWay,
          discountValue: res.data.discountValue,
          couponsUsered: false,
          sureCoupons: coupons,
        })
        if (actualTotalAmount > totalAmount) {
          message.error("当前应付金额大于总金额，请更换优惠卷")
          this.setState({
            canPay: false
          })
        }
      })
      .catch(err => {
        this.setState({
          actualTotalAmount: this.state.totalAmount, //应付
          discountWay: "", //优惠类型
          discountValue: "",
        })
      })
  }
  /**
   * 先支付校验
   * 再获取支付手机号码
   * 再获取验证码
   * 再提交订单
   */
  //支付校验
  _checkOrder() {
    // this.props.form.validateFields((err, values) => {
    //   if (!err) {
    checkOrder({
      actualPayAmount: this.state.actualTotalAmount,
    }).then((res) => {
      if (res.retType === "0") {
        // this._saveOrder();
        this._getPayPhone();
      }
    });
    //   }
    // });
  }
  //获取企业钱包账户资料
  _getPayPhone() {
    getPayPhone({}).then((res) => {
      if (res.retType === "0") {
        this.setState({
          mobilePhone: res.data,
          paymentStatus: !this.state.paymentStatus,
        });
      }
    });
    // .catch(err => {
    //   if (err.retType === "-1") {
    //     message.warning(
    //       "您的企业尚未开通企业钱包，请访问【金融保险】-【金融钱包】-【企业钱包】免费在线开通。"
    //     );
    //   }
    // });
  }
  //确认提交订单
  _saveOrder() {
    this.props.form.validateFields((err, values) => {
      console.log(this.state.actualTotalAmount)
      if(!this.state.activeCode){
        return message.error("请输入短信验证码")
      }
      if (!err) {
        const data = {
          activeCode: this.state.activeCode,
          orderDetailListStr: JSON.stringify(this.state.mergeList),
          amount: this.state.totalAmount,
          actualPayAmount: this.state.actualTotalAmount,
          productCouponId: this.state.discountWay?this.state.sureCoupons:"",
          productCategoryType: 11,
        };
        console.log(this.state.deliveryAddress)
        if (this.state.showReceivingAddress) {
          data.deliveryAddress = this.state.deliveryAddress
        }
        console.log(data)
        saveOrder({
          ...data,
        }).then((res) => {
          // console.log(res);
          if (res.retType === "0") {
            this.setState({
              paymentStatus: !this.state.paymentStatus,
            });
            const _this = this;
            Modal.success({
              title: "支付成功！",
              content: (
                <p>
                  云会议资源购买订单支付后，系统将进行资源分配，预计1~2个工作日完成。
                </p>
              ),
              okText: "查看订单",
              onOk() {
                // _this.props.history.push("/meeting/resource");
                // _this.props.history.push({ pathname: "/meeting/buy-setMeal", state: '3' });
                _this.props.changeKeyTab("3");
              },
            });
          }
        });
      }
    });
  }
  render() {
    
    const { getFieldDecorator } = this.props.form;
    const { mergeList, totalAmount, mobilePhone, actualTotalAmount, coupons, couponsChecked } = this.state;
    const columns = [
      {
        title: "分类",
        dataIndex: "name",
        key: "name",
      },
      {
        title: "产品",
        dataIndex: "productName",
        key: "productName",
      },
      {
        title: "单价",
        dataIndex: "eachAmount",
        key: "eachAmount",
        render: (text, record) => {
          return (
            <span>
              {formatCurrency(text)}
              {record.unit}
            </span>
          );
        },
      },
      {
        title: "时长",
        dataIndex: "duration",
        key: "duration",
        render: (text, record) => {
          return (
            <span>
              {record.productBuyMode === "1"
                ? text + "月"
                : record.productBuyMode === "2"
                  ? text + "年"
                  : "---"}
            </span>
          );
        },
      },
      {
        title: "数量",
        dataIndex: "num",
        key: "num",
      },
      {
        title: "小计（元）",
        dataIndex: "amount",
        key: "amount",
        render: (text, recoed) => {
          return <span>{formatCurrency(text)}</span>;
        },
      },
    ];
    //如果订单包含productServiceType为2或3则不能使用优惠卷
    let hasHardware = mergeList.some(item=>item.productServiceType==="2" || item.productServiceType==="3")
    
    return (
      // <div className="resource-list">
      <div className="confirm-order">
        <Table
          columns={columns}
          dataSource={mergeList}
          pagination={false}
          rowKey={(record) => record.prodsuctBuyModeId}
          style={{ width: "80%", marginBottom: "20px" }}
        />
        {this.state.showReceivingAddress && (
          <div>
            <label style={{ display: "inline-block", marginRight: "16px" }}>
              <span style={{ color: "red" }}>*</span>收货地址：
              <Input
                style={{
                  width: "240px",
                  marginLeft: "16px",
                  marginBottom: "16px",
                }}
                placeholder="请填写收货地址"
                onChange={(e) => {
                  this.setState({
                    deliveryAddress: e.target.value.trim(),
                  });
                }}
                maxLength={100}
              />
            </label>
          </div>
        )}

        <div>
          <h2>
            总价：
            <span style={{ color: "#F59A23" }}>
              {formatCurrency(totalAmount)}
            </span>
            元
          </h2>
          <h2>
            应付：
            <span style={{ color: "#F59A23" }}>
              {actualTotalAmount === 0 ? 0 : formatCurrency(actualTotalAmount)}
            </span>
            元
          </h2>
          <div style={{ margin: "10px 0" }}>
            {
              hasHardware?
              <Checkbox checked={false}  disabled>
                使用优惠劵(该订单包含硬件设备及增值服务无法使用优惠券，请拆单购买)
              </Checkbox>:
              <Checkbox
              onChange={(e) => {
                console.log(e.target.checked)
                if (!e.target.checked) {
                  console.log(123)
                  this.setState({
                    actualTotalAmount: this.state.totalAmount,
                    coupons: "",
                    couponsUsered: false,
                    canPay: true,
                    couponsChecked: e.target.checked
                  });
                  return
                }
                this.setState({
                  couponsChecked: e.target.checked,
                  couponsUsered: true
                });
              }}
            >
              使用优惠劵
            </Checkbox>
            }
            {
              couponsChecked && hasHardware===false ?
                <>
                  <Input style={{ width: "200px", marginRight: "20px" }} placeholder="请输入优惠卷码" value={coupons}
                    onChange={(e) => {
                      let reg = /^[1-9]\d*$/;
                      if (!reg.test(e.target.value)) {
                        if (e.target.value === "") {
                          this.setState({
                            coupons: e.target.value,
                          })
                        }
                        return;
                      }
                      this.setState({
                        coupons: e.target.value,

                      });
                    }}
                  />
                  {
                    coupons ?
                      <Button onClick={()=>this.setActualTotalAmount(this.state.actualTotalAmount)} type="primary">确认</Button> :
                      <Button disabled type="primary">确认</Button>
                  }
                </> : ""
            }
          </div>
          <div style={{ margin: "10px 0" }}>
            <Checkbox
              onChange={(e) => {
                this.setState({
                  checkbox: e.target.checked,
                });
              }}
            >
              支付前请阅读并同意
            </Checkbox>
            <a
              href="https://wiki.baibaodun.cn/document/indexout?document_id=1475"
              target="_blank"
              rel="noopener noreferrer"
            >
              《百保盾云会议服务使用说明》
            </a>
          </div>
          {this.props.children}   {/* 上一步按钮 */}
          {this.state.checkbox && this.state.canPay && this.state.couponsUsered==false ? (
            <Button
              onClick={() => {
                if (this.state.mergeList.length > 0) {
                  if (this.state.showReceivingAddress && !this.state.deliveryAddress) {
                    return Modal.info({
                      title: '您购买了硬件设备，请留下您的收货地址！',
                      content: '',
                      okText: "知道了",
                    })
                  }
                  this._checkOrder();
                } else {
                  message.warn("您还未选择任何产品，无需支付");
                }
              }}
              disabled={!this.state.checkbox}
              type="primary"
            >
              企业钱包支付
            </Button>
          ) : (
              <Tooltip title="请先勾选支付协议">
                <Button disabled={true}>企业钱包支付</Button>
              </Tooltip>
            )}
        </div>
        <Modal
          title="企业钱包支付"
          visible={this.state.paymentStatus}
          onOk={() => {
            this._saveOrder();
          }}
          onCancel={() => {
            // clearInterval(this.state.timer);
            this.setState(
              {
                paymentStatus: !this.state.paymentStatus,
                // verificationName: "获取验证码",
                // timer: null
              }
              // () => {
              //   this.setState({
              //     time: 0
              //   });
              // }
            );
            this.props.form.resetFields();
          }}
        >
          <Alert
            message={
              <div style={{ color: "#333" }}>
                <span>
                  购买云会议资源，当前仅支持企业钱包支付，请提前充值购买资金到企业钱包中；
                  下单支付完成后，需等待系统配置资源，预计1~2个工作日后生效。
                </span>
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: "15px" }}
          />
          <div>
            <Form>
              <Form.Item {...formItemLayout} label="绑定手机号">
                {getFieldDecorator("mobilePhone", {
                  // initialValue: this.state.mobilePhone,
                  // rules: [{ required: true, message: "请输入绑定手机号" }]
                })(
                  <div>
                    <Input
                      placeholder={mobilePhone}
                      style={{ width: "140px", marginRight: "10px" }}
                      disabled
                    />
                    <Button
                      type="primary"
                      disabled={this.state.time > 0}
                      onClick={() => {
                        let { time, timer } = this.state;
                        if (time > 0) return;
                        if (timer) clearInterval(timer);
                        if (!mobilePhone || !/^\d{11}$/.test(mobilePhone)) {
                          return message.error({
                            message: "系统没有获取到手机号",
                          });
                        }
                        //发送验证码
                        sendPayVerifycode({}).then((res) => {
                          time = 59;
                          this.setState({
                            verificationName: `重试(${time}s)`,
                            time,
                          });
                          timer = setInterval(() => {
                            time -= 1;
                            if (time > 0) {
                              this.setState({
                                time,
                                verificationName: `重试(${time}s)`,
                                timer,
                              });
                            } else {
                              clearInterval(timer);
                              this.setState(
                                {
                                  verificationName: "获取验证码",
                                  timer: null,
                                },
                                () => {
                                  this.setState({
                                    time: 0,
                                  });
                                }
                              );
                            }
                          }, 1000);
                        });
                      }}
                    >
                      {this.state.verificationName}
                    </Button>
                  </div>
                )}
              </Form.Item>
              {/* <Form.Item {...formItemLayout} label="短信验证码">
                {getFieldDecorator("activeCode", {
                  rules: [{ required: true, message: "请输入短信验证码" }],
                })( */}
                <label style={{paddingLeft:'15px'}}><span style={{color:'red'}}>*</span>短信验证码：</label>
                  <Input
                    placeholder="请输入验证码"
                    style={{ width: "50%" }}
                    onChange={e => {
                      this.setState({
                        activeCode: e.target.value
                      });
                    }}
                  />
                {/* )}
              </Form.Item> */}
            </Form>

          </div>
        </Modal>
      </div>
    );
  }
}
