import {
  addConnect,
  delConnect,
  getConnect,
  searchTableConnect,
  updateConnect,
} from '@/services/iot/connect';
import { getDataModel } from '@/services/iot/dataModel';
import { PlusOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  EditableProTable,
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Avatar, Button, Card, Collapse, Popconfirm, Tabs, Tag } from 'antd';
import { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';

const { Meta } = Card;
const { Panel } = Collapse;
type DataSourceType = {
  id: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: string;
  update_at?: string;
  children?: DataSourceType[];
};

const defaultData: DataSourceType[] = [
  {
    id: 624748504,
    title: '属性1',
    readonly: '大于',
  },
  {
    id: 624691229,
    title: '属性2',
    readonly: '大于',
  },
];

export default () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [drawerVisit, setDrawerVisit] = useState(false);
  const [modalVisit, setModalVisit] = useState(false);
  const [modalVisit2, setModalVisit2] = useState(false);
  const [modelOption, setModelOption] = useState();
  const [isEdit, setIsEdit] = useState(false);
  const [isEditData, setIsEdittData] = useState<API.IOT.Device>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [position, setPosition] = useState<'top' | 'bottom' | 'hidden'>('bottom');

  // 确认删除
  const confirm = (record: API.IOT.Device) => {
    console.log(record);
    delConnect(record.id).then(() => {
      actionRef?.current?.reload();
    }); // 删除
  };

  // 取消删除
  const cancel = (record: API.IOT.Device) => {
    console.log(record);
  };

  // 设备型号和厂商联动
  const onSelect = (val: any, option: any) => {
    setModelOption(option['data-item']);
  };

  // 编辑回显
  const onEdit = (record: any) => {
    setDrawerVisit(true);
    setIsEdit(true);
    getConnect(record.id).then((res: any) => {
      setIsEdittData(res);
      formRef?.current?.setFieldsValue(res);
    });
  };

  // 查看详情
  const onView = (record: any) => {
    setModalVisit(true);
  };

  // 新增规则
  const addRule = () => {
    setModalVisit2(true);
  };

  const columns: ProColumns<API.IOT.Device>[] = [
    {
      title: '序号',
      dataIndex: 'serial',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '名称',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      search: false,
    },
    {
      title: '协议',
      dataIndex: 'protocol',
      search: false,
    },
    {
      disable: true,
      title: 'IP地址',
      dataIndex: 'host',
      search: false,
    },
    {
      dataIndex: 'port',
      disable: true,
      title: '端口号',
      search: false,
    },
    {
      dataIndex: 'url',
      disable: true,
      title: 'URL',
      search: false,
    },
    {
      dataIndex: 'url',
      disable: true,
      title: '坐标',
      search: false,
    },
    {
      dataIndex: 'url',
      disable: true,
      title: '数据模型',
      search: false,
    },
    {
      title: '编码格式',
      dataIndex: 'type',
      search: false,
    },

    {
      title: '描述',
      dataIndex: 'note',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            onEdit(record);
          }}
        >
          编辑
        </a>,
        <a
          key="editable"
          onClick={() => {
            onView(record);
          }}
        >
          查看
        </a>,
        <Popconfirm
          title="确认删除?"
          onConfirm={(e) => {
            confirm(record);
          }}
          onCancel={(e) => {
            cancel(record);
          }}
          okText="是"
          cancelText="否"
          key={record.id}
        >
          <a target="_blank" key="delete">
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];

  const columnsEditableProTable: ProColumns<DataSourceType>[] = [
    {
      title: '属性',
      dataIndex: 'title',
      valueType: 'select',
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        open: {
          text: '属性1',
          status: 'Error',
        },
        closed: {
          text: '属性2',
          status: 'Success',
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'readonly',
      valueType: 'select',
      valueEnum: {
        dayu: {
          text: '大于',
          status: 'Success',
        },
        dengyu: {
          text: '等于',
          status: 'Success',
        },
        xiaoyu: {
          text: '小于',
          status: 'Success',
        },
      },
    },
    {
      title: '值',
      key: 'state',
      dataIndex: 'state',
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,

        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      {/* table主体 */}
      <ProTable<API.IOT.Device>
        headerTitle="车型管理"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={searchTableConnect as any}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'sessionStorage',
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setDrawerVisit(true);
              setIsEdit(false);
            }}
          >
            新建
          </Button>,
        ]}
      />

      {/* 连接配置管理 */}
      <DrawerForm<API.IOT.Device>
        title="连接配置管理"
        formRef={formRef}
        onVisibleChange={setDrawerVisit}
        visible={drawerVisit}
        autoFocusFirstInput
        drawerProps={{
          destroyOnClose: true,
        }}
        onFinish={async (values: any) => {
          console.log(values);
          let editObj;
          if (isEdit) {
            // 编辑模式 替换对象
            editObj = { ...(isEditData || {}), ...values };
            editObj.dataModel = modelOption;
          }
          values.dataModel = modelOption;
          !isEdit
            ? await addConnect(values).then(() => {
              actionRef?.current?.reload();
            })
            : await updateConnect(editObj, isEditData?.id).then(() => {
              actionRef?.current?.reload();
            });

          // 不返回不会关闭弹框
          return true;
        }}
      >
        <ProForm.Group>
          <ProFormText
            name="name"
            width="md"
            label="名称"
            placeholder="请输入名称"
            rules={[{ required: true, message: ' ' }]}
          />
          <ProFormText width="md" name="alias" label="别名" placeholder="请输入名称" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            width="md"
            name="protocol"
            label="链接协议"
            request={async () => [
              { label: 'MQTT', value: 'MQTT' },
              { label: 'COAP', value: 'COAP' },
              { label: 'LWM2M', value: 'LWM2M' },
              { label: 'SNMP', value: 'SNMP' },
              { label: 'REST', value: 'REST' },
            ]}
            placeholder="Please select a country"
            rules={[{ required: true, message: ' ' }]}
          />

          <ProFormSelect
            width="md"
            name="contentType"
            label="编码格式"
            request={async () => [
              { label: 'BYTE', value: 'BYTE' },
              { label: 'JSON', value: 'JSON' },
              { label: 'PROTO', value: 'PROTO' },
              { label: 'AVRO', value: 'AVRO' },
            ]}
            placeholder="Please select a country"
            rules={[{ required: true, message: ' ' }]}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText width="md" name="host" label="IP地址" placeholder="请输入名称" />
          <ProFormText width="md" name="port" label="端口号" placeholder="请输入名称" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText width="md" name="host" label="URL" placeholder="请输入名称" />
          <ProFormText width="md" name="port" label="坐标" placeholder="请输入名称" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            width="md"
            name="dataModel"
            label="数据模型"
            request={() => getDataModel('') as any}
            placeholder="Please select a country"
            rules={[{ required: true, message: ' ' }]}
            fieldProps={{
              //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
              onSelect: (val: any, option: any) => onSelect(val, option),
            }}
          />
          <ProFormText width="md" name="uri" label="uri" placeholder="请输入名称" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            width="md"
            name="type"
            label="类型"
            request={async () => [
              { label: '接入', value: 'IN' },
              { label: '接出', value: 'OUT' },
            ]}
            placeholder="Please select a country"
            rules={[{ required: true, message: ' ' }]}
          />
          <ProFormTextArea width="md" name="note" label="描述" placeholder="请输入名称" />
        </ProForm.Group>
      </DrawerForm>

      {/* 查看详情 */}
      <ModalForm
        title="设备详情"
        visible={modalVisit}
        onFinish={async (values: any) => {
          return true;
        }}
        onVisibleChange={setModalVisit}
        autoFocusFirstInput
        modalProps={{
          onCancel: () => console.log('run'),
        }}
        submitTimeout={2000}
      >
        <Tabs defaultActiveKey="1" centered>
          <Tabs.TabPane tab="设备详情" key="1">
            <Card style={{ width: '30% ', marginBottom: '30px' }}>
              <Meta
                avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                title="设备名称"
                description={
                  <div>
                    <p>设备型号</p>
                    <div>
                      {' '}
                      <Tag color="#2db7f5">IP地址</Tag>
                    </div>
                  </div>
                }
              />
            </Card>
            <h4>数据传输</h4>
            <Tag color="#2db7f5">MQTT</Tag>
            <ProForm.Group>
              <ProFormText name="name" width="md" label="URL" placeholder="请输入名称" />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormSelect
                width="md"
                name="contentType"
                label="编码格式"
                request={async () => [
                  { label: 'BYTE', value: 'BYTE' },
                  { label: 'JSON', value: 'JSON' },
                  { label: 'PROTO', value: 'PROTO' },
                  { label: 'AVRO', value: 'AVRO' },
                ]}
                placeholder="Please select a country"
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormSelect
                width="md"
                name="dataModel"
                label="数据模型"
                request={() => getDataModel('') as any}
                placeholder="Please select a country"
                fieldProps={{
                  //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                  onSelect: (val: any, option: any) => onSelect(val, option),
                }}
              />
            </ProForm.Group>
          </Tabs.TabPane>
          <Tabs.TabPane tab="报警规则" key="2">
            <Collapse defaultActiveKey={['1']}>
              <Panel header="规则标题" key="1"></Panel>
            </Collapse>
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                addRule();
              }}
            >
              新增规则
            </Button>
          </Tabs.TabPane>
        </Tabs>
      </ModalForm>

      {/* 规则新增 */}
      <ModalForm
        title="规则新增"
        visible={modalVisit2}
        onFinish={async (values: any) => {
          return true;
        }}
        onVisibleChange={setModalVisit2}
        autoFocusFirstInput
        modalProps={{
          onCancel: () => console.log('run'),
        }}
        submitTimeout={2000}
      >
        <ProForm.Group>
          <ProFormSelect
            width="md"
            name="dataModel"
            label="数据模型"
            request={() => getDataModel('') as any}
            placeholder="Please select a country"
            fieldProps={{
              //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
              onSelect: (val: any, option: any) => onSelect(val, option),
            }}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText width="md" name="host" label="标题" placeholder="请输入名称" />
          <ProFormText width="md" name="port" label="名称" placeholder="请输入名称" />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSelect
            width="md"
            name="type"
            label="类型"
            request={async () => [
              { label: '接入', value: 'IN' },
              { label: '接出', value: 'OUT' },
            ]}
            placeholder="Please select a country"
            rules={[{ required: true, message: ' ' }]}
          />
          <ProFormDigit label="次数" name="input-number" min={1} max={10} />
        </ProForm.Group>
        <EditableProTable<DataSourceType>
          rowKey="id"
          headerTitle="条件规则"
          maxLength={5}
          recordCreatorProps={
            position !== 'hidden'
              ? {
                position: position as 'top',
                record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
              }
              : false
          }
          loading={false}
          columns={columnsEditableProTable}
          request={async () => ({
            data: defaultData,
            total: 3,
            success: true,
          })}
          value={dataSource}
          onChange={setDataSource}
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              console.log(rowKey, data, row);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </ModalForm>
    </PageContainer>
  );
};
