import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { ButtonGroup, Button, Card, Input, InputNumber, CardBody,
  Textarea, DatePicker, SelectField, MenuItem, FormField } from 'patd';
import { DashHead, DashTitle, DashBody, LabelItem, BillLabel, DashBack } from '../../../ui';
import service from '../../services/service';
import translator from '../../translate';
import classes from '../classes.scss';


const styles = {
  CardBody: {
    padding: '36px 24px',
  },
};
class Create extends Component {
  constructor(props) {
    super(props);
    this.state = {
      serviceName: '',
      description: '',
      type: 'Function',
      typeText: translator.Functions,
      elementary: 0,
      intermediate: 0,
      senior: 0,
      loading: false,
      beginTime: moment().format('YYYY-MM-DD'),
      end: moment().add(+7, 'day').format('YYYY-MM-DD'),
      errorText: {
        serviceName: '', description: '', beginTime: '', end: '', regPass: false,
      },
      price: { // 后台获取的费用信息
        junior: { id: '0', price: 0 },
        medium: { id: '0', price: 0 },
        senior: { id: '0', price: 0 },
      },
    };
  }

  componentDidMount() {
    this.listProductSpec4Cts();
  }

  // 获取费用信息
  listProductSpec4Cts=() => {
    service.listProductSpec4Cts().then((data) => {
      if (data && data.ProductSpec.length) {
        const price = {};
        for (const k of data.ProductSpec) {
          price[k.Name] = { id: k.Id, price: k.Price };
        }
        this.setState({ price });
      }
    });
  }


  // 计算总价
  sum=() => {
    const {
      elementary, intermediate, senior, price,
    } = this.state;
    const amount = (elementary * price.junior.price)
    + (intermediate * price.medium.price)
    + (senior * price.senior.price);
    return amount.toFixed(6);
  }
  changeName=(e) => {
    const value = e.target.value;
    this.checkError('serviceName', value);
    this.setState({ serviceName: value });
  }
  changeDesc=(e) => {
    const value = e.target.value;
    this.checkError('description', value);
    this.setState({ description: value });
  }

  changeManpower=(Manpower, v) => {
    this.setState({ [Manpower]: v }, () => {
      this.checkError('manpower');
    });
  }
  changTime=(time, value) => {
    this.setState({ [time]: moment(value).format('YYYY-MM-DD') });
    this.checkError(time, value);
  }

  // 检查校验规则
  checkError=(key, value) => {
    const { elementary, intermediate, senior } = this.state;
    const { errorText } = this.state;
    const reg = service.regular.serviceName;
    const isEmpty = /^\s*$/;
    errorText.regPass = true;
    errorText.manpowerCheck = true;
    if (key === 'serviceName') {
      errorText.serviceName = '';
      if (!reg.test(value)) {
        errorText.serviceName = translator.MaxLength;
      }
    } else if (key === 'description') {
      errorText.description = '';
      if (value.length > 300 || isEmpty.test(value)) {
        errorText.description = translator.MaxLength300;
      }
    } else if (key === 'beginTime') {
      const today = new Date(moment().format('YYYY-MM-DD')).getTime();
      const time = new Date(moment(value).format('YYYY-MM-DD')).getTime();
      const endTime = new Date(moment(this.state.end).format('YYYY-MM-DD')).getTime();
      errorText.beginTime = '';
      if (time < today) {
        errorText.beginTime = translator.TimeThanHH;
      }
      if (endTime < time) {
        errorText.end = translator.TimeThan;
      }
    } else if (key === 'end') {
      const beginTime = new Date(moment(this.state.beginTime).format('YYYY-MM-DD')).getTime();
      const time = new Date(moment(value).format('YYYY-MM-DD')).getTime();
      errorText.end = '';
      if (time < beginTime) {
        errorText.end = translator.TimeThan;
      }
    }


    const {
      serviceName, description, beginTime, end,
    } = errorText;
    if (serviceName !== '' || description !== '' || beginTime !== '' || end !== ''
      || this.state.serviceName === '' || this.state.description === '') {
      errorText.regPass = false;
    }

    if (
      elementary <= '0' && intermediate <= '0' && senior <= '0') {
      errorText.regPass = false;
    }
    this.setState({ errorText });
  }
  //  购买按钮触发
  create=() => {
    const {
      price, elementary, intermediate, senior,
    } = this.state;
    this.setState({ loading: true }); // 禁用按钮
    let opProductJsonStr = [];
    opProductJsonStr.push({
      productSpecId: price.junior.id,
      period: elementary,
    });

    opProductJsonStr.push({
      productSpecId: price.medium.id,
      period: intermediate,
    });

    opProductJsonStr.push({
      productSpecId: price.senior.id,
      period: senior,
    });


    opProductJsonStr = JSON.stringify(opProductJsonStr);
    const params = {
      testName: this.state.serviceName,
      testIllustration: this.state.description,
      testType: this.state.type,
      startDate: this.state.beginTime,
      endDate: this.state.end,
      opProductJsonStr,
    };
    service.createOrder4Cts(params).then((data) => {
      this.setState({ loading: false }); // 恢复按钮
      if (data.OrderId) {
        // 路由有两个，一个是分布式的router,还有一个是挂在window.pay下面
        // 如果如要跳转到其他产品则用window.pay下的router,否则条状会失败
        window.pay.router.push(`/console/payment/confirm/${data.OrderId}`);
      }
    });
  }

