import * as React from 'react';
import { 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 { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
import { Drawer, Space, Table, message } from 'antd';
import InitForm from '@/components/InitForm';
import copy from 'copy-to-clipboard';

function Pushsetting(props) {
  const actionRef = useRef(),
    formRef = useRef();
  const [drawer, setdrawer] = useState({
    open: false,
  });
  const [checkVariableDraw, setCheckVariableDraw] = useState(false);
  const [variablePath, setVariablePath] = useState(null);
  const pathconfig = useMemo(() => {
    let pathconf = getcolumns(setdrawer)?.pathconfig ?? {};
    return pathconf;
  }, []);
  const { run, loading } = useRequest(doFetch, {
    manual: true,
    onSuccess: (res, params) => {
      if (res?.code == '0000') {
        actionRef?.current?.reload();
        setdrawer((s) => ({
          ...s,
          open: false,
        }));
      }
    },
  });

  const news = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '详情',
              val: 'detail',
              title: '详细信息',
            }));
          },
        }}
      >
        新增通知
      </PremButton>
    );
  };

  const edit = (text, row, _, action) => {
    return (
      <PremButton
        btn={{
          size: 'small',
          onClick: () => {
            setdrawer((s) => ({
              ...s,
              open: true,
              item: row,
              title: '编辑',
              val: 'edit',
            }));
          },
        }}
      >
        编辑
      </PremButton>
    );
  };

  const remove = (text, row, _, action) => {
    return (
      <PremButton
        pop={{
          title: '是否删除?',
          okText: '确认',
          cancelText: '取消',
          onConfirm: () => {
            run({ url: pathconfig?.delete || '/delete', params: { id: row?.id } });
          },
        }}
        btn={{
          size: 'small',
          type: 'danger',
        }}
      >
        删除
      </PremButton>
    );
  };

  // 查看变量
  const checkVariableOpen = () => {
    setCheckVariableDraw(true);
  };
  const CheckVariable = () => {
    const columns = [
      {
        title: '变量名称',
        dataIndex: 'variableName',
        key: 'variableName',
      },
      {
        title: '变量编号',
        dataIndex: 'variableCode',
        key: 'variableCode',
      },
      {
        title: '操作',
        key: 'action',
        render: (_, record) => (
          <Space size="middle">
            <a
              onClick={() => {
                console.log(record, _);
                copy(record.variableCode);
                message.success('已成功复制到剪切板！');
              }}
            >
              复制
            </a>
          </Space>
        ),
      },
    ];

    return (
      <AutoTable
        columns={columns}
        resizeable={false}
        path="/base/paBusinessMsgSceneVariable/queryPageBySceneId"
        params={variablePath}
      />
    );
  };

  const columns = useMemo(() => {
    let defcolumn = getcolumns(setdrawer)?.columns;
    return defcolumn.concat({
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (text, row, _, action) => [
        news(text, row, _, action),
        edit(text, row, _, action),
        remove(text, row, _, action),
      ],
    });
  }, []);

  const selectValueType = {
    1: '全部',
    2: '公司',
    3: '部门',
    4: '工厂',
    5: '车间',
    6: '工段',
    7: '产线',
  };

  return (
    <div style={{ position: 'relative' }}>
      <AutoTable
        pagetitle={<h3 className="page-title">推送配置</h3>}
        columns={columns}
        actionRef={actionRef}
        path={pathconfig?.list || '/ngic-auth/sysUser/query/page'}
        pageextra={pathconfig?.enableadd ? 'add' : null}
        resizeable={false}
        addconfig={{
          // access: 'sysDepartment_save',
          btn: {
            disabled: false,
            type: 'primary',
            onClick: () => {
              setdrawer((s) => ({
                ...s,
                pushSettingFlag: true,
                open: true,
                item: null,
                title: '新增',
                val: 'add',
              }));
            },
          },
        }}
      />

      <DrawerPro
        fields={columns}
        params={{ id: drawer?.item?.id }}
        formRef={formRef}
        placement="right"
        detailpath={pathconfig?.detail || null}
        checkVariableOpen={checkVariableOpen}
        detailData={drawer?.item}
        defaultFormValue={drawer?.item}
        onValuesChange={async (a, b) => {
          if (a?.fitField) {
            console.log(a, b);
            const res = doFetch({ url: selectValueType[a?.fitField] });
            console.log(formRef);
          } else if (a?.businessMsgSceneId) {
            setVariablePath({
              businessMsgSceneId: a?.businessMsgSceneId,
            });
          }
        }}
        onClose={() => {
          setdrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        {...drawer}
        onFinish={(vals) => {
          if (drawer?.val == 'add') {
            run({ url: pathconfig?.add || '/add', params: { ...vals } });
          } else if (drawer?.val == 'edit') {
            run({ url: pathconfig?.edit || '/edit', params: { ...vals, id: drawer?.item?.id } });
          }
        }}
      />
      <Drawer
        title="查看变量"
        width={700}
        placement="right"
        onClose={() => {
          setCheckVariableDraw(false);
        }}
        open={checkVariableDraw}
      >
        <CheckVariable />
      </Drawer>
    </div>
  );
}

export default Pushsetting;
