import './index.less'
import {Component} from "react";
import {Dialog} from "tdesign-react";
import {isMobile, formValidate} from '@/js/utils/tool';
import CustomSelect from "@/js/components/Select";
import CustomInputNumber from '@/js/components/InputNumber';
import CustomInput from '@/js/components/Input';
import CustomButton from '@/js/components/Button';
import {ReactComponent as ResetSvg} from '@/assets/svg/trade/reset.svg';
import {ReactComponent as SubmitSvg} from '@/assets/svg/trade/submit.svg';
import {SpotTradeField} from '@/js/constants/trade';
import {show_message} from '@/js/utils/tdesign';
import {getLocalSpotHelperSelect, getLocalUserList, getLocalSymbolList} from '@/js/utils/local';
import {open_loading} from '@/js/utils/tdesign';
import {isShow} from '@/js/utils/dom';
import {SpotStrategy, SpotBatchOperation} from '@/js/utils/api/spot';

const users = 'user_ids';
const symbols = 'symbols';
export default class TradeDialog extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = {
            [users]: [],
            [symbols]: [],
            // 买卖类型
            [SpotTradeField.direction]: '',
            // 交易类型
            [SpotTradeField.order_type]: '',
            // 限价价格
            [SpotTradeField.limit_price]: '',

        }
        // 交易对列表
        this.symbolOptions = [];
        // 交易策略options
        this.strategyOptions = [];
        // 用户options
        this.userOptions = getLocalUserList(true, false);
        // 买卖类型options
        this.positionSideOptions = getLocalSpotHelperSelect('direction', false);
        // 订单类型options
        this.orderTypeOptions = getLocalSpotHelperSelect('order_type', false);
    }

    // 重置
    onReset = () => {
        const items = Object.keys(this.state);
        items.forEach((item: any) => {
            if (typeof this.state[item] === 'string') {
                this.setState({
                    [item]: ''
                })
            } else if (typeof this.state[item] === 'number') {
                this.setState({
                    [item]: 0,
                })
            } else {
                this.setState({
                    [item]: []
                })
            }

        })
    }

    // 提交
    onSubmit = async () => {
        // 必填项
        const requiredFields = [users, symbols, SpotTradeField.spot_strategy_id, SpotTradeField.direction, SpotTradeField.order_type];
        // 判断必填项是否为空
        const status = formValidate(requiredFields, this.state);
        if (!status) {
            show_message('请填写必填项');
            return;
        }
        // 限价单时，限价价格必填
        if (this.state[SpotTradeField.order_type] === 'LIMIT' && !this.state[SpotTradeField.limit_price]) {
            show_message('限价单价格必填');
            return;
        }
        let loading = null;
        try {
            // 现价交易提交
            loading = open_loading();
            const res: any = await SpotBatchOperation(this.state);
            if (res.code == 0) {
                show_message('提交成功', 'success');
                this.onClose();
            }
            if (loading) {
                loading.hide();
            }
        } catch (e) {
            console.log(e);
            if (loading) {
                loading.hide();
            }
        }
    }

    // 子组件的值变化
    onValueChange = (value: string | number | any[], name: string) => {
        if (name) {
            this.setState({
                [name]: value
            })
        }
    }

    getStrategy = async () => {
        try {
            const res: any = await SpotStrategy();
            if (res.code == 0) {
                this.strategyOptions = res.data;
            }
        } catch (e) {
            console.log(e)
        }
    }
    SymbolList = async () => {
        try {
            this.symbolOptions = await getLocalSymbolList();
        } catch (e) {
            console.log(e)
        }
    }

    componentDidMount() {
        // 获取交易策略
        this.getStrategy()
        // 获取交易对列表
        this.SymbolList();
    }

    onClose = () => {
        const {onClose} = this.props;
        if (onClose) {
            onClose();
        }
    }

    render() {
        const {visible} = this.props;
        const state = this.state;
        return (
            <Dialog visible={visible} placement={"center"} onClose={this.onClose} footer={false}
                    className={[isMobile() ? 'trade-dialog__mobile' : ''].join(' ')}>
                <div className='custom-trade-form'>
                    <div className='trade-form-item'>
                        <div className='trade-form-item__label required'>用户</div>
                        <div className='trade-form-item__value'>
                            <CustomSelect value={state[users]} name={users}
                                          options={this.userOptions}
                                          className={"trade-dialog-select"}
                                          clearable={true} multiple={true} autoWidth={false}
                                          popupProps={{
                                              overlayClassName: 'trade-dialog-select__overlay'
                                          }} onChange={this.onValueChange}></CustomSelect>
                        </div>
                    </div>
                    <div className='trade-form-item'>
                        <div className='trade-form-item__label required'>交易对</div>
                        <div className='trade-form-item__value'>
                            <CustomSelect value={state[symbols]} name={symbols}
                                          options={this.symbolOptions}
                                          filterable={true}
                                          className={"trade-dialog-select"}
                                          clearable={true} multiple={true} autoWidth={false}
                                          popupProps={{
                                              overlayClassName: 'trade-dialog-select__overlay'
                                          }} onChange={this.onValueChange}></CustomSelect>
                            {/*<CustomInput value={state[SpotTradeField.symbol]} name={SpotTradeField.symbol}*/}
                            {/*             align={'center'} type={"text"}*/}
                            {/*             onChange={this.onValueChange}>*/}
                            {/*</CustomInput>*/}
                        </div>
                    </div>
                    <div className='trade-form-item'>
                        <div className='trade-form-item__label'>策略</div>
                        <div className='trade-form-item__value'>
                            <CustomSelect value={state[SpotTradeField.spot_strategy_id]}
                                          name={SpotTradeField.spot_strategy_id} options={this.strategyOptions}
                                          className={"trade-dialog-select"}
                                          clearable={true} autoWidth={false}
                                          popupProps={{
                                              overlayClassName: 'trade-dialog-select__overlay'
                                          }} onChange={this.onValueChange}></CustomSelect>
                        </div>
                    </div>
                    <div className='trade-form-item'>
                        <div className='trade-form-item__label required'>买卖类型</div>
                        <div className='trade-form-item__value'>
                            <CustomSelect value={state[SpotTradeField.direction]}
                                          name={SpotTradeField.direction}
                                          options={this.positionSideOptions}
                                          className={"trade-dialog-select"}
                                          clearable={true} autoWidth={false}
                                          popupProps={{
                                              overlayClassName: 'trade-dialog-select__overlay'
                                          }} onChange={this.onValueChange}></CustomSelect>
                        </div>
                    </div>
                    <div className='trade-form-item'>
                        <div className='trade-form-item__label required'>交易类型</div>
                        <div className='trade-form-item__value'>
                            <CustomSelect value={state[SpotTradeField.order_type]}
                                          name={SpotTradeField.order_type} options={this.orderTypeOptions}
                                          className={"trade-dialog-select"}
                                          clearable={true} autoWidth={false}
                                          popupProps={{
                                              overlayClassName: 'trade-dialog-select__overlay'
                                          }} onChange={this.onValueChange}></CustomSelect>
                        </div>
                    </div>
                    <div className='trade-form-item' style={{
                        display: isShow(state[SpotTradeField.order_type] === 'LIMIT')
                    }}>
                        <div className='trade-form-item__label required'>限价价格</div>
                        <div className='trade-form-item__value'>
                            <CustomInput type={"number"} value={state[SpotTradeField.limit_price]} align={'center'}
                                         name={SpotTradeField.limit_price}
                                         onChange={this.onValueChange}></CustomInput>
                        </div>
                    </div>
                    <div className='trade-form-item'>
                        <div className='trade-form-item__value'>
                            <div className='trade-form-submit'>
                                <CustomButton icon={<ResetSvg/>} onClick={this.onReset}>重置</CustomButton>
                                <CustomButton icon={<SubmitSvg/>} onClick={this.onSubmit}>提交</CustomButton>
                            </div>
                        </div>
                    </div>
                </div>
            </Dialog>
        );
    }
}
