import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Select, InputNumber, TreeSelect, message, Modal, Button } from 'antd';
import { ProTable } from '@ant-design/pro-table';
import quickAPI from "../../service";
import styles from "./index.less";
import indexStyles from "../../index.less";
import { PlusOutlined } from '@ant-design/icons';
import { nanoid } from 'nanoid'
import BaiDuMapPostion from '../BaiDuMapPostion';

const key = 'message';

const StoreConfig = (props) => {

    const [currentPage, setCurrentPage] = useState(0);
    const [pageSize, setPageSize] = useState(20);

    const { TextArea } = Input;
    const { Option, OptGroup } = Select;
    const [storeForm] = Form.useForm();
    //门店树
    const [orgTree, setOrgTree] = useState([]);
    //支付方式列表
    const [payTypeList, setPayTypeList] = useState([]);

    //提交表单
    const onFinishSubmit = async (formValues) => {
        message.loading('正在配置', key);
        if (formValues.id) {
            const response = await quickAPI.UpdateOrg(formValues);
            if (response.succeeded) {
                message.success('修改成功');
                setIsShowModal(false);
                actionRef.current.reload();
            } else {
                message.error(response.errors || '修改出错');
            }
        } else {
            formValues.code = nanoid();
            const response = await quickAPI.AddOrg(formValues);
            if (response.succeeded) {
                message.success('添加成功');
                actionRef.current.reload();
                setIsShowModal(false);
            } else {
                message.error(JSON.stringify(response.errors) || '添加出错');
            }
        }
        message.destroy(key);
    }

    //当前操作的门店对象
    const [currentOption, setCurrentOption] = useState({ id: '' });
    //是否显示 新增/编辑 菜谱弹窗
    const [isShowModal, setIsShowModal] = useState(false);
    const actionRef = useRef();

    //获取门店树
    const onFetchOrgTree = async () => {
        const response = await quickAPI.getOrgTree();
        if (response.statusCode === 200) {
            const org = [
                {
                    key: '0',
                    parentId: '0',
                    title: '顶级',
                    value: '0',
                    children: response.data || [],
                }
            ]
            setOrgTree(org);
        } else {
            message.error(response.errors || '获取门店架构出错');
        }
    }

    //获取支付配置
    const getPayTemplateList = async () => {
        const response = await quickAPI.getPayTemplateList();
        if (response.statusCode === 200) {
            setPayTypeList(response.data.data);
        } else {
            message.error(response.errors || '获取获取支付方式出错');
        }
    }

    //门店列表
    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            tip: 'key',
            hideInSearch: true,
            hideInTable: true,
        },
        {
            title: '门店名称',
            dataIndex: 'name',
        },
        {
            title: '门店编码',
            dataIndex: 'code',
        },
        {
            title: '门店类型',
            dataIndex: 'type',
            valueEnum: {
                0: {
                    text: '机构',
                },
                1: {
                    text: '配送中心',
                },
                2: {
                    text: '直营店',
                },
                3: {
                    text: '加盟店',
                },
            },
        },
        {
            title: '电话',
            dataIndex: 'tel',
            hideInSearch: true,
        },
        {
            title: '排序',
            dataIndex: 'sort',
            valueType: 'digit',
            hideInSearch: true,
        },
        {
            title: '描述',
            dataIndex: 'remark',
            valueType: 'textarea',
            hideInSearch: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        setCurrentOption(record);
                        setIsShowModal(true);
                        storeForm.setFieldsValue(record);
                    }}>更新</a>
            ]
        }
    ];

    const [selectedRowKeys, setSelectRowKeys] = useState([]);

    const [isShowBaiduMap, setIsShowBaiduMap] = useState(false);

    const handleBaiduMapOk = (pos) => {
        const formValues = storeForm.getFieldsValue(true);
        formValues.store_Loc = `${pos.point.lng.toFixed(10)},${pos.point.lat.toFixed(10)}`;
        formValues.store_Addr = pos.address;
        storeForm.setFieldsValue(formValues);
        setIsShowBaiduMap(false);
        message.success('门店坐标设置成功！')
    }

    useEffect(() => {
        if (props.storeConfig.id) {
            setSelectRowKeys([props.storeConfig.id]);
        }
        onFetchOrgTree();
        getPayTemplateList();
    }, []);

    return <>
        {
            isShowBaiduMap && <BaiDuMapPostion isShowBaiduMap={isShowBaiduMap} handleOk={handleBaiduMapOk} handleCancel={() => setIsShowBaiduMap(false)}></BaiDuMapPostion>
        }
        <Modal width={600} title={currentOption.id ? '编辑门店架构' : '新增门店架构'} visible={isShowModal} footer={false} onCancel={() => setIsShowModal(false)}>
            <Form
                form={storeForm}
                layout="horizontal"
                preserve={false}
                labelCol={{
                    span: 4,
                }}
                onFinish={onFinishSubmit}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>

                <Form.Item name="code" hidden={true} label="门店编码">
                    <Input placeholder="请输入门店编码" />
                </Form.Item>

                <Form.Item name="name" label="门店名称" rules={[{ required: true, max: 64 }]}>
                    <Input placeholder="请输入名称" />
                </Form.Item>

                <Form.Item name="pid" label="所属机构" rules={[{ required: true }]}>
                    <TreeSelect
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        treeData={orgTree}
                        placeholder="请选择所属机构"
                        treeDefaultExpandAll
                    />
                </Form.Item>

                <Form.Item
                    name="type"
                    label="门店类型"
                    rules={[{ required: true, message: '请选择门店类型' }]}
                >
                    <Select placeholder="请选择机构类型" >
                        <OptGroup>
                            <Select.Option value={2}>直营店</Select.Option>
                            <Select.Option value={3}>加盟店</Select.Option>
                        </OptGroup>
                    </Select>
                </Form.Item>

                <Form.Item
                    name="payTemplateId"
                    label="支付模板"
                >
                    <Select placeholder="请选择支付模板" >
                        {
                            payTypeList?.map(item => {
                                return <Option value={item.id} key={item.id}>{item.name}</Option>
                            })
                        }
                    </Select>
                </Form.Item>
                <div className={indexStyles.add_row_content}>
                    <Form.Item label={'店铺坐标'} name="store_Loc" rules={[{
                        required: true, max: 100, pattern: /^[-\+]?\d+(\.\d+)\,[-\+]?\d+(\.\d+)$/,
                        message: '经纬度格式不对'
                    }]}>
                        <Input style={{ width: '55%' }}  placeholder="104.070734,30.575041" />
                    </Form.Item>
                    <Button type="primary" className={indexStyles.add_row_btn} onClick={() => { setIsShowBaiduMap(true); }}>打开地图</Button>
                </div>


                <Form.Item label={'店铺地址'} name="store_Addr" rules={[{ required: true, max: 100 }]}>
                    <Input placeholder="成都市武侯区桂溪街道环球中心N5-9111C" />
                </Form.Item>

                <Form.Item name="tel" label="电话" rules={[{ max: 20 }]}>
                    <Input placeholder="请输入联系电话" />
                </Form.Item>

                <Form.Item name="sort" label="排序">
                    <InputNumber min={1} step={1} precision={0} />
                </Form.Item>

                <Form.Item name="remark" label="备注">
                    <TextArea rows={4} rules={[{ max: 500 }]} />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </Form>
        </Modal>

        <ProTable
            search={false}
            style={{ width: '100%' }}
            headerTitle="门店列表"
            actionRef={actionRef}
            rowKey="id"
            rowSelection={{
                type: 'radio',
                onChange: (selectedRowKeys, selectedRows) => {
                    setSelectRowKeys(selectedRowKeys);
                    props.onSelectedChange('storeConfig', selectedRows[0]);
                },
                selectedRowKeys: selectedRowKeys
            }}
            request={async (params) => {
                let UserData = [];
                let total = 0;
                await quickAPI.getpage(params).then((r) => {
                    UserData = r.data.data;
                    total = r.data.total;
                });
                let filterData = UserData.filter(item => item.type === 2 || item.type === 3);
                return {
                    data: filterData,
                    success: true,
                    total: total,
                };
            }}
            columns={columns}
            pagination={{
                current: currentPage,
                pageSize: pageSize,
                onChange: (page, pageSize) => {
                    setCurrentPage(page);
                    setPageSize(pageSize);
                }
            }}
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                    storeForm.resetFields();
                    setCurrentOption({ id: '' });
                    setIsShowModal(true);
                }}>
                    新建
                </Button>
            ]}
        />
    </>
}

export default StoreConfig;
