/** @format */

import * as React from 'react';
import {notification,Badge,Tooltip,Typography, Input } from 'antd';

import {ColumnProps} from 'antd/es/table';
import {PaginationProps} from 'antd/es/pagination';
import md5 from 'md5';
import {formatNumer} from '../../../utils/operation';
import Result from '../../../components/result';
import Search, {SearchItemProps} from '../../../components/search/search';
import {interfaceStatus} from '../../../const/status';
import MerchantSelect from '../../../components/select/merchant';
import DataApiSelect from '../../../components/select/dataApi';
import MerchantStatusSelect from '../../../components/select/merchantStatus';
import {encodeBase64} from '../../../utils/base64';
import Button from '../../../components/button';
import {authStatus,AUTH_STATUS,DATA_API_STATUS_COLOR} from '../../../const/status';
import Table, {ExpandedRow} from '../../../components/table';
import {
    useMerchantListWithDataApi,
    useMerchantAuth,
    MerchantRecordState,
    useUpdateMerchant,
    useMerchantReviewList,
} from '../../../service/merchant';
import AuthComponent from '../components/merchant-auth';
import InsertMerchantComponent from '../components/merchant-form/createMerchant';
import MerchantForm from '../components/merchant-form/merchantForm';
import DatePicker from '../../../components/DatePicker/rangePicker';
import moment from 'moment';

const { Text } = Typography;

