/** @format */

import * as React from 'react';
import { Badge } from "antd"
import { ColumnProps } from 'antd/es/table';
import { PaginationProps } from 'antd/es/pagination';
import { orderStatus, ORDER_STATUS_COLOR } from '../../../const/status';
import Result from '../../../components/result';
import Search, { SearchItemProps } from '../../../components/search/search';
import { formatNumer } from '../../../utils/operation';
import MerchantSelect from '../../../components/select/merchant';
// import DataApiSelect from '../../../components/select/dataApi';
import { decodeBase64 } from '../../../utils/base64';
import Table from '../../../components/table';
import Select from '../../../components/select/select';
import { useOrderMangent } from '../../../service/merchant';
import Input from '../../../components/input';
import DatePicker from '../../../components/DatePicker/rangePicker';
import moment from 'moment';
import UpdateOrderPriceModalForm from './change/updateOrderPriceModalForm'
import UpdateOrderStatusModalForm from './change/updateOrderStatusModalForm'


interface RecordProps {
    index: number;
    id: number;
    status_code: number;
    data_api_name: string;
    query_type: string;
    combo_type: string;
    price: string;
    add_order_time: string;
}

interface SearchColumnsProps {
    merchant_id: number | '';
    data_api_name: string;
    status_code: number;
    time: any;
}

interface dependState {
    merchant_id: number | '';
    data_api_id: number | '';
}

const orderManagement: React.FC = props => {
    const search = decodeBase64(location.search.slice(1));
    const id = new URLSearchParams(search).get('id');
    const [state, requestData] = useOrderMangent({ merchant_id: Number(id), page_number: 1, data_api_name: '', status_code: 0, start_time: '', end_time: '' });
    const handleChangePage = ({ current }: PaginationProps) => {
        requestData({
            page_number: current,
        });
    };
    const tableColumns = React.useMemo(() => {
        const Columns: ColumnProps<RecordProps>[] = [
            {
                title: '订单号',
                dataIndex: 'order_no',
                key: 'order_no',
            },
            {
                title: '商户名称',
                dataIndex: 'merchant_name',
                key: 'merchant_name',
            },
            {
                title: '项目',
                dataIndex: 'data_api_name',
                key: 'data_api_name',
                render: (_,record:any) => {
                    const {alias, data_api_name} = record;
                    return <div>{alias?alias:data_api_name}</div>;
                },
            },
            {
                title: '查询方式',
                dataIndex: 'query_type',
                key: 'query_type',
            },
            {
                title: '套餐规格',
                dataIndex: 'combo_desc',
                key: 'combo_desc',
            },
            {
                title: '购买数量',
                dataIndex: 'count',
                key: 'count',
            },
            {
                title: '购买账号',
                dataIndex: 'buy_account',
                align: 'right',
                key: 'buy_account',
            },
            {
                title: '价格(￥)',
                dataIndex: 'price',
                key: 'price',
                align: 'right',
                width: 100,
                render: (_,record:any) => {
                    const {count, price} = record;
                    const result = Number(count * price).toFixed(2);
                    return <div>{result}</div>;
                },
            },
            {
                title: '状态',
                dataIndex: 'status_code',
                key: 'status_code',
                width: 100,
                render: text => {
                    return <Badge text={orderStatus[text]} color={ORDER_STATUS_COLOR[text - 1]}></Badge>
                },
            },
            {
                title: '下单时间',
                dataIndex: 'add_order_time',
                key: 'add_order_time',
            },
            {
                title: '操作',
                key: 'opertion',
                render: (text, record) => {
                    const { status_code } = record
                    return <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', width: 100 }}>
                        {status_code === 1 && <UpdateOrderPriceModalForm record={record} refresh={refresh} />}
                        {status_code === 2 && <UpdateOrderStatusModalForm record={record} refresh={refresh} />}
                    </div>
                }
            },
        ];
        return Columns;
    }, []);

    const refresh = () => {
        requestData()
    }

    const [dependState, setDependState] = React.useState<dependState>({
        merchant_id: '',
        data_api_id: '',
    });

    const searchDataSource = React.useMemo(() => {
        const dataSource: SearchItemProps[] = [
            {
                key: 'merchant_id',
                component: (
                    <MerchantSelect
                        data_api_id={dependState.data_api_id}
                        onChange={id => setDependState(preState => ({ ...preState, merchant_id: id as number }))}
                    />
                ),
            },
            {
                key: 'data_api_name',
                component: (
                    <Input placeholder='请输入产品名' />
                ),
            },
            {
                key: 'time',
                component: (
                    <DatePicker allowClear showTime/>
                ),
            },
            {
                key: 'status_code',
                options: {
                    initialValue: 0,
                },
                style: {position:'relative',left:100},
                component: <Select options={[
                    {
                        label: '全部',
                        key: 0,
                        value: 0,
                    }, {
                        label: '待确认',
                        key: 1,
                        value: 1,
                    }, {
                        label: '待审核',
                        key: 2,
                        value: 2,
                    }, {
                        label: '已完成',
                        key: 3,
                        value: 3,
                    }, {
                        label: '审核未通过',
                        key: 4,
                        value: 4,
                    },{
                        label: '已取消',
                        key: 5,
                        value: 5,
                    }]} style={{width:120}}/>,
            },
        ];
        return dataSource;
    }, [dependState]);

    const handleReset = () => {
        setDependState(preState => ({ ...preState, merchant_id: '', data_api_id: '', }))
        requestData({
            page_number: 1,
            merchant_id: 0,
            data_api_name: '',
            status_code: 0,
            start_time: '',
            end_time: ''
        });
    }


    const handleSearch = (values: SearchColumnsProps) => {
        requestData({
            page_number: 1,
            merchant_id: values.merchant_id || 0,
            data_api_name: values.data_api_name || "",
            status_code: values.status_code,
            start_time: values.time ? moment(values.time[0]).format('YYYY-MM-DD HH:mm:ss') : '',
            end_time: values.time ? moment(values.time[1]).format('YYYY-MM-DD HH:mm:ss') : ''
        });
    };


    return (
        <>
            <Search
                handleReset={handleReset}
                disabled={state.loading}
                algin='space-between'
                handleSubmit={handleSearch}
                dataSource={searchDataSource}
            />
            <Result error={state.error} onRetry={() => requestData()}>
                <Table
                    pagination={{
                        total: state.total,
                        current: state.deepData.page_number
                    }}
                    onChange={handleChangePage}
                    rowKey='order_no'
                    columns={tableColumns}
                    loading={state.loading}
                    dataSource={state.dataSource}
                />
            </Result>
        </>
    );
};
export default orderManagement;
