/** @format */

import * as React from 'react';
import {notification,Badge,Tooltip,Typography } 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,
} from '../../../service/merchant';
import AuthComponent from '../components/merchant-auth';
import InsertMerchantComponent from '../components/merchant-form/createMerchant';
import MerchantForm from '../components/merchant-form/merchantForm';
import MerchantTypeSelect from '../../../components/select/merchantTypeSelect';
const { Text } = Typography;

interface SearchColumnsProps {
    merchant_id: number | '';
    data_api_id: number | '';
    status_code: number;
    merchant_type: any;
}
interface ModalState {
    values?: MerchantRecordState;
    visible: boolean;
}
interface dependState {
    merchant_id: number | '';
    data_api_id: number | '';
}

const merchantTypeIncludes = [2,3]

const MerchantList: React.FC = (props) => {
    const {history}=props;
  
    //获取商户列表
    const [merchantListState, requestMerchantList] = useMerchantListWithDataApi({
        merchant_id: '',
        page_number: 1,
        data_api_id: '',
        status_code: 0,
        is_all: false,
        merchant_type:'',
    });
   
    //商户认证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,
            })
          }
          requestMerchantList()
          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});
            requestMerchantList();
        });
    };

    const handleSearch = (values: SearchColumnsProps) => {
        requestMerchantList({
            page_number: 1,
            merchant_id: values.merchant_id||"",
            data_api_id: values.data_api_id||"",
            status_code: values.status_code,
            merchant_type:values.merchant_type ||'',
        });
    };

    //表格条件改变
    const handleChangeTable = (pagination: PaginationProps) => {
        const {current} = pagination;
        requestMerchantList({
            page_number: current,
        });
    };
    const [dependState, setDependState] = React.useState<dependState>({
        merchant_id: '',
        data_api_id: '',
    });
    const handleReset=()=>{
      setDependState(preState=>({...preState,merchant_id: '',data_api_id: '',}))
    }
    //搜索框的数据
    const searchDataSource = React.useMemo(() => {
        const dataSource: SearchItemProps[] = [
            {
                key:'merchant_type',
                component:<MerchantTypeSelect />
            },
            {
                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_id',
                component: (
                    <DataApiSelect
                        merchant_id={dependState.merchant_id}
                        onChange={id => setDependState(preState => ({...preState, data_api_id: id as number}))}
                    />
                ),
            },
            {
                key: 'status_code',
                options: {
                    initialValue: 0,
                },
                component: <MerchantStatusSelect />,
            },
        ];
        return dataSource;
    }, [dependState]);

    const TableColumns = React.useMemo(() => {
        const columns: ColumnProps<MerchantRecordState>[] = [
            {
                title: '商户',
                dataIndex: 'merchant_name',
                key: 'merchant_name',
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '商户类型',
                dataIndex: 'merchant_type',
                render:(_,record:any)=>{
                    const { merchant_type } = record
                    if(merchant_type === 1){
                        return <div>普通客户</div>
                    }
                    if(merchant_type === 2){
                        return <div>预存款客户</div>
                    }
                    if(merchant_type === 3){
                        return <div>后结算客户</div>
                    }
                }
            },
            {
                title: '产品',
                key: 'producetName',
                render: (_, record) => {
                    const {data_api_info} = record;
                    if (data_api_info) {
                        return data_api_info.map((element, index) => <p key={index}>{element.data_api_name}</p>);
                    }
                    return '--';
                },
            },
            {
                title: '产品别名',
                key: 'producetAliasName',
                render: (_, record) => {
                    const {data_api_info} = record;
                    if (data_api_info) {
                        return data_api_info.map((element, index) => <p key={index}>{element.alias || '-'}</p>);
                    }
                    return '--';
                },
            },
            {
                title: '剩余查次(次)',
                key: 'left_count',
                align: 'right',
                render: (_, record) => {
                    const {data_api_info, merchant_type} = record;
                    if (data_api_info) {
                        return data_api_info.map((element, index) => {
                            const { left_count} = element
                            return left_count == 0 && merchantTypeIncludes.includes(merchant_type) ?<p>-</p>:<p key={index}>{formatNumer(element.left_count)}</p>
                        })
                    }
                    return '--';
                },
            },
            {
                title: '剩余天数(天)',
                align: 'right',
                key: 'left_day',
                render: (_, record) => {
                    const {data_api_info,merchant_type} = record;
                    if (data_api_info) {
                        return data_api_info.map((element, index) => {
                            const { left_day} = element
                            return left_day == 0 && merchantTypeIncludes.includes(merchant_type) ?<p>-</p>:<p key={index}>{formatNumer(element.left_day)}</p>
                        })
                    }
                    return '--';
                },
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',

                render: (_, record) => {
                    const {data_api_info} = record;
                    if (data_api_info) {
                        return data_api_info.map((element, index) =>{
                          const color=DATA_API_STATUS_COLOR[element.status_code]
                          const text=interfaceStatus[element.status_code]
                          return <p key={index}>
                                  <Badge status={color}/>
                                  <Text type={color==="error"?"danger":color}>{text}</Text>
                              </p> 
                        });
                    }
                    return '--';
                },
            },
            {
                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={() => {
                                    const path =
                                        '/home/merchant/permissionManger?' +
                                        encodeBase64('name=' + encodeURIComponent(record.merchant_name)  + '&id=' + record.id);
                                    history.push(path);
                                }}
                                type='link'
                            >
                                权限
                            </Button>
                            <Button
                                onClick={() => {
                                    const path =
                                        '/home/merchant/orderManent?' +
                                        encodeBase64('name=' + encodeURIComponent(record.merchant_name) + '&id=' + record.id);
                                    history.push(path);
                                }}
                                type='link'
                            >
                                订单
                            </Button>
                            <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='end'
                extra={
                    <InsertMerchantComponent
                        onOk={() =>
                            requestMerchantList({page_number: 1, status_code: 0, merchant_id: '', data_api_id: ''})
                        }
                    >
                        <Button icon='plus'>新增</Button>
                    </InsertMerchantComponent>
                }
                handleSubmit={handleSearch}
                dataSource={searchDataSource}
            />
            <Result error={merchantListState.error} onRetry={() => requestMerchantList()}>
                <Table
                    rowKey='id'
                    onChange={handleChangeTable}
                    expandedRowRender={({app_key, app_secret}) => (
                        <ExpandedRow 
                          left={   
                            <Tooltip placement="topLeft" title={app_key}>
                                {`app_key:  ${app_key || '-'}`}
                            </Tooltip> } 
                          right={ 
                            <Tooltip placement="topLeft" title={app_secret}>
                              { `app_secret:  ${app_secret || '-'}`}
                            </Tooltip> }  
                       />
                    )}
                    loading={merchantListState.loading}
                    pagination={{
                        total: merchantListState.total,
                        current:merchantListState.deepData.page_number
                    }}
                    dataSource={merchantListState.dataSource}
                    columns={TableColumns}
                />
            </Result>
        </>
    );
};
export default MerchantList;