  render() {
    const {
      serviceName, description, type, elementary, typeText,
      intermediate, senior, beginTime, end, errorText, price,
    } = this.state;
    const payment = [{ key: 'case', text: translator['Per Case'] }];
    const typeList = [
      { key: 'Function', text: translator.Functions },
      { key: 'Performance', text: translator.Performance },
      { key: 'Stability', text: translator.Stability },
    ];
    return (
      <div>
        <DashHead>
          <DashBack to="/console/cloudTest/list" />
          <DashTitle>{translator['Create Cloud Test']}</DashTitle>
        </DashHead>
        <DashBody>
          {/* 下面这里在Panel之前用了一个DIV包起来加了panelBill,info,bill样式，
            创建页面如果不需要展示价格信息则不需要用该样式
          */}
          <div className={classes.panelBill}>
            {/* 左侧表单信息-待测项目说明 */}
            <div className={classes.info}>
              <Card title={translator.BasicInfo}>
                {/* 根据需求添加 PandeBody 默认是14的Padding,
                根据各个场景的不同可遵循设计规范以添加自定义样式 */}
                <CardBody style={{ padding: '36px 24px' }}>
                  {/* 表单项-服务名 */}
                  <LabelItem
                    title={translator['Service Name']}
                    alignItems="flex-start"
                    required
                  >
                    <FormField
                      errorText={errorText.serviceName}
                    >
                      <Input
                        value={serviceName}
                        onChange={this.changeName}
                        onBlur={(e) => {
                        const value = e.target.value;
                       this.checkError('serviceName', value);
                      }}
                      />
                    </FormField>

                  </LabelItem>
                  {/* 表单项-待测项目说明 */}
                  <LabelItem
                    title={translator.TestDescription}
                    required
                  >
                    <FormField errorText={errorText.description}>
                      <Textarea
                        style={{ width: 440 }}
                        resizeable={false}
                        value={description}
                        onChange={this.changeDesc}
                        onBlur={(e, value) => {
                        this.checkError('description', value);
                      }}
                        placeholder={translator.Description}
                      />
                    </FormField>
                  </LabelItem>
                  {/* 表单项 - 测试类型 */}
                  <LabelItem title={translator['Test Type']}>
                    <SelectField
                      value={type}
                      onChange={(e, index, value) => {
                       this.setState({ type: value, typeText: e.target.innerText });
                      }}
                    >
                      {
                      typeList.map(item => (
                        <MenuItem key={item.key} value={item.key} >
                          {item.text}
                        </MenuItem>
                      ))
                      }
                    </SelectField>
                  </LabelItem>
                  {/* 表单项-人力需求 */}
                  <LabelItem title={translator['Manpower Demandt']} required>
                    {/* 表单项-人力需-初级 */}
                    <LabelItem title={translator.Elementary}>
                      <div style={{ display: 'flex' }}>
                        <InputNumber
                          min={0}
                          value={elementary}
                          onChange={(v) => {
                           this.changeManpower('elementary', v);
                          }}

                        />
                        <div style={{ margin: 10 }}>{translator.People}</div>
                      </div>
                    </LabelItem>
                    {/* 表单项-人力需-中级 */}
                    <LabelItem title={translator.Intermediate}>
                      <div style={{ display: 'flex' }}>
                        <InputNumber
                          min={0}
                          value={intermediate}
                          onChange={(v) => {
                            this.changeManpower('intermediate', v);
                           }}
                        />
                        <div style={{ margin: 10 }}>{translator.People}</div>
                      </div>
                    </LabelItem>
                    {/* 表单项-人力需-高级 */}
                    <LabelItem title={translator.Senior}>
                      <div style={{ display: 'flex' }}>
                        <InputNumber
                          min={0}
                          value={senior}
                          onChange={(v) => {
                          this.changeManpower('senior', v);
                         }}
                        />
                        <div style={{ margin: 10 }}>{translator.People}</div>
                      </div>
                    </LabelItem>
                  </LabelItem>
                  {/* 表单项-'开始日期 */}
                  <LabelItem title={translator['Begin Time']}>
                    <DatePicker
                      style={{ margin: 0 }}
                      hintText={translator['Select Date']}
                      onChange={(value) => {
                        this.changTime('beginTime', value);
                      }}
                      value={new Date(beginTime)}
                    />
                    <div style={{ color: '#f57938', marginTop: '5px' }}>{errorText.beginTime}</div>
                  </LabelItem>

                  {/* 表单项-'结束日期 */}
                  <LabelItem title={translator['End Time']}>
                    <DatePicker
                      style={{ margin: 0 }}
                      hintText={translator['Select Date']}
                      onChange={(value) => {
                        this.changTime('end', value);
                      }}
                      value={new Date(end)}
                    />
                    <div style={{ color: '#f57938', marginTop: '5px' }}>{errorText.end}</div>
                  </LabelItem>
                  {/* 表单项-付费方式 */}


                  <LabelItem title={translator['Payment Method']}>
                    <ButtonGroup value="case">
                      {payment.map(data => <Button label={data.text} value={data.key} key={data.key} />)}
                    </ButtonGroup>
                  </LabelItem>


                </CardBody>
              </Card>
            </div>
            {/* 右侧结算信息-待测项目说明 */}
            <div className={classes.bill} >
              <Card title={translator.Bill} style={{ maxHeight: '100%' }}>
                {/* 右侧结算信息-服务名 */}
                <CardBody style={Object.assign({}, styles.CardBody, { overflowY: 'auto' })}>
                  <BillLabel
                    title={translator['Service Name']}
                  >
                    {serviceName}
                  </BillLabel>
                  {/* 右侧结算信息-测试类型 */}
                  <BillLabel title={translator['Test Type']}>
                    {typeText}
                  </BillLabel>
                  {/* 右侧结算信息-开始时间 */}
                  <BillLabel title={translator['Begin Time']}>
                    {beginTime}
                  </BillLabel>
                  {/* 右侧结算信息-结束时间 */}
                  <BillLabel title={translator['End Time']}>
                    {end}
                  </BillLabel>
                  {/* 右侧结算信息-付费方式 */}
                  <BillLabel title={translator['Payment Method']}>
                    {translator['Per Case']}
                  </BillLabel>
                  {/* 右侧结算信息-人力需求 */}
                  {/* 右侧结算信息-人力单价 */}
                  <BillLabel title={`${translator.Elementary}${translator.ManpowerPrice}`}>
                    {`￥ ${price.junior.price.toFixed(6)}/${translator.person}/${translator.Hour}`}
                  </BillLabel>
                  <BillLabel title={translator.Quantity}>
                    {elementary}
                  </BillLabel>
                  <BillLabel title={`${translator.Intermediate}${translator.ManpowerPrice}`}>
                    {`￥ ${price.medium.price.toFixed(6)}/${translator.person}/${translator.Hour}`}
                  </BillLabel>
                  <BillLabel title={translator.Quantity}>
                    {intermediate}
                  </BillLabel>
                  <BillLabel title={`${translator.Senior}${translator.ManpowerPrice}`}>
                    {`￥ ${price.senior.price.toFixed(6)}/${translator.person}/${translator.Hour}`}
                  </BillLabel>
                  <BillLabel title={translator.Quantity}>
                    {senior}
                  </BillLabel>
                </CardBody>
                <div
                  style={{ borderTop: '1px solid #e2e2e2', padding: '12px 24px 24px' }}
                >
                  {/* 右侧结算信息-总价 */}
                  <BillLabel
                    title={translator.Total}
                    total
                  >
                    {`￥ ${this.sum()}/${translator.Hour}`}
                  </BillLabel>

                  {/* 右侧结算信息-购买按钮 */}
                  <Button
                    label={translator.Purchase}
                    primary
                    style={{ width: '100%' }}
                    disabled={!errorText.regPass || this.state.loading}
                    onClick={this.create}
                  />
                </div>
              </Card>
            </div>
          </div>
        </DashBody>
      </div>
    );
  }
}


export default Create;
