/* eslint-disable array-callback-return */
// index.tsx
import { ERROR_CODE } from '@/constants/constants';
import { bindUserAdd, getBindUserList } from '@/services/terminal';
import { getGroupTree } from '@/services/userList';
import { Button, Form, message, Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import SelectedTable from '../selectedTable';
import styles from './index.less';

interface UserEditModalProps {
  //   visible: boolean;
  // orgTreeData?: User.OrganizationNode[];
  onCancel: () => void;
  onOk: (values?: any) => void;
  confirmLoading?: boolean;
  dataDetial?: Termial.ModalBaseNode;
  selectedOrg?: number;
}

const BindUserModal: React.FC<UserEditModalProps> = ({
  // orgTreeData,
  onCancel,
  onOk,
  confirmLoading = false,
  dataDetial,
}) => {
  const { recordData, visible } = dataDetial || {};
  const { device_id, device_group_id } = recordData || {};
  const [orgTreeData, setOrgTreeData] = useState<User.OrganizationNode[]>([]);
  const [form] = Form.useForm();

  const getGroupList = async () => {
    const params = {
      type: 1,
    };
    try {
      const result = await getGroupTree(params);
      console.log('result=====', result);
      const { code, data = [] } = result || {};
      if (code === ERROR_CODE) {
        if (data.length > 0) {
          const { children = [] } = data[0] || {};
          setOrgTreeData(children);
        }
      } else {
        message.error(result.message || '获取终端分组失败');
      }
    } catch (err) {
      message.error('获取终端分组失败');
    }
  };

  useEffect(() => {
    getGroupList();
  }, [visible]);

  useEffect(() => {
    if (!device_id) return;
    const payload = { device_id: device_id };
    getBindUserList(payload).then((res: any) => {
      console.log('res========', res);
      const { code, data = [] } = res || {};
      if (code === ERROR_CODE) {
        if (data && data.length > 0) {
          const list: any[] = [];
          data.map((item: any) => {
            const { type, user_id, user_name, user_group_id, user_group_name } =
              item || {};
            if (type === 1) {
              list.push({ record_id: user_id, name: user_name, ...item });
            } else {
              list.push({
                record_id: user_group_id,
                name: user_group_name,
                ...item,
              });
            }
          });
          const initialValues = { user_list: list, status: 1 };
          form.setFieldsValue(initialValues);
        }
      }
    });
  }, [visible, form, recordData]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const { user_list = [] } = values || {};
      const list: any[] = [];
      if (user_list && user_list.length > 0) {
        user_list.forEach((item: any) => {
          const { record_id, type, id } = item || {};
          if (type === 1) {
            // 用户
            list.push({
              user_id: record_id,
              id: id,
              device_id,
              device_group_id,
              type: type,
            });
          } else {
            //用户分组
            list.push({
              user_group_id: record_id,
              id: id,
              device_id: device_id,
              device_group_id,
              type: type,
            });
          }
        });
        const payload = {
          data: list,
        };
        bindUserAdd(payload)
          .then(() => {
            message.success('绑定成功');
            onOk();
          })
          .catch(() => {});
      }
      console.log('list=====', list);
      onOk(list);
    } catch (error) {
      message.error('请检查表单字段');
    }
  };

  return (
    <Modal
      title={'绑定用户'}
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      confirmLoading={confirmLoading}
      width={1200}
      maskClosable={false}
      centered={true}
      destroyOnHidden={true}
      cancelText="取消"
      okText="确定"
      footer={
        <div style={{ display: 'flex', justifyContent: 'right' }}>
          <Button
            type="primary"
            onClick={handleOk}
            style={{ marginRight: '20px' }}
          >
            确定
          </Button>
          <Button onClick={onCancel} style={{ marginRight: '20px' }}>
            取消
          </Button>
        </div>
      }
    >
      <div className={styles.model_content}>
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 19 }}
          layout="horizontal"
          style={{ paddingTop: '20px', paddingBottom: '20px' }}
        >
          <Form.Item
            name="user_list"
            label="选择用户"
            rules={[{ required: true, message: '请选择绑定用户' }]}
          >
            <SelectedTable orgTreeData={orgTreeData} />
          </Form.Item>
          {/* <Form.Item
            name="description"
            label="描述内容"
            rules={[{ required: false, message: '请输入描述内容' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item> */}
        </Form>
      </div>
    </Modal>
  );
};

export default BindUserModal;
