import React, { useState, useMemo, useRef, useEffect } from 'react';
import DrawerPro from '@/components/DrawerPro';
import AutoTable from '@/components/AutoTable';
import PremButton from '@/components/PremButton';
import getcolumns from './columns';
import { doFetch, exportFetch } from '@/utils/doFetch';
import { useRequest, useAsyncEffect } from "ahooks";
import styles from "./index.less";
import TreeRender from '@/components/TreeRender';
import { Divider, Tabs, message } from "antd";
import Leaseresume from "./Leaseresume";
import Operatinghistory from "./Operatinghistory";
import Resume from "./Resume";
import Basemsg from "./Basemsg";
import setAllCanvas from "@/utils/drawimage"//导出二维码
const Ledger = () => {
    let actionRef = useRef();
    const [drawer, setdrawer] = useState({
        open: false,
    }),
        [defaultmsg, cds] = useState({
            supplier: {},
            factory: {}
        }),
        [extraparams, setextraparams] = useState({}),
        [searchParams, csp] = useState({});
    const { run, loading, runAsync } = useRequest(doFetch, {
        manual: true,
        onSuccess: (res, params) => {
            if (res?.code == "0000") {
                actionRef?.current?.reload();
                setdrawer((s) => ({
                    ...s,
                    open: false,
                }));
            }
        },
    });
    const columns = useMemo(() => {
        let defcolumn = getcolumns(setdrawer)?.columns ?? [];
        return defcolumn.concat({
            title: '操作',
            valueType: 'option',
            width: 190,
            render: (text, row, _, action) => getExtra(text, row, _, action),
            colProps: {
                fixed: 'right'
            }
        });
    }, []);
    const pathconfig = useMemo(() => {
        let pathconf = getcolumns(setdrawer)?.pathconfig ?? {};
        return pathconf;
    }, []);
    useAsyncEffect(async () => {
        let res = await doFetch({ url: "/lease/umEquipmentSupplier/queryByDefault", params: {} }),
            res2 = await doFetch({ url: "/auth/sysFactory/queryByDefault", params: {} });
        cds({
            supplier: res?.data?.data ?? {},
            factory: res2?.data?.data ?? {}
        });
    }, [])


    const onselecteTree = (selectedKeys, e, alldata) => {
        let params = {};
        if (selectedKeys.length) {
            switch (e.node.type) {
                case 1:
                    params = { factoryId: e.node.key }
                    break;
                case 2:
                    params = { shopId: e.node.key }
                    break;
                case 3:
                    params = { sectionId: e.node.key }
                    break;
                case 4:
                    params = { productionLineId: e.node.key }
                    break;
                default:
                    params = {};
            }
        } else {
            params = {}
        }

        setextraparams(params);
    };
    const getExtra = (text, row, _, action) => {
        //0: 报废 1: 预占 2: 租赁 3: 销售 4: 闲置 5:待复检 6: 未绑定 7: 绑定
        let ifsd = row.status == 0,
            ifsa = row.status == 1,
            ifsb = row.status == 2,
            ifsg = row.status == 3,
            ifs = row.status == 4,
            ifsc = row.status == 5,
            ifse = row.status == 6,
            ifsf = row.status == 7,
            devicetype1 = row.equipmentType == 1,
            devicetype2 = row.equipmentType == 2,
            intelligentUnit = row.ledgerEquipment;

        return [
            (ifsd || (devicetype1 && ifs) || (devicetype2 && ifse)) && <PremButton
                key='edit'
                btn={{
                    size: 'small',
                    onClick: () => {
                        setdrawer((s) => ({
                            ...s,
                            open: true,
                            item: row,
                            val: 'edit',
                            title: '编辑'
                        }));
                    },
                }}
            >
                修改
            </PremButton>,
            devicetype1 && <PremButton
                key='bind'
                btn={{
                    size: 'small',
                    onClick: () => {
                        setdrawer((s) => ({
                            ...s,
                            open: true,
                            item: row,
                            val: 'bind',
                            title: '绑定',
                            fields: [
                                {
                                    title: '关联智能单元',
                                    dataIndex: 'ledgerEquipmentId',
                                    key: 'ledgerEquipmentId',
                                    valueType: 'select',
                                    options: { path: '/lease/umLeaseLedger/intelligentUnitSelectbox', params: { id: row.id } },
                                    colProps: { span: 8 },
                                    span: 3,
                                    fieldProps: {
                                        placeholder: '请选择',
                                        showSearch: true,
                                    },
                                    formItemProps: { rules: [{ required: true, message: '此项为必填项' }] },
                                }
                            ]
                        }));
                    },
                }}
            >
                绑定
            </PremButton>,
            devicetype2 && ifsf && <PremButton
                key='unbind'
                pop={{
                    title: '是否解绑?',
                    okText: '确认',
                    cancelText: '取消',
                    onConfirm: async () => {
                        runAsync({ url: "/lease/umLeaseLedger/unBingDing", params: { id: row.id } });
                    },
                }}
                btn={{
                    size: 'small',
                }}
            >
                解绑
            </PremButton>,
            (ifs && !intelligentUnit || ifse) && <PremButton
                key='Scrapped1'
                pop={{
                    title: '是否报废?',
                    okText: '确认',
                    cancelText: '取消',
                    onConfirm: async () => {
                        runAsync({ url: "/lease/umLeaseLedger/scrap", params: { id: row.id } });
                    },
                }}
                btn={{
                    size: 'small',
                    type: 'danger',
                }}
            >
                报废
            </PremButton>,
            ifs && devicetype1 && intelligentUnit && <PremButton
                key='Scrapped2'
                pop={{
                    title: <div>该设备有关联智能单元<br />
                        请确认是一同报废或<br />
                        释放出关联智能单元？</div>,
                    okText: '释放',
                    cancelText: '一同报废',
                    onConfirm: async () => {
                        runAsync({ url: "/lease/umLeaseLedger/scrapSubmit", params: { flag: 2, id: row.id } });
                    },
                    onCancel: async () => {
                        runAsync({ url: "/lease/umLeaseLedger/scrapSubmit", params: { flag: 1, id: row.id } });
                    },
                }}
                btn={{
                    size: 'small',
                    type: 'danger',
                }}
            >
                报废
            </PremButton>,
            ifsc && <PremButton
                key='Scrapped1'
                pop={{
                    title: '是否转闲置?',
                    okText: '确认',
                    cancelText: '取消',
                    onConfirm: async () => {
                        runAsync({ url: "/lease/umLeaseLedger/leaveUnused", params: { id: row.id, } });
                    },
                }}
                btn={{
                    size: 'small',
                }}
            >
                转闲置
            </PremButton>,
            ifsd && <PremButton
                key='remove'
                pop={{
                    title: '是否删除该设备?',
                    okText: '确认',
                    cancelText: '取消',
                    onConfirm: async () => {
                        runAsync({ url: pathconfig.delete, params: { id: row.id, } });
                    },
                }}
                btn={{
                    size: 'small',
                    type: 'danger',
                }}
            >
                删除
            </PremButton>,
        ];
    }
    const items = useMemo(() => {
        if (drawer.val == 'only') {
            if (drawer.item.equipmentType == 1) {
                return [
                    { label: '基础信息', key: 'item-1', children: <Basemsg drawer={drawer} /> },
                    { label: '绑定履历', key: 'item-2', children: <Resume drawer={drawer} url='/lease/umLeaseLedgerEquipment/queryList' /> },
                    { label: '租赁履历', key: 'item-3', children: <Leaseresume drawer={drawer} /> },
                    { label: '操作履历', key: 'item-4', children: <Operatinghistory drawer={drawer} /> }
                ]
            } else {
                return [
                    { label: '基础信息', key: 'item-1', children: <Basemsg drawer={drawer} /> },
                    { label: '绑定履历', key: 'item-2', children: <Resume drawer={drawer} url='/lease/umLeaseLedgerEquipment/queryListByLeaseLedgerId' /> },
                    { label: '操作履历', key: 'item-4', children: <Operatinghistory drawer={drawer} /> }
                ]
            }
        }
    }, [drawer.val, drawer.item]);
    const rightExtra = () => {
        return [
            <PremButton
                key='add'
                btn={{
                    type: 'primary',
                    onClick: () => {
                        setdrawer((s) => ({
                            ...s,
                            open: true,
                            val: 'add',
                            title: '新增',
                            item: {
                                factoryId: defaultmsg?.factory?.id,
                                supplierId: defaultmsg?.supplier?.id
                            }
                        }));
                    }
                }}
            >
                新增
            </PremButton>,
            <PremButton
                key='export'
                btn={{
                    type: 'default',
                    onClick: async () => {
                        message.warning('导出中，请稍后');
                        await exportFetch({ url: '/lease/umLeaseLedger/exportExcel', params: { ...searchParams, ...extraparams } });
                    },
                    style: { margin: '0 12px' }
                }}
            >
                导出
            </PremButton>,
            <PremButton
                key='exportqrcode'
                btn={{
                    type: 'default',
                    onClick: async () => {
                        let res = await doFetch({ url: '/lease/umLeaseLedger/queryQrCode', params: { ...searchParams, ...extraparams } });
                        setAllCanvas(res?.data?.dataList ?? [], 20, 20);
                    },
                }}
            >
                导出二维码
            </PremButton>,
            <PremButton
                key='status'
                btn={{
                    type: 'default',
                    onClick: () => {

                    },
                    style: { marginLeft: 12 }
                }}
            >
                状态查看
            </PremButton>,
        ];
    }


    return <div className={styles.ledgerbox}>
        <div className={styles.ledgerheader}>
            <div className="ant-card-head" style={{ backgroundColor: 'white' }}>
                <div className="ant-card-head-wrapper">
                    <div className="ant-card-head-title">
                        <h3 className="page-title">租赁台账</h3>
                    </div>
                </div>
            </div>
        </div>
        <div className={styles.ledgercontent}>
            <div className={styles.ledgerleft}>
                <TreeRender url="/auth/sysFactory/getTree" onselected={onselecteTree} noaction={true} />
            </div>
            <div className={styles.ledgerright}>
                <AutoTable
                    pagetitle={'设备列表'}
                    columns={columns}
                    path={pathconfig?.list}
                    actionRef={actionRef}
                    resizeable={false}
                    pageextra={rightExtra}
                    bordered={false}
                    x={2200}
                    extraparams={extraparams}
                    dataSourceFieldsChange={(val) => {
                        csp(val)
                    }}
                />
            </div>
        </div>


        <DrawerPro
            {...drawer}
            fields={drawer.val == 'bind' ? drawer.fields : columns}
            detailpath={drawer.val == 'add' || !drawer?.item?.id ? '' : pathconfig?.detail}
            params={drawer.val == 'add' ? {} : { id: drawer?.item?.id }}
            defaultFormValue={drawer?.item ?? {}}
            placement="right"
            onClose={() => {
                setdrawer((s) => ({
                    ...s,
                    open: false,
                }));
            }}
            onFinish={async (vals) => {
                let newParams = JSON.parse(JSON.stringify(vals));
                if (drawer?.val == "add") {
                    await runAsync({ url: pathconfig?.add, params: { ...newParams } });
                } else if (drawer?.val == "edit") {
                    await runAsync({
                        url: pathconfig?.edit,
                        params: { ...newParams, id: drawer?.item?.id },
                    });
                } else if (drawer.val == 'bind') {
                    await runAsync({ url: "/lease/umLeaseLedger/bound", params: { ...newParams, id: drawer?.item?.id } });
                }
            }}
        >
            <Tabs items={items} destroyInactiveTabPane />
        </DrawerPro>
    </div>
}
export default Ledger;