/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable default-case */
/* eslint-disable react/jsx-no-undef */
import React, { useState, useEffect } from 'react';
import {
  Row,
  Col,
  Select,
  Spin,
  Table,
  Input,
  Button,
  Space,
  Tooltip,
  Popconfirm,
  notification,
} from 'antd';
import {
  SyncOutlined,
  PlusOutlined,
  ArrowUpOutlined,
  EditTwoTone,
  DeleteOutlined,
  VideoCameraOutlined,
  ZoomInOutlined,
  CaretUpFilled,
  CaretDownFilled,
} from '@ant-design/icons';
import voca from 'voca';
import styles from './index.less';
import { GetVideoConfigList, deleteInsertVideoConfig } from '@/services/videoManger/videoManger';
import AddModal from './AddModal';
import CheckModal from './CheckModal';
import VideoModal from './VideoModal';
import DHModal from './DHModal';
import HKModal from './HKModal';
import AddAllModal from './AddAllModal';

const videoManager = () => {
  const [configurationType, setConfigurationType] = useState('1');
  const [loading, setLoading] = useState(false); // 加载
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const { Search } = Input;
  const [addVisible, setAddVisible] = useState(false);
  const [checkVisible, setCheckVisible] = useState(false);
  const [videoVisible, setVideoVisible] = useState(false);
  const [type, setType] = useState('萤石云'); // 视频厂商类型
  const [type1, setType1] = useState('bb'); // 表单样式
  const [kind, setKind] = useState('');
  const [tableData, setTableData] = useState('');
  const [flag, setFlag] = useState(0);
  const [obj, setObj] = useState({});
  const [show1, setShow1] = useState('block');
  const [show2, setShow2] = useState('none');
  const [addDHVisible, setAddDHVisible] = useState(false);
  const [addHKVisible, setAddHKVisible] = useState(false);
  const [showSearchStyle, setShowSearchStyle] = useState(false); // 是否显示模糊查询样式
  const [addAllVisible, setAddAllVisible] = useState(false);

  const columns = [
    {
      title: '名称',
      dataIndex: 'Name',
      key: 'Name',
      // width: 200,
      align: 'center',
      onCell: () => ({
        style: {
          maxWidth: 200,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: item => (
        <Tooltip placement="topLeft" title={item}>
          {searchStyle(item)}
        </Tooltip>
      ),
    },
    {
      title: '视频厂商',
      dataIndex: 'VideoManufacturer',
      key: 'VideoManufacturer',
      width: 150,
      align: 'center',
    },
    {
      title: '登录名',
      dataIndex: 'LoginName',
      key: 'LoginName',
      // width: 350,
      align: 'center',
      render: item => searchStyle(item),
    },
    // {
    //   title: '登录密码',
    //   dataIndex: 'LoginPwd',
    //   key: 'LoginPwd',
    //   width: 350,
    //   align: 'center',
    // },
    {
      title: '设备编码',
      dataIndex: 'EquipmentCode',
      key: 'EquipmentCode',
      width: 200,
      align: 'center',
      render: item => searchStyle(item),
    },
    {
      title: '通道ID',
      dataIndex: 'PassageId',
      key: 'PassageId',
      // width: 150,
      align: 'center',
      onCell: () => ({
        style: {
          maxWidth: 150,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: item => (
        <Tooltip placement="topLeft" title={item}>
          {item}
        </Tooltip>
      ),
    },
    {
      title: '刻录机名称',
      dataIndex: 'RecorderName',
      key: 'RecorderName',
      width: 150,
      align: 'center',
      onCell: () => ({
        style: {
          maxWidth: 150,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer',
        },
      }),
      render: item => (
        <Tooltip placement="topLeft" title={item}>
          {item}
        </Tooltip>
      ),
    },
    {
      // title: '录入时间',
      dataIndex: 'CreateTime',
      key: 'CreateTime',
      // width: 150,
      align: 'center',
      title: (
        <div>
          录入时间
          <Tooltip title="点击降序">
            <CaretUpFilled
              style={{
                display: show1,
                color: '#1890ff',
                marginTop: '-13px',
                marginLeft: '60%',
              }}
              onClick={() => shengxu()}
            />
          </Tooltip>
          <Tooltip title="点击升序">
            <CaretDownFilled
              style={{
                display: show2,
                color: '#1890ff',
                marginTop: '-13px',
                marginLeft: '60%',
              }}
              onClick={() => jiangxu()}
            />
          </Tooltip>
        </div>
      ),
    },
    {
      title: '操作',
      dataIndex: '',
      key: '',
      align: 'center',
      render: record => (
        <Space size="middle">
          <Tooltip title="编辑">
            <EditTwoTone onClick={() => edit(record)} style={{ fontSize: '16px' }} />
          </Tooltip>
          <Tooltip title="预览">
            <VideoCameraOutlined
              onClick={() => preView(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip>
          <Tooltip title="查看">
            <ZoomInOutlined
              onClick={() => check(record)}
              style={{ fontSize: '16px', color: '#1890FF' }}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              placement="bottomRight"
              title={
                <p>
                  即将删除 <span className={styles.redText}>{voca.stripTags(record.Name)}</span>
                  ,是否确认删除?
                </p>
              }
              okText="确认"
              cancelText="取消"
              onConfirm={() => delete1(record)}
            >
              <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 模糊查询匹配的样式
  const searchStyle = val => {
    let n;
    if (showSearchStyle) {
      n = val.replace(new RegExp(searchWord, 'g'), `<span style='color:red'>${searchWord}</span>`);
    } else {
      n = val;
    }
    return <div dangerouslySetInnerHTML={{ __html: n }} />;
  };

  const edit = record => {
    if (type == '大华') {
      setAddDHVisible(true);
    } else if (type == '海康ISC') {
      setAddHKVisible(true);
    } else {
      setAddVisible(true);
    }

    setKind('edit');
    setObj(record);
  };
  const preView = record => {
    setVideoVisible(true);
    setObj(record);
  };
  const check = record => {
    setCheckVisible(true);
    setObj(record);
    console.log(record);
  };
  const delete1 = record => {
    deleteInsertVideoConfig({ Id: record.Id }).then(res => {
      if (res.msg === 'Ok') {
        notification.success({
          message: '提示',
          duration: 3,
          description: '删除成功',
        });
        setFlag(flag + 1);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };
  const shengxu = () => {
    setShow1('none');
    setShow2('block');
    setLoading(true);
    GetVideoConfigList({
      VideoType: type,
      pageIndex: 1,
      pageSize: 1000,
      IsAsc: true,
    }).then(res => {
      setLoading(false);
      if (res.msg === 'Ok') {
        setTableData(res.data.list);
      }
    });
  };
  const jiangxu = () => {
    setShow2('none');
    setShow1('block');
    setLoading(true);
    GetVideoConfigList({
      VideoType: type,
      pageIndex: 1,
      pageSize: 1000,
      IsAsc: false,
    }).then(res => {
      setLoading(false);
      if (res.msg === 'Ok') {
        setTableData(res.data.list);
      }
    });
  };
  useEffect(() => {
    setLoading(true);
    getData();
  }, []);

  useEffect(() => {
    setLoading(true);
    getData();
    setShowSearchStyle(false);
  }, [type, flag]);

  const getData = () => {
    GetVideoConfigList({
      VideoType: type,
      pageIndex: 1,
      pageSize: 1000,
      QueryWhere: searchWord,
    }).then(res => {
      setLoading(false);
      if (res.msg === 'Ok') {
        setTableData(res.data.list);
      }
    });
  };
  const selectChange = value => {
    setConfigurationType(value);
    switch (value) {
      case '1':
        setType('萤石云');
        setType1('bb');
        break;
      case '2':
        setType('海康');
        setType1('bb');
        break;
      case '3':
        setType('海康1.2');
        setType1('aa');
        break;
      case '4':
        setType('海康NVR');
        setType1('aa');
        break;
      case '5':
        setType('大华');
        break;
      case '6':
        setType('海康ISC');
        break;
    }
  };

  // 获取搜索框的值
  const handleSearch = e => {
    setSearchWord(e.target.value);
  };
  // 搜索
  const submitSearchUser = () => {
    GetVideoConfigList({
      VideoType: type,
      pageIndex: 1,
      pageSize: 1000,
      QueryWhere: searchWord,
    }).then(res => {
      if (res.msg === 'Ok') {
        setShowSearchStyle(true);
        setTableData(res.data.list);
      }
    });
  };
  // 重置
  const handleReset = () => {
    setConfigurationType('1');
    setSearchWord('');
    setType('萤石云');
    setType1('bb');
    setFlag(flag + 1);
  };

  // 新增
  const addVideo = () => {
    console.log(type);
    if (type == '大华') {
      setAddDHVisible(true);
    } else if (type == '海康ISC') {
      console.log(1212);
      setAddHKVisible(true);
    } else {
      setAddVisible(true);
    }
    setKind('add');
  };

  const addAll = () => {
    setAddAllVisible(true);
  };

  const onSubmit = () => {
    setAddAllVisible(false);
    setAddDHVisible(false);
    setAddHKVisible(false);
    setAddVisible(false);
    setFlag(flag + 1);
  };
  return (
    <div className={styles.videoManagerContainer}>
      <Row className={styles.head}>
        <Col span={24}>
          <span>配置类型:</span>
          <Select
            defaultValue="萤石云"
            value={configurationType}
            onChange={selectChange}
            className={styles.sel}
          >
            <Option value="1">萤石云</Option>
            <Option value="2">海康</Option>
            <Option value="3">海康1.2</Option>
            <Option value="4">海康NVR</Option>
            <Option value="5">大华</Option>
            <Option value="6">海康ISC</Option>
          </Select>
          <span style={{ marginLeft: '50px' }}>快速搜索:</span>
          <Search
            style={{ width: 260 }}
            placeholder="请输入名称,登录名,设备编码查询"
            onSearch={submitSearchUser}
            onChange={e => handleSearch(e)}
            enterButton
            value={searchWord}
          />
          <Button
            icon={<SyncOutlined className={styles.icon} />}
            onClick={handleReset}
            style={{
              marginLeft: '30px',
              verticalAlign: 'middle',
              marginTop: '-3px',
            }}
          >
            重置
          </Button>
          {/* <Button
            icon={<PlusOutlined className={styles.icon} />}
            onClick={addVideo}
            style={{
              float: 'right',
              verticalAlign: 'middle',
              // marginTop: '-3px',
            }}
          >
            新增
          </Button> */}
          <Button
            icon={<PlusOutlined className={styles.icon} />}
            onClick={addAll}
            style={{
              float: 'right',
              verticalAlign: 'middle',
              // marginTop: '-3px',
            }}
          >
            新增
          </Button>
        </Col>
      </Row>
      <Spin spinning={loading} tip="loading">
        <div className={styles.table}>
          {tableData.length > 0 ? (
            <Table
              size="small"
              bordered
              rowKey={record => record.Id}
              columns={columns}
              dataSource={tableData}
              scroll={{ y: 'calc(100vh - 210px)', x: 'max-content' }}
              onRow={record => ({
                onDoubleClick: event => {
                  event.stopPropagation();
                  edit(record);
                }, // 双击
              })}
              pagination={{
                showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 20,
                showQuickJumper: true,
                showSizeChanger: true,
              }}
            />
          ) : (
            <Table
              size="small"
              bordered
              rowKey={record => record.Id}
              columns={columns}
              dataSource={tableData}
              scroll={{ y: 'calc(100vh - 116px)', x: 'max-content' }}
              onRow={record => ({
                onDoubleClick: event => {
                  event.stopPropagation();
                  edit(record);
                }, // 双击
              })}
              pagination={{
                showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                pageSizeOptions: [10, 20, 50, 100],
                defaultPageSize: 20,
                showQuickJumper: true,
                showSizeChanger: true,
              }}
            />
          )}
        </div>
      </Spin>
      <AddModal
        visible={addVisible}
        onCancel={() => {
          setAddVisible(false);
        }}
        okText="确认"
        cancelText="取消"
        type={type}
        type1={type1}
        kind={kind}
        obj={obj}
        callBackSubmit={onSubmit}
      />
      <AddAllModal
        visible={addAllVisible}
        onCancel={() => {
          setAddAllVisible(false);
        }}
        okText="确认"
        cancelText="取消"
        type={type}
        type1={type1}
        kind={kind}
        obj={obj}
        callBackSubmit={onSubmit}
      />
      <CheckModal
        visible={checkVisible}
        onCancel={() => {
          setCheckVisible(false);
        }}
        okText="确认"
        cancelText="取消"
        type={type}
        type1={type1}
        obj={obj}
      />
      <VideoModal
        visible={videoVisible}
        onCancel={() => {
          setVideoVisible(false);
        }}
        obj={obj}
      />
      <DHModal
        visible={addDHVisible}
        onCancel={() => {
          setAddDHVisible(false);
        }}
        okText="确认"
        cancelText="取消"
        type={type}
        kind={kind}
        obj={obj}
        callBackSubmit={onSubmit}
      />
      <HKModal
        visible={addHKVisible}
        onCancel={() => {
          setAddHKVisible(false);
        }}
        okText="确认"
        cancelText="取消"
        type={type}
        kind={kind}
        obj={obj}
        callBackSubmit={onSubmit}
      />
    </div>
  );
};

export default videoManager;