/* 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 {
  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 [userDataSource, setUserDataSource] = useState<any[]>([]);
  // const [groupDataSource, setGroupDataSource] = useState<any[]>([]);
  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) => {
      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 || {};
            const obj: any = { ...item };
            delete obj.id;
            if (type === 1) {
              list.push({
                table_id: `user_${user_id}`,
                id: user_id,
                name: user_name,
                user_name: user_name,
                type: type,
              });
            } else {
              list.push({
                table_id: `group_${user_group_id}`,
                id: user_group_id,
                name: user_group_name,
                type: type,
              });
            }
          });
          setUserDataSource(data);
          const initialValues = { user_list: list };
          form.setFieldsValue(initialValues);
        }
      }
    });
  }, [visible, form, recordData]);

  const onBind = (payload: any) => {
    bindUserAdd(payload)
      .then((res: any) => {
        const { code } = res || {};
        if (code === ERROR_CODE) {
          message.success('绑定成功');
          onOk();
        } else {
          message.error('绑定失败');
        }
      })
      .catch(() => {});
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const { user_list = [] } = values || {};
      const list: any[] = [];
      user_list.forEach((item: any) => {
        const { type, id } = item || {};
        if (type === 1) {
          // 用户
          const obj: any = {
            device_id,
            device_group_id,
            type: type,
            user_id: id,
          };
          const newData = userDataSource.filter(
            (record) => record.user_id === item.id && record.type === 1,
          );
          if (newData && newData.length === 1) {
            obj.id = newData[0].id;
          }
          list.push(obj);
        } else {
          //用户分组
          const obj: any = {
            device_id,
            device_group_id,
            type: type,
            user_group_id: id,
          };
          const newData = userDataSource.filter(
            (record) => record.user_group_id === item.id && record.type === 2,
          );
          if (newData && newData.length === 1) {
            obj.id = newData[0].id;
          }
          list.push(obj);
        }
      });
      const payload = {
        data: list,
        device_id:device_id,
      };
      onBind(payload);
    } 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={null}
      // 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}
          onFinish={handleOk}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 19 }}
          layout="horizontal"
          style={{ paddingTop: '20px', paddingBottom: '20px' }}
        >
          <Form.Item
            name="user_list"
            label="选择用户"
            rules={[{ required: false, message: '请选择绑定用户' }]}
          >
            <SelectedTable orgTreeData={orgTreeData} />
          </Form.Item>
          {/* <Form.Item
            name="description"
            label="描述内容"
            rules={[{ required: false, message: '请输入描述内容' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item> */}
          <Form.Item label={null}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginRight: '20px' }}
            >
              确定
            </Button>
            <Button onClick={onCancel}>取消</Button>
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default BindUserModal;
