import './index.less'
import {Component} from "react";
import {formValidate, filterObjectField, filterObjectFieldByKeys} 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 {ContractTradeField} from '@/js/constants/trade';
import {show_message} from '@/js/utils/tdesign';
import {getLocalUserList, getLocalContractHelperSelect, getLocalSymbolList} from '@/js/utils/local';
import {ContractStrategy, ContractBatchOperation} from '@/js/utils/api/contract';
import {open_loading} from '@/js/utils/tdesign';
import {isShow} from '@/js/utils/dom';
import {setLocal, getLocal, localContractRecordKey, localContractSymbolKey} from '@/js/utils/local';

const users = 'user_ids';

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

// 获取本地缓存的交易记录
const getLocalRecord = () => {
    let params: any = {};
    const localRecord = getLocal(localContractRecordKey);
    if (localRecord) {
        params = localRecord;
    } else {
        // 默认字段
        params = {
            [users]: [],
            [ContractTradeField.pairs]: '',
            [ContractTradeField.contract_strategy_id]: '',
            [ContractTradeField.side]: '',
            [ContractTradeField.position_side]: '',
            [ContractTradeField.order_type]: '',
            [ContractTradeField.amount]: 3000,
            [ContractTradeField.levers]: 3,
            [ContractTradeField.stop_surplus]: 0,
            [ContractTradeField.stop_loss]: 0.3,
            // 限价价格
            [ContractTradeField.limit_price]: null,

        }
    }
    // 添加不提交的字段
    // 交易对
    params.symbolOptions = [];
    params.userOptions = getLocalUserList(true, false);
    // 交易策略options
    params.strategyOptions = [];
    // 方向options
    params.sideOptions = getLocalContractHelperSelect('side', false);
    // 买卖类型options
    params.positionSideOptions = getLocalContractHelperSelect('position_side', false);
    // 订单类型options
    params.orderTypeOptions = getLocalContractHelperSelect('order_type', false);
    return params;
}

export default class StartTrade extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = getLocalRecord();
    }

    SymbolList = async () => {
        try {
            const list = await getLocalSymbolList();
            this.setState({
                symbolOptions: list
            });
        } catch (e) {
            console.log(e)
        }
    }

    // 重置
    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]: []
                })
            }

        })
        console.log(this.state)
    }

    // 提交
    onSubmit = async () => {
        // 必填项
        const requiredFields = [users, ContractTradeField.pairs, ContractTradeField.side,
            ContractTradeField.amount, ContractTradeField.position_side, ContractTradeField.order_type];
        // 判断必填项是否为空
        const status = formValidate(requiredFields, this.state);
        if (!status) {
            show_message('请填写必填项');
            return;
        }
        // 限价单时，限价价格必填
        if (this.state[ContractTradeField.order_type] === 'LIMIT' && !this.state[ContractTradeField.limit_price]) {
            show_message('限价单价格必填');
            return;
        }
        // 过滤不要的字段
        let params: any = filterObjectFieldByKeys(this.state, noSubmitFields);
        // 过滤空值
        params = filterObjectField(params);
        let loading = null;
        try {
            loading = open_loading();
            const res: any = await ContractBatchOperation(params);
            if (res.code == 0) {
                show_message('提交成功', 'success');
                // 缓存本地数据
                setLocal(localContractRecordKey, params);
                // 更新本次提交的交易对


            }
            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 ContractStrategy();
            if (res.code == 0) {
                this.setState({
                    strategyOptions: res.data
                })
            }
        } 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[ContractTradeField.pairs]} name={ContractTradeField.pairs}
                                      options={state.symbolOptions}
                                      className={"trade-dialog-select"}
                                      filterable={true}
                                      clearable={false} customClear={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[ContractTradeField.contract_strategy_id]}
                                      name={ContractTradeField.contract_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[ContractTradeField.side]}
                                      name={ContractTradeField.side} options={state.sideOptions}
                                      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[ContractTradeField.position_side]}
                                      name={ContractTradeField.position_side}
                                      options={state.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[ContractTradeField.order_type]}
                                      name={ContractTradeField.order_type} options={state.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[ContractTradeField.order_type] === 'LIMIT')
                }}>
                    <div className='trade-form-item__label required'>限价价格</div>
                    <div className='trade-form-item__value'>
                        <CustomInput type={"number"} value={state[ContractTradeField.limit_price]} align={'center'}
                                     name={ContractTradeField.limit_price}
                                     onChange={this.onValueChange}></CustomInput>
                    </div>
                </div>
                <div className='trade-form-item'>
                    <div className='trade-form-item__label'>杠杆</div>
                    <div className='trade-form-item__value'>
                        <CustomInputNumber value={state[ContractTradeField.levers]} align={'center'}
                                           name={ContractTradeField.levers}
                                           onChange={this.onValueChange}></CustomInputNumber>
                    </div>
                </div>
                <div className='trade-form-item'>
                    <div className='trade-form-item__label required'>买入金额</div>
                    <div className='trade-form-item__value'>
                        <CustomInput value={state[ContractTradeField.amount]} name={ContractTradeField.amount}
                                     align={'center'} type={"number"}
                                     onChange={this.onValueChange}>
                        </CustomInput>
                    </div>
                </div>
                <div className='trade-form-item'>
                    <div className='trade-form-item__label'>止盈</div>
                    <div className='trade-form-item__value'>
                        <CustomInput value={state[ContractTradeField.stop_surplus]}
                                     name={ContractTradeField.stop_surplus}
                                     align={'center'} type={"number"}
                                     suffixIcon={
                                         (
                                             <div className='trade-form-input-suffix'>
                                                 %
                                             </div>
                                         )
                                     } onChange={this.onValueChange}>
                        </CustomInput>
                    </div>
                </div>
                <div className='trade-form-item'>
                    <div className='trade-form-item__label'>止损</div>
                    <div className='trade-form-item__value'>
                        <CustomInput value={state[ContractTradeField.stop_loss]}
                                     name={ContractTradeField.stop_loss} align={'center'} type={"number"}
                                     suffixIcon={
                                         (
                                             <div className='trade-form-input-suffix'>
                                                 %
                                             </div>
                                         )
                                     } 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 <></>;
        }
    }
}
