import React, { useState, useRef, useEffect } from 'react';
import { Modal, Button, message, Popconfirm, Typography, Select,Form,Input,Radio,DatePicker} from 'antd';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { QuestionCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import weekday from "dayjs/plugin/weekday";
import localeData from "dayjs/plugin/localeData";
dayjs.extend(weekday);
dayjs.extend(localeData);
const dateFormat = 'YYYY/MM/DD';
const { Paragraph, Text } = Typography;

import { PageStoreAuthorization, AddStoreAuthorization, UpdateStoreAuthorization, UpdateStoreAuthTime, GetStoreList,DelStoreAuthTime } from "./services"
const App = () => {

    const actionRef = useRef();
    const [ModalVisible, handleModalVisible] = useState(false);
    const [currentRow, setCurrentRow] = useState();
    const [storeList, setStoreList] = useState([]);
    const [form] = Form.useForm();

    //初始化数据
    useEffect(() => {
        function initData() {
            GetStoreList().then((r) => {
                let data = [];
                if (r.statusCode == 200) {
                    r.data.forEach((item) => {
                        data.push({
                            id: item.id,
                            label: item.name,
                            value: item.id,
                        });
                    });
                    setStoreList(data);
                }
            });
        }
        initData();
    }, []);



    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            hideInSearch: true,
            hideInTable: true,
            tip: '规则名称是唯一的 key'
        },
        {
            title: '场景',
            dataIndex: 'storeName',
            valueType: 'textarea',
            width:200,
        },
        {
            title: '授权码',
            dataIndex: 'key',
            valueType: 'textarea',
            search: false,
            render: (text) => <Paragraph style={{ display: 'inline' }} copyable>{text}</Paragraph>,
        },
        
        {
            title: '有效日期',
            dataIndex: 'periodValidity',
            valueType: 'date',
            width:150,
            search: false,
            render: (_, record) => {
                var time=dayjs(record.periodValidity, dateFormat).format('YYYY-MM-DD');
                return <span>{record.periodValidity == null ? "长期有效" : time}</span>
            }
        },
        {
            title: '修改时间',
            dataIndex: 'updateAt',
            valueType: 'textarea',
            width: 150,
            search: false
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            fixed: 'right',
            width: 250,
            render: (_, record) => [
                <Popconfirm
                    type="primary"
                    key="primary"
                    title="确认更新吗?"
                    okText="是"
                    cancelText="否"
                    onConfirm={async () => {
                        await UpdateStoreAuthorization(record.id).then((r) => {
                            if (r.statusCode == 200 && r.data) {
                                message.success("修改成功");
                                actionRef.current.reload();

                            } else {
                                message.error(r.errors || "修改失败");
                            }
                        });
                    }}
                    onCancel={() => { }}
                >
                    <a href="#">更新授权码</a>
                </Popconfirm>,
                <a href="#" onClick={() => {
                    setCurrentRow(record);
                    var aa = record.periodValidity == null ? "cqyx" : "gdsj";
                    var time=record.periodValidity == null ?null:dayjs(record.periodValidity, dateFormat);
                    
                    form.setFieldsValue({ id: record.id, autho:aa, periodValidity: time,storeId:record.storeId });
                    handleModalVisible(true);
                }}>更新授权时间</a>,
                <Popconfirm
                    type="primary"
                    key="primary"
                    title="确认删除吗?"
                    okText="是"
                    cancelText="否"
                    onConfirm={async () => {
                        await DelStoreAuthTime(record.id).then((r) => {
                            if (r.statusCode == 200 && r.data) {
                                message.success("删除成功");
                                actionRef.current.reload();

                            } else {
                                message.error(r.errors || "删除失败");
                            }
                        });
                    }}
                    onCancel={() => { }}
                >
                    <a href="#">删除</a>
                </Popconfirm>,

            ],
        },
    ];

    return (
        <PageContainer host header={{ title: '', breadcrumb: {}, }}>
            <ProTable
                actionRef={actionRef}
                rowKey="id"
                pagination={{ defaultPageSize: 10 }}
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button type="primary" key="primary" onClick={() => {
                        handleModalVisible(true);
                    }} >
                        添加授权码
                    </Button>
                ]}
                request={async (params) => {
                    var data = [];
                    var total = 0;
                    await PageStoreAuthorization(params).then((r) => {
                        total = r.data.total;
                        data = r.data.data;
                    });
                    return {
                        data: data,
                        success: true,
                        total: total,
                    };
                }}
                columns={columns}
            />

            <Modal title="授权操作" open={ModalVisible}
                onOk={() => {
                    form.submit();

                }}
                onCancel={() => {
                    handleModalVisible(false);
                }}>

                <Form form={form} onFinish={(values) => {
                    if (values.id) {
                        UpdateStoreAuthTime(values).then((r) => {
                            if (r.statusCode == 200 && r.data) {
                                message.success("修改成功");
                                actionRef.current.reload();
                                handleModalVisible(false);

                            } else {
                                message.error(r.errors || "修改失败");
                            }
                        });

                    } else {
                        AddStoreAuthorization(values).then((r) => {
                            if (r.statusCode == 200 && r.data) {
                                message.success("添加成功");
                                actionRef.current.reload();
                                handleModalVisible(false);

                            } else {
                                message.error(r.errors || "添加失败");
                            }
                        });
                    }
                }}
                    style={{
                        maxWidth: 600,
                    }}>
                    <Form.Item name="id" hidden={true}>
                        <Input />
                    </Form.Item>
                    <Form.Item name="storeId" label="场景" rules={[{ required: true, }]}>
                        <Select style={{ width: 330, }} onChange={(value) => { setCurrentRow(value); }} options={storeList} />
                    </Form.Item>
                    <Form.Item name="autho" label="授权时间" rules={[{ required: true, }]} >
                        <Radio.Group >
                            <Radio value="cqyx"> 长期有效 </Radio>
                            <Radio value="gdsj"> 固定时间 </Radio>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.autho !== currentValues.autho} >
                        {({ getFieldValue }) =>
                            getFieldValue('autho') == 'gdsj' ? (
                                <Form.Item name="periodValidity" label="固定时间" rules={[{ required: true, }]}>
                                    <DatePicker style={{ width: "300px" }} />
                                </Form.Item>
                            ) : null
                        }
                    </Form.Item>
                </Form>
            </Modal>

        </PageContainer>
    );
};

export default App;
