import React, { Component } from "react";
import Taro from "@tarojs/taro";
import { View, Button, } from '@tarojs/components'
import { AtRadio, AtInput, AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui";
import { accountList } from '../../utils/tools/config';
import { creatOrder } from '../../utils/servers/servers';
import './index.less';

import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/radio.scss";

class Select extends Component {
  constructor(props) {
    super(props);
    this.state = {
      type: -1,
      other: "",
    };
  }

  componentDidMount() {
    const { type, other } = this.props
    this.setState({
      type,
      other
    })
  }

  handleChange(e) {
    this.setState({
      type: e
    })
  }

  onInputChange(e) {
    this.setState({
      other: e
    })
  }

  creatOrder() {
    const { prid, onClose } = this.props
    const { type, other, } = this.state
    creatOrder({
      prid,
      type,
      typeOther: other,
    }).then(v => {
      if (v.error.length === 0) {
        onClose()
        Taro.redirectTo({
          url: '/pages/drafts/index?id=' + v.data
        })
      } else {
        Taro.showToast({ title: v.error[0].message, icon: 'none' })
      }
    }).catch(() => {
      Taro.showToast({
        title: '系统错误,请稍后再试',
        icon: 'none'
      })
    })
  }


  render() {
    const { visible = "", onClose, noPost = false, onOk } = this.props
    const { type, other } = this.state
    return (
      <AtModal
        isOpened={visible != ""}
        closeOnClickOverlay={false}
      >
        <AtModalHeader>请选择报销类型</AtModalHeader>
        <AtModalContent>
          <View className="rlist">
            <AtRadio
              options={accountList}
              value={type}
              onClick={this.handleChange.bind(this)}
            />
            {type == 0 &&
              <AtInput
                name='other'
                type='text'
                placeholder='请填写明细'
                value={other}
                onChange={this.onInputChange.bind(this)}
              />}
          </View>
        </AtModalContent>
        <AtModalAction>
          <Button onClick={onClose}>取消</Button>
          <Button onClick={() => {
            if (type == -1) {
              Taro.showToast({
                title: '请选择报销费用类型',
                icon: 'none'
              })
            } else if (type == 0 && !other) {
              Taro.showToast({
                title: '请填写其他明细',
                icon: 'none'
              })
            } else {
              noPost
                ? this.creatOrder()
                : onOk(type, other)
            }
          }}>确定</Button>
        </AtModalAction>
      </AtModal>
    )
  }
}

export default Select;
