import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { FormInstance, ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import { MerchantModel } from "../data";
import { useRef, useState } from "react";
import { Col, Form, message, Row, Switch } from "antd";
import { updateMerchants } from "../service";
import { getFieldEnum } from "@/services/options";
import LinkManTable from "./LinkManTable";
import BrandTable from "./BrandTable";
import Draggable from "react-draggable";
import React from "react";


// 更新信息
const handleAddUpdate = async (fields: MerchantModel) => {
    const hide = message.loading('正在提交...');

    const result = await updateMerchants(fields);
    hide();
    if (result.Result_Code !== 100) {
        message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
        return false;
    }
    message.success(fields.COOPMERCHANTS_ID ? '更新成功！' : '新建成功！');
    return true;
};
type DetailProps = {
    currentRow: any;
    modalVisible: any;
    handleModalVisible: any;
    setCurrentRow: any
    actionRef: any
    disabled: any
    setDraggleDisabled: any
    bounds: any
    onDraggaleStart: any
    draggleRef: any
}
const AddEdit = ({ currentRow, modalVisible, handleModalVisible, setCurrentRow, actionRef, disabled, setDraggleDisabled, onDraggaleStart, bounds, draggleRef }: DetailProps) => {
    const formRef = useRef<FormInstance>();
    const brandTableRef = useRef<any>()



    return (
        <div>
            {/* 编辑信息 */}
            <ModalForm<MerchantModel>
                title={
                    <div
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}
                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        {currentRow ? '更新商户信息' : '新建商户'}
                    </div>
                }
                modalProps={{
                    modalRender: (modal) => {
                        return <Draggable
                            disabled={disabled}
                            bounds={bounds}
                            onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                        >
                            <div ref={draggleRef}>{modal}</div>
                        </Draggable>
                    },
                    destroyOnClose: true,
                    onCancel: () => {
                        setCurrentRow(undefined);
                        handleModalVisible(false)
                    }
                }}
                layout={'horizontal'}
                width={1024}
                wrapperCol={{ span: 16 }}
                labelCol={{ span: 6 }}
                formRef={formRef}
                visible={modalVisible}
                autoFocusFirstInput
                request={() => {
                    if (currentRow) {
                        return { ...currentRow, COOPMERCHANTS_STATE: currentRow.COOPMERCHANTS_STATE ? 1 : 0 }
                    } else {
                        return { COOPMERCHANTS_STATE: 1 }
                    }
                }}
                // onVisibleChange={(value) => {
                //     console.log('ModalForm', value);

                //     handleModalVisible(value);
                //     if (value) {
                //         formRef.current?.setFieldsValue(
                //             currentRow ? { ...currentRow, COOPMERCHANTS_STATE: currentRow.COOPMERCHANTS_STATE ? 1 : 0 } : { COOPMERCHANTS_STATE: 1 },
                //         );
                //         console.log('currentRow', currentRow ? { ...currentRow, COOPMERCHANTS_STATE: currentRow.COOPMERCHANTS_STATE ? 1 : 0 } : { COOPMERCHANTS_STATE: 1 });

                //     } else {
                //         formRef.current?.resetFields();
                //         setCurrentRow(undefined);
                //     }
                // }}

                onFinish={async (values) => {
                    let newValue: MerchantModel = { ...values };
                    if (currentRow) {
                        // 编辑数据
                        newValue = { ...values, COOPMERCHANTS_ID: currentRow.COOPMERCHANTS_ID };
                    }
                    newValue.COOPMERCHANTS_STATE = values.COOPMERCHANTS_STATE ? 1 : 0
                    console.log('newValue', newValue);
                    const success = await handleAddUpdate(newValue as MerchantModel);

                    if (success) {
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                        handleModalVisible(false);
                    }

                    return false;
                }}
            >
                <div style={{ height: '600px', overflowY: 'scroll', boxSizing: 'border-box' }}>
                    <Row gutter={20}>
                        <Col span={12}>
                            <ProFormText
                                name="COOPMERCHANTS_NAME"
                                label="商户名称"
                                placeholder="请输入名称"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入名称',
                                    },
                                ]}
                            />
                            <ProFormText
                                name="TAXPAYER_IDENTIFYCODE"
                                label="统一信用代码"
                                placeholder="统一信用代码"
                            />
                            <ProFormText name="BANK_NAME" label="开户行" placeholder="请输入开户行"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入开户行',
                                    },
                                ]} />
                            <ProFormText
                                name="COOPMERCHANTS_LINKMAN"
                                label="法人姓名"
                                placeholder="请输入法人姓名"
                            />
                            <ProFormSelect
                                name="MERCHANTTYPE_ID"
                                label="所属类别"
                                placeholder="请选择所属类别"
                                // tooltip="若无你需选择商户类别，请添加后选择"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择所属类别',
                                    },
                                ]}
                                request={async () => {
                                    const options = await getFieldEnum({ FieldExplainField: 'MERCHANTS_TYPE' });
                                    return options
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="COOPMERCHANTS_EN"
                                label="商户简称"
                                placeholder="请输入名称"
                            />
                            <ProFormText
                                name="COOPMERCHANTS_CODE"
                                label="商户编码"
                                placeholder="请输入商户编码"
                            />
                            <ProFormSelect
                                name="COOPMERCHANTS_NATURE"
                                label="商户性质"
                                placeholder="请选择商户性质"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择商户性质',
                                    },
                                ]}
                                options={[{ value: 1000, label: '企业' }, { value: 2000, label: '个体' }, { value: 3000, label: '自然人' }]}
                            />
                            <ProFormText name="BANK_ACCOUNT" label="银行账号" placeholder="请输入银行账号" rules={[
                                {
                                    required: true,
                                    message: '请输入银行账号',
                                },
                            ]} />
                            <ProFormText
                                name="COOPMERCHANTS_MOBILEPHONE"
                                label="联系电话"
                                placeholder="请输入手机号"
                            />
                            {/* 当前依赖包动画过渡有问题 临时采用 Form.Item 方式进行Switch交互 */}
                            <Form.Item
                                name="COOPMERCHANTS_STATE"
                                label="是否有效"
                                rules={[
                                    {
                                        required: true,
                                        message: '是否无效',
                                    },
                                ]}
                            >
                                <Switch
                                    checkedChildren="有"
                                    unCheckedChildren="无"
                                    defaultChecked={currentRow ? !!currentRow.COOPMERCHANTS_STATE : true}
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24}>
                            <ProFormTextArea
                                name="COOPMERCHANTS_ADDRESS"
                                wrapperCol={{ span: 20 }}
                                labelCol={{ span: 3 }}
                                label="商户地址"
                            />
                        </Col>
                    </Row>
                    {/* 联系人列表 */}
                    {
                        modalVisible ?
                            <LinkManTable merchartsId={currentRow?.COOPMERCHANTS_ID} show={modalVisible}></LinkManTable> : ''
                    }

                    {/* 品牌列表编辑新增 */}
                    {
                        modalVisible ?
                            <BrandTable onRef={brandTableRef} merchartsId={currentRow?.COOPMERCHANTS_ID} currentRow={currentRow} /> : ''
                    }
                </div>
            </ModalForm>
        </div>
    )
}

export default connect(({ user, }: ConnectState) => ({
    currentUser: user.currentUser,
}))(AddEdit);