interface SearchColumnsProps {
    merchant_id: number | '';
    merchant_name: string | '';
    phone?: string;
    time:any
}
interface ModalState {
    values?: MerchantRecordState;
    visible: boolean;
}
interface dependState {
    merchant_id: number | '';
    data_api_id: number | '';
}
const MerchantList: React.FC = (props) => {
    const {history}=props;
  
    //获取商户列表
    const [merchantListState, requestMerchantReviewList] = useMerchantReviewList({
        merchant_id: '',
        page_number: 1,
        data_api_id: '',
        status_code: 0,
        is_all: false,
        merchant_name:'',
        phone:'',
        start_time:'',
        end_time:''
    });
   
    //商户认证hooks
    const [authState, requestAuth] = useMerchantAuth();

    //商户更新的modal状态
    const [UpdateModalState, setUpdateModalState] = React.useState<ModalState>({
        visible: false,
    });
    //商户认证的modal状态
    const [authModalState, setAuthModalState] = React.useState<ModalState>({
        visible: false,
    });

    const [updateState, requestUpdateMerchant] = useUpdateMerchant();
   
    const handleUpdateModalState = (visible = false, values?: MerchantRecordState) => {
        setUpdateModalState({visible, values});
    };
    //请求更新商户信息
    const handleuUpdateMerchant = values => {
        requestUpdateMerchant({
          ...values,
          id:UpdateModalState.values?.id,
          merchant_parssword:values.merchant_parssword?md5(values.merchant_parssword):""
        }).then(error=>{
          if(error){
            return notification.error({
              message:`更新${UpdateModalState.values?.merchant_name}商户失败`,
              description:error,
            })
          }
          requestMerchantReviewList()
          handleUpdateModalState()
        })
    };

    //更新认证弹窗状态
    const handleUpdateAuthVisible = (visible = false, record?: MerchantRecordState) => {
        setAuthModalState({visible, values: record});
    };
    //请求去设置认证状态
    const handleSubmitAuth = (values: {state: 1 | 2}) => {
        requestAuth({...values,id:authModalState.values?.id as number}).then(error => {
            if (error) {
                return notification.error({
                    message: '更新认证状态失败',
                    description: error,
                });
            }
            setAuthModalState({visible: false});
            requestMerchantReviewList();
        });
    };

    const handleSearch = (values: SearchColumnsProps) => {
        requestMerchantReviewList({
            page_number: 1,
            merchant_id: values.merchant_id||"",
            merchant_name: values.merchant_name || '',
            phone: values.phone || '',
            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') : ''
        });
    };

    //表格条件改变
    const handleChangeTable = (pagination: PaginationProps) => {
        const {current} = pagination;
        requestMerchantReviewList({
            page_number: current,
        });
    };
    const [dependState, setDependState] = React.useState<dependState>({
        merchant_id: '',
        data_api_id: '',
    });
    const handleReset=()=>{
      setDependState(preState=>({...preState,merchant_id: '',data_api_id: '',}))
      requestMerchantReviewList({
        merchant_id: '',
        page_number: 1,
        data_api_id: '',
        status_code: 0,
        is_all: false,
        merchant_name:'',
        phone:'',
        start_time:'',
        end_time:''
      })
    }

    //搜索框的数据
    const searchDataSource = React.useMemo(() => {
        const dataSource: SearchItemProps[] = [
            {
                key: 'merchant_name',
                component: (
                    <Input placeholder='请输入商户名' />
                ),
            },
            {
                key: 'phone',
                component: (
                    <Input placeholder='请输入手机号' />
                ),
            },
            {
                key: 'time',
                component: (
                    <DatePicker allowClear showTime/>
                ),
            },
            {
                key:'adas',
                component:(
                    <div></div>
                )
            }
        ];
        return dataSource;
    }, [dependState]);

    const TableColumns = React.useMemo(() => {
        const columns: ColumnProps<MerchantRecordState>[] = [
            {
                title: '商户',
                dataIndex: 'merchant_name',
                key: 'merchant_name',
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '手机号',
                key: 'phone',
                render: (_, record) => {
                    const {phone} = record;
                    return phone || '--';
                },
            },
            {
                title: '申请时间',
                key: 'create_time',
                render: (_, record) => {
                    const {create_time} = record;
                    return create_time || '--';
                },
            },
            {
                title: '认证状态',
                dataIndex: 'auth_status',
                key: 'auth_status',
                render(text) {
                    return <p>
                          <Badge status={AUTH_STATUS[text]}></Badge>
                          <Text type={AUTH_STATUS[text]}>{ authStatus[text]||"--"}</Text>
                       </p>
                },
            },
            {
                title: '操作',
                width: 280,
                fixed:"right",
                render: (_, record) => {
                    return (
                        <>
                            <Button onClick={() => handleUpdateAuthVisible(true, record)} type='link'>
                                认证
                            </Button>
                            <Button type='link' onClick={() => handleUpdateModalState(true, record)}>
                                修改
                            </Button>
                        </>
                    );
                },
            },
        ];
        return columns;
    }, [merchantListState.deepData]);
    return (
        <>
            {authModalState.values && (
                <AuthComponent
                    loading={authState.loading}
                    visible={authModalState.visible}
                    values={authModalState.values}
                    handleSubmit={handleSubmitAuth}
                    onCancle={() => handleUpdateAuthVisible(false)}
                />
            )}
            {UpdateModalState.values ? (
                <MerchantForm
                    loading={updateState.loading}
                    title={`修改(${UpdateModalState.values.name})`}
                    onCancel={() => handleUpdateModalState(false)}
                    onSubmit={handleuUpdateMerchant}
                    values={UpdateModalState.values}
                    visible={UpdateModalState.visible}
                />
            ) : null}
            <Search
                handleReset={handleReset}
                disabled={merchantListState.loading}
                algin='space-between'
                handleSubmit={handleSearch}
                dataSource={searchDataSource}
            />
            <Result error={merchantListState.error} onRetry={() => requestMerchantReviewList()}>
                <Table
                    rowKey='id'
                    onChange={handleChangeTable}
                    loading={merchantListState.loading}
                    pagination={{
                        total: merchantListState.total,
                        current:merchantListState.deepData.page_number
                    }}
                    dataSource={merchantListState.dataSource}
                    columns={TableColumns}
                />
            </Result>
        </>
    );
};
export default MerchantList;
