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 {ContractTradeField} from '@/js/constants/trade';
import {show_message} from '@/js/utils/tdesign';
import {getLocalUserList, getLocalContractHelperSelect} 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';

const users = 'user_ids';
export default class TradeDialog extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = {
            [users]: [],
            [ContractTradeField.pairs]: '',
            [ContractTradeField.contract_strategy_id]: '',
            [ContractTradeField.side]: '',
            [ContractTradeField.position_side]: '',
            [ContractTradeField.order_type]: '',
            [ContractTradeField.amount]: null,
            [ContractTradeField.levers]: null,
            [ContractTradeField.stop_surplus]: null,
            [ContractTradeField.stop_loss]: null,
            // 限价价格
            [ContractTradeField.limit_price]: null,
        }
        this.userOptions = getLocalUserList(true, false);
        // 交易策略options
        this.strategyOptions = [];
        // 方向options
        this.sideOptions = getLocalContractHelperSelect('side', false);
        // 买卖类型options
        this.positionSideOptions = getLocalContractHelperSelect('position_side', false);
        // 订单类型options
        this.orderTypeOptions = getLocalContractHelperSelect('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]: []
                })
            }

        })
        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 loading = null;
        try {
            loading = open_loading();
            const res: any = await ContractBatchOperation(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
            })
        }
    }

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

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

    componentDidMount() {
        this.getStrategy()
    }

    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[ContractTradeField.pairs]} name={ContractTradeField.pairs}*/}
                            {/*              options={this.userOptions}*/}
                            {/*              className={"trade-dialog-select"}*/}
                            {/*              clearable={true} autoWidth={false}*/}
                            {/*              popupProps={{*/}
                            {/*                  overlayClassName: 'trade-dialog-select__overlay'*/}
                            {/*              }} onChange={this.onValueChange}></CustomSelect>*/}
                            <CustomInput value={state[ContractTradeField.pairs]} name={ContractTradeField.pairs}
                                         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[ContractTradeField.contract_strategy_id]}
                                          name={ContractTradeField.contract_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[ContractTradeField.side]}
                                          name={ContractTradeField.side} options={this.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={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[ContractTradeField.order_type]}
                                          name={ContractTradeField.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[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>
            </Dialog>
        );
    }
}
