import ButtonComp from '@/components/ButtonComp';
import ContentWarp from '@/components/ContentWarp';
import { managerSystemConfigList, managerSystemEditOrAdd, unitAddressList } from '@/services/register';
import { rowClassName } from '@/utils';
import { Form, Input, Pagination, Radio, Select, Table, message } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.less'
import { useLocation, useParams, history } from 'umi';
import eventBus from '@/utils/eventBus';

const { TextArea } = Input;

export default function Page() {
  const urlParams = useParams();
  const location = useLocation()

  const [tableData, setTableData] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [layer, setLayer] = useState(1);
  const [managerSysType, setManagerSysType] = useState(1);
  const [content, setContent] = useState('');
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [unitList, setUnitList] = useState([]);

  let sysData = localStorage.getItem(`${urlParams?.fileType}`);
  let info = sysData ? JSON.parse(sysData) : null;

  const columns: any = [
    { title: '单位名称', dataIndex: 'unitName', key: 'unitName', align: 'center',render: (text: any) => text || '--' },
    { title: '系统名称', dataIndex: 'sysName', key: 'sysName', align: 'center' ,render: (text: any) => text || '--' },
    { title: '实体标识', dataIndex: 'sysEntityId', key: 'sysEntityId', align: 'center' ,render: (text: any) => text || '--'},
    { title: '310标识', dataIndex: 'sysMarkId', key: 'sysMarkId', align: 'center' ,render: (text: any) => text || '--'},
    { title: '系统型号', dataIndex: 'sysType', key: 'sysType', align: 'center' ,render: (text: any) => text || '--'},
    { title: '管理盘号', dataIndex: 'diskNumber', key: 'diskNumber', align: 'center' ,render: (text: any) => text || '--'},
    { title: '所属网络', dataIndex: 'name', key: 'name', align: 'center' ,render: (text: any) => text || '--'},
    { title: 'Ⅰ型隔离器外网IP', dataIndex: 'isolatorExternalIp', key: 'isolatorExternalIp', align: 'center' ,render: (text: any) => text || '--'},
    { title: '电话号码', dataIndex: 'telephone', key: 'telephone', align: 'center' ,render: (text: any) => text || '--'},
    { title: '联系人', dataIndex: 'contacts', key: 'contacts', align: 'center' ,render: (text: any) => text || '--'},
    { title: '联系方式', dataIndex: 'contactsInfo', key: 'contactsInfo', align: 'center' ,render: (text: any) => text || '--'},
    { title: '席位名称', dataIndex: 'seatName', key: 'seatName', align: 'center' ,render: (text: any) => text || '--'}
  ]

  useEffect(() => {
    getUnitList()
    initForm()
  }, [])

  useEffect(() => {
    getList();
    setSelectedRowKeys([])
  }, [pageNumber]);

  const getUnitList = () => {
    unitAddressList({ pageNum: 1, pageSize: 50 }).then((res: any) => {
      if (res.result == 'success') {
        setUnitList(res.data[0].list)
      }
    })
  }

  const getList = () => {
    managerSystemConfigList({ pageNumber, pageSize }).then((res) => {
      if (res?.result == "success") {
        setTotal(res.data[0].total)
        setTableData(res.data[0].list)
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

  const initForm = () => {
    form.resetFields()
    setManagerSysType(1)
    setContent('')
  }

  const updateList = () => {
    pageNumber == 1 ? getList() : setPageNumber(1);
  }


  const onFinish = (values: any) => {
    let params = {
      level: layer,
      photoUrl: "",
      managerSysType,
      content,
      ...values
    }

    if (layer == 2) {
      params.isolatorIntranetIp = '199.66.33.33'
    }

    managerSystemEditOrAdd(params).then((res) => {
      if (res?.result == "success") {
        message.success('添加成功');
        initForm();
        updateList();
        eventBus.emit('getDeviceRegisterList');
      } else {
        message.error(res?.errorMsg);
      }
    })
  };

  const pageOnChange = (pageNumber: number) => {
    setPageNumber(pageNumber);
  }

  const onShowSizeChange = (current: any, pageSize: any) => {
    setpageSize(pageSize);
    getList();
  }


  return (
    <div>
      <div className='flex_jB'>
        <ContentWarp text={'注册信息'} style={{ width: 'calc(72% - 25px)', minHeight: 400, }}>
          <div className='pd20'>
            <Radio.Group value={layer} onChange={(e) => {
              setLayer(e.target.value)
              initForm()
            }}>
              <Radio value={0} disabled style={{ marginRight: 30 }}> 上级 </Radio>
              <Radio value={1} style={{ marginRight: 30 }}> 本级 </Radio>
              <Radio value={2} style={{ marginRight: 30 }}> 下级 </Radio>
              <Radio value={3} disabled> 专用 </Radio>
            </Radio.Group>

            <div className='mb10 mt20 flex_aiC'>
              <div style={{ marginRight: 40 }}>级别：{layer}</div>
              <div className='mr16'>管理系统类型：</div>
              <Radio.Group value={managerSysType} onChange={(e) => { setManagerSysType(e.target.value) }}>
                <Radio value={1} style={{ marginRight: 20 }}> 密钥分发平台 </Radio>
                <Radio value={2} > 核心区安全隔离器 </Radio>
              </Radio.Group>
            </div>

            {
              (layer == 1 || layer == 2) ?
                <Form
                  form={form}
                  onFinish={onFinish}
                  className={styles.formSty}
                >
                  <div className='flex_jB' style={{ flexWrap: 'nowrap' }}>
                    <div style={{ width: '50%', minWidth: 450 }}>
                      <div className='flex_fw'>
                        <Form.Item name="unitName" label="单位名称" rules={[{ required: true, message: '请选择单位名称' },]}>
                          <Select
                            placeholder="请选择单位名称"
                            style={{ width: 200 }}
                            options={unitList}
                            fieldNames={{ label: 'unitName', value: 'unitName' }}
                          />
                        </Form.Item>
                        <ButtonComp text={'定位'} style={{ margin: '20px 0 0px 20px' }} onClick={() => {
                          let obj: any = {
                            selectVal: 6,
                            active: 2,
                            activeName: '位置管理',
                          }
                          localStorage.setItem(`${urlParams?.fileType}`, JSON.stringify({ ...info, layoutInfo: obj }))
                          history.push(`/registerManage/unitLocation/${urlParams?.fileType}${location?.search}`)
                        }} />
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="sysName" label="系统名称" rules={[{ required: true, message: '请输入系统名称' },]}>
                          <Input placeholder="请输入系统名称" />
                        </Form.Item>
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="sysEntityId" label="实体标识" rules={[{ required: true, message: '请输入实体标识' },]}>
                          <Input placeholder="请输入实体标识" />
                        </Form.Item>
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="sysMarkId" label="310标识" rules={[{ required: true, message: '请输入310标识' },]}>
                          <Input placeholder="请输入310标识" />
                        </Form.Item>
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="isolatorExternalIp" label="Ⅰ型隔离器外网IP" rules={[{ required: true, message: '请输入Ⅰ型隔离器外网IP' },]}>
                          <Input placeholder="请输入Ⅰ型隔离器外网IP" />
                        </Form.Item>
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="managerArea" label="管理区域" rules={[{ required: true, message: '请选择管理区域' },]}>
                          <Select
                            placeholder="请选择管理区域"
                            style={{ width: 200 }}
                            options={[
                              { label: '安徽', value: '安徽' },
                              { label: '北京', value: '北京' },
                              { label: '广州', value: '广州' }
                            ]}>
                          </Select>
                        </Form.Item>
                      </div>
                      {
                        layer == 2 &&
                        <div className='flex_aiC'>
                          <Form.Item name="diskNumber" label="管理盘号" rules={[{ required: true, message: '请输入管理盘号' },]}>
                            <Input placeholder="请输入管理盘号" />
                          </Form.Item>
                          <ButtonComp text={'选择'} style={{ margin: '20px 0 0px 20px' }} onClick={() => { }} />
                        </div>
                      }
                    </div>
                    <div style={{ width: '50%', minWidth: 400 }}>
                      <div className='flex_aiC'>
                        <Form.Item name="telephone" label="电话号码">
                          <Input placeholder="请输入电话号码" />
                        </Form.Item>
                      </div>
                      {
                        layer == 1 && <>
                          <div className='flex_aiC'>
                            <Form.Item name="isolatorIntranetIp" label="Ⅰ型隔离器内网IP" rules={[{ required: true, message: '请输入Ⅰ型隔离器内网IP' },]}>
                              <Input placeholder="请输入Ⅰ型隔离器内网IP" />
                            </Form.Item>
                          </div>
                          <div className='flex_aiC'>
                            <Form.Item name="pwdServerIp" label="密钥编制服务器IP">
                              <Input placeholder="请输入密钥编制服务器IP" />
                            </Form.Item>
                          </div>
                        </>
                      }
                      <div className='flex_aiC'>
                        <Form.Item name="contactsInfo" label="联系方式" >
                          <Input placeholder="请输入联系方式" />
                        </Form.Item>
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="contacts" label="联系人" >
                          <Input placeholder="请输入联系人" />
                        </Form.Item>
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="seatName" label="席位名称">
                          <Input placeholder="请输入席位名称" />
                        </Form.Item>
                      </div>
                      <div className='flex_aiC'>
                        <Form.Item name="sysType" label="系统型号">
                          <Select
                            placeholder="请选择系统型号"
                            style={{ width: 200 }}
                            options={[
                              { label: '型号1', value: 1 },
                              { label: '型号2', value: 2 },
                              { label: '型号3', value: 3 }
                            ]}>
                          </Select>
                        </Form.Item>
                      </div>
                    </div>
                  </div>
                </Form> :
                <div></div>
            }
          </div>
        </ContentWarp>

        <div className='ml20' style={{ height: 'auto', width: '27%', marginTop: 8 }}>
          <div className='mb10'>设备照片</div>
          <div style={{ height: "calc(50% - 27px)", border: '1px solid #d8d8d8', background: '#fff' }}>
            <img src={require('../../../../../assets/images/device_img.png')} style={{ width: '100%', height: '100%' }} />
          </div>
          <div className='mb10 mt20'>备注</div>
          <TextArea
            style={{ height: "calc(50% - 44px)", resize: 'none' }}
            value={content}
            onChange={(e) => { setContent(e.target.value) }}
            placeholder="请输入备注" />
        </div>
      </div>

      <div className='flex_jE mt30 mb30'>
        <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'修改'} onClick={() => { }} />
        <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'添加'} onClick={() => form.submit()} />
        <ButtonComp type={'cancel'} text={'删除'} onClick={() => { }} />
      </div>

      <Table
        scroll={tableData.length > 0 ? { y: 41 * 5 } : {}}
        pagination={false}
        bordered
        columns={columns}
        dataSource={tableData}
        rowKey={(record: any) => record?.id}
        rowClassName={rowClassName}
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedKeys: any) => {
            setSelectedRowKeys(selectedKeys);
          }
        }}
      />

      {total > 0 && <div className='flex_aiC_jB mt20'>
        <div>共 {total} 条</div>
        <Pagination
          current={pageNumber}
          pageSize={pageSize}
          total={total}
          showQuickJumper
          onChange={pageOnChange}
          onShowSizeChange={onShowSizeChange}
        />
      </div>}
    </div>
  );
}