/** @format */

import * as React from 'react';
import Axios from '../utils/xhr';
import {
    PUT_MERCHANT_ORDER_PRICE,
    POST_MERCHANT_ORDER_STATUS,
} from '../const/path';

export const useUpdateOrderPrice = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const updatePrice = (params: {order_no: string; price: number}) => {
        setState({loading: true, error: null});
        return Axios({
            url: PUT_MERCHANT_ORDER_PRICE,
            method: 'PUT',
            params: {
                order_no: params.order_no,
                price: params.price,
            },
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState({loading: false, error: null});
                    return;
                } else {
                    setState({loading: false, error: msg});
                    return msg;
                }
            })
            .catch(error => {
                setState({loading: false, error: error.message});
                return error.message;
            });
    };
    return [state, updatePrice] as const;
};

export const useUpdateOrderStatus = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const updateStatus = (params: {order_no: string; is_pass : 1 | 2}) => {
        setState({loading: true, error: null});
        return Axios({
            url: POST_MERCHANT_ORDER_STATUS,
            method: 'POST',
            params: {
                order_no: params.order_no,
                is_pass: params.is_pass,
            },
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState({loading: false, error: null});
                    return;
                } else {
                    setState({loading: false, error: msg});
                    return msg;
                }
            })
            .catch(error => {
                setState({loading: false, error: error.message});
                return error.message;
            });
    };
    return [state, updateStatus] as const;
};

