import './index.less'
import {Component} from "react";
import {formValidate, filterObjectFieldByKeys, filterObjectField} from '@/js/utils/tool';
import CustomSelect from "@/js/components/Select";
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';
import {setLocal, getLocal, localSpotRecordKey, localSpotSymbolKey, setLocalSymbolList} from '@/js/utils/local';

const users = 'user_ids';
const symbols = 'symbols';

// 不提交的字段
const noSubmitFields = ['symbolOptions', 'strategyOptions', 'userOptions',
    'positionSideOptions', 'orderTypeOptions'];

// 获取本地缓存的交易记录
const getLocalRecord = () => {
    let params: any = {};
    const localRecord = getLocal(localSpotRecordKey);
    if (localRecord) {
        params = localRecord;
    } else {
        params = {
            [users]: [],
            [symbols]: [],
            // 买卖类型
            [SpotTradeField.direction]: '',
            // 买入金额
            [SpotTradeField.amount]: null,
            // 止盈
            [SpotTradeField.stop_surplus]: null,
            // 止损
            [SpotTradeField.stop_loss]: null,
            // 卖出比例
            [SpotTradeField.quantity_ratio]: null,
            // 交易类型
            [SpotTradeField.order_type]: '',
            // 限价价格
            [SpotTradeField.limit_price]: '',
        }
    }
    // 添加不提交的字段
    // 交易对
    params.symbolOptions = [];
    // 交易策略options
    params.strategyOptions = [];
    // 用户options
    params.userOptions = getLocalUserList(true, false);
    // 买卖类型options
    params.positionSideOptions = getLocalSpotHelperSelect('direction', false);
    // 订单类型(交易类型)options
    params.orderTypeOptions = getLocalSpotHelperSelect('order_type', false);
    return params;
}
export default class TradeDialog extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = getLocalRecord()
    }

    // 重置
    onReset = () => {
        const items = Object.keys(this.state);
        items.forEach((item: any) => {
            // 跳过不提交的字段
            if (!noSubmitFields.includes(item)) {
                if (typeof this.state[item] === 'string') {
                    this.setState({
                        [item]: ''
                    })
                } else if (typeof this.state[item] === 'number') {
                    this.setState({
                        [item]: 0,
                    })
                } else {
                    this.setState({
                        [item]: []
                    })
                }
            }
        })
    }

    // 是否展示买入组件
    isShowBuyComponent = () => {
        return {
            display: isShow(this.state[SpotTradeField.direction] === 'BUY')
        }
    }

    // 提交
    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;
        }
        // 买入类型时，买入金额必填
        if (this.state[SpotTradeField.direction] === 'BUY' && !this.state[SpotTradeField.amount]) {
            show_message('买入金额必填');
            return;
        }
        // 卖出类型时，卖出比例必填
        if (this.state[SpotTradeField.direction] === 'SELL' && !this.state[SpotTradeField.quantity_ratio]) {
            show_message('卖出比例必填');
            return;
        }
        // 过滤不要的字段
        let params: any = filterObjectFieldByKeys(this.state, noSubmitFields);
        // 过滤空值
        params = filterObjectField(params);
        let loading = null;
        try {
            // 现价交易提交
            loading = open_loading();
            const res: any = await SpotBatchOperation(params);
            if (res.code == 0) {
                show_message('提交成功', 'success');
                // 存最新记录
                setLocal(localSpotRecordKey, params);
                // 存本次选择的交易对
                setLocalSymbolList(localSpotSymbolKey, params.symbols);
            }
            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.setState({
                    strategyOptions: res.data
                })
            }
        } catch (e) {
            console.log(e)
        }
    }
    SymbolList = async () => {
        try {
            const list = await getLocalSymbolList(true, localSpotSymbolKey);
            this.setState({
                symbolOptions: list,
            })
        } catch (e) {
            console.log(e)
        }
    }

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

    currentElement() {
        const state = this.state;
        return (
            <div className='custom-trade-form' style={this.props.style}>
                <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={state.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={state.symbolOptions}
                                      filterable={true}
                                      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'>策略</div>
                    <div className='trade-form-item__value'>
                        <CustomSelect value={state[SpotTradeField.spot_strategy_id]}
                                      name={SpotTradeField.spot_strategy_id} options={state.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={state.positionSideOptions.length ? state.positionSideOptions : this.props.HelpData['direction']}
                                      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={this.isShowBuyComponent()}>
                    <div className='trade-form-item__label required'>买入金额</div>
                    <div className='trade-form-item__value'>
                        <CustomInput type={"number"} value={state[SpotTradeField.amount]} align={'center'}
                                     name={SpotTradeField.amount}
                                     onChange={this.onValueChange}></CustomInput>
                    </div>
                </div>
                <div className='trade-form-item' style={this.isShowBuyComponent()}>
                    <div className='trade-form-item__label'>止盈</div>
                    <div className='trade-form-item__value'>
                        <CustomInput type={"number"} value={state[SpotTradeField.stop_surplus]} align={'center'}
                                     name={SpotTradeField.stop_surplus}
                                     onChange={this.onValueChange}></CustomInput>
                    </div>
                </div>
                <div className='trade-form-item' style={this.isShowBuyComponent()}>
                    <div className='trade-form-item__label'>止损</div>
                    <div className='trade-form-item__value'>
                        <CustomInput type={"number"} value={state[SpotTradeField.stop_loss]} align={'center'}
                                     name={SpotTradeField.stop_loss}
                                     onChange={this.onValueChange}></CustomInput>
                    </div>
                </div>
                {/*选择卖出展示的组件*/}
                <div style={{
                    display: isShow(state[SpotTradeField.direction] === 'SELL')
                }}>
                    <div className='trade-form-item'>
                        <div className='trade-form-item__label required'>卖出比例</div>
                        <div className='trade-form-item__value'>
                            <CustomInput type={"number"} value={state[SpotTradeField.quantity_ratio]} align={'center'}
                                         name={SpotTradeField.quantity_ratio}
                                         onChange={this.onValueChange}></CustomInput>
                        </div>
                    </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={state.orderTypeOptions.length ? state.orderTypeOptions : this.props.HelpData['order_type']}
                                      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>
        )
    }

    render() {
        const props = this.props;
        if (props['v-if']) {
            return this.currentElement();
        } else {
            return <></>;
        }
    }
}
