import {
  vehicleModelsUrlConnect, addConnect,
  delConnect,
  getConnect,
  updateConnect,
} from '@/services/SearchVehicle/searchVehicle';
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, Tooltip } 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,
      search: false,
    },
    {
      title: '车型',
      dataIndex: 'level',
      search: false,
      render: (text, record, _, action) => [
        <Tag color="#f50">{record?.level?.code}</Tag>,
        <Tag color="#2db7f5">{record?.level?.name}</Tag>
      ],
    },
    {
      title: '车系',
      dataIndex: 'level',
      search: false,
      render: (text, record, _, action) => [
        <div>{record?.serial?.type?.name}</div>
      ],
    },
    {
      title: '车型描述',
      dataIndex: 'note',
      search: false,
    },
    {
      title: '车企',
      dataIndex: 'record',
      search: false,
      render: (text, record, _, action) => [
        <div>{record?.serial?.brand?.name}</div>
      ],
    },
    {
      title: '车企描述',
      dataIndex: 'record',
      search: false,
      ellipsis: true,
      render: (text, record, _, action) => [
        <Tooltip placement="topLeft" title={record?.serial?.brand?.note}>
          <span>{record?.serial?.brand?.note}</span>
        </Tooltip>

      ],
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            onEdit(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          title="确认删除?"
          onConfirm={(e) => {
            confirm(record);
          }}
          onCancel={(e) => {
            cancel(record);
          }}
          okText="是"
          cancelText="否"
          key={record.id}
        >
          <a target="_blank" key="delete">
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];
  return (
    <PageContainer>
      {/* table主体 */}
      <ProTable<API.IOT.Device>
        headerTitle="车型管理"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={vehicleModelsUrlConnect 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>,
        ]}
      />

      {/* 左侧Drawer */}
      <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: ' ' }]}
          />
          <ProFormTextArea width="md" name="note" label="车型描述" placeholder="请输入车型描述" />
        </ProForm.Group>
        {/* <ProForm.Group>
          <ProFormText
            name="name"
            width="md"
            label="车企"
            placeholder="请输入车企"
            rules={[{ required: true, message: ' ' }]}
          />
          <ProFormTextArea width="md" name="note" label="车企描述" placeholder="请输入车企描述" />
        </ProForm.Group> */}
      </DrawerForm>

    </PageContainer>
  );
};
