import ButtonComp from '@/components/ButtonComp';
import ContentWarp from '@/components/ContentWarp';
import { rowClassName } from '@/utils';
import { Form, Input, Modal, Pagination, Select, Table, Upload, message } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.less'
import { deviceHardEditOrAdd, deviceHardPage, unitAddressList } from '@/services/register';
import { useParams, history } from 'umi';
import SelectDiskDialog from './Dialog/selectDiskDialog';
import { fileStr, sysType, sysTypeStr } from '@/utils/sysType';
import eventBus from '@/utils/eventBus';

const { TextArea } = Input;

export default function Page() {
  const urlParams = useParams();
  let sysData = localStorage.getItem(`${urlParams?.fileType}`);
  let info = sysData ? JSON.parse(sysData) : null;

  const [tableData, setTableData] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();
  const [content, setContent] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [unitList, setUnitList] = useState([]);
  const [selectDisk, setSelectDisk] = useState(false); // 选择管理盘弹窗

  const columns: any = [
    { title: '单位名称', dataIndex: 'unitName', key: 'unitName', align: 'center' },
    { title: '设备名称', dataIndex: 'deviceName', key: 'deviceName', align: 'center' },
    { title: '实体标识', dataIndex: 'deviceEntityId', key: 'deviceEntityId', align: 'center' },
    { title: '310标识', dataIndex: 'deviceMarkId', key: 'deviceMarkId', align: 'center' },
    { title: '设备型号', dataIndex: 'deviceType', key: 'deviceType', align: 'center' },
    { title: '管理盘号', dataIndex: 'diskNumber', key: 'diskNumber', align: 'center' },
    { title: '所属网络', dataIndex: 'homeNetwork', key: 'homeNetwork', align: 'center' },
    { title: 'IP地址', dataIndex: 'ip', key: 'ip', align: 'center' },
    { title: '电话号码', dataIndex: 'telephone', key: 'telephone', align: 'center' },
    { title: '联系人', dataIndex: 'contacts', key: 'contacts', align: 'center' },
    { title: '联系方式', dataIndex: 'contactsInfo', key: 'contactsInfo', align: 'center' },
    { title: '席位名称', dataIndex: 'seatName', key: 'seatName', align: 'center' }
  ]

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

  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 = () => {
    deviceHardPage({ 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()
    setContent('')
  }

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

  const onFinish = (values: any) => {
    let str: string = sysType[urlParams?.fileType] + fileStr[urlParams?.fileType]
    let params = {
      sysType: sysTypeStr[str],
      level: 1,
      photoUrl: "",
      content,
      ...values
    }
    console.log("params", params);

    deviceHardEditOrAdd(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(70% - 25px)' }}>
          <div className='pd20'>
            <div >级别：1</div>
            <Form
              form={form}
              onFinish={onFinish}
              className={styles.formSty}
            >
              <div className='flex_aiC_jB' style={{ flexWrap: 'nowrap' }}>
                <div style={{ width: '55%', 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="deviceName" label="设备名称" rules={[{ required: true, message: '请输入设备名称' }]}>
                      <Input placeholder='请输入设备名称' />
                    </Form.Item>
                  </div>
                  <div className='flex_fw'>
                    <Form.Item name="deviceType" label="设备型号" rules={[{ required: true, message: '请选择设备型号' }]}>
                      <Select
                        placeholder="请选择设备型号"
                        style={{ width: 200 }}
                        options={[
                          { label: '设备型号1', value: '设备型号1' },
                          { label: '设备型号2', value: '设备型号2' },
                          { label: '设备型号3', value: '设备型号3' },
                        ]} />
                    </Form.Item>
                    <Form.Item style={{ width: 60 }} name="version" label="版本">
                      <Select style={{ width: 120 }} placeholder="请选择" />
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="deviceNumber" label="设备编号" rules={[{ required: true, message: '请输入设备编号' }]}>
                      <Input placeholder="请输入设备编号" />
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="deviceEntityId" label="实体标识" rules={[{ required: true, message: '请输入实体标识' }]}>
                      <Input placeholder="请输入实体标识" />
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="deviceMarkId" label="310标识" rules={[{ required: true, message: '请输入310标识' }]}>
                      <Input placeholder="请输入310标识" />
                    </Form.Item>
                  </div>
                  <div className='flex_fw'>
                    <Form.Item name="diskNumber" label="管理盘号" rules={[{ required: true, message: '请选择管理盘号' }]}>
                      <Input disabled placeholder="请选择管理盘号" />
                    </Form.Item>
                    <ButtonComp text={'选择'} style={{ margin: '20px 0 0px 20px' }} onClick={() => setSelectDisk(true)} />
                  </div>
                </div>
                <div style={{ width: '45%', minWidth: 400 }}>
                  <div className='flex_aiC'>
                    <Form.Item name="homeNetwork" label="所属网络" rules={[{ required: true, message: '请选择所属网络' }]}>
                      <Select
                        placeholder="请选择所属网络"
                        style={{ width: 200 }}
                        options={[
                          { label: '指挥专网', value: '指挥专网' },
                          { label: '军事综合信息网', value: '军事综合信息网' },
                          { label: '资源管理网', value: '资源管理网' }
                        ]}>
                      </Select>
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="contacts" label="联系人" rules={[{ required: true, message: '请输入联系人' }]}>
                      <Input placeholder="请输入联系人" />
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="contactsInfo" label="联系方式" rules={[{ required: true, message: '请输入联系方式' }]}>
                      <Input placeholder="请输入联系方式" />
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="ip" label="IP地址" rules={[{ required: true, message: '请输入IP地址' }]}>
                      <Input placeholder="请输入IP地址" />
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="telephone" label="电话号码" rules={[{ required: true, message: '请输入电话号码' }]}>
                      <Input placeholder="请输入电话号码" />
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="connFlag" label="接入标志" rules={[{ required: true, message: '请选择接入标志' }]}>
                      <Select
                        placeholder="请选择接入标志"
                        style={{ width: 200 }}
                        options={[
                          { label: '接入', value: 1 },
                          { label: '未接入', value: 2 }
                        ]}>
                      </Select>
                    </Form.Item>
                  </div>
                  <div className='flex_aiC'>
                    <Form.Item name="seatName" label="席位名称" rules={[{ required: true, message: '请输入席位名称' }]}>
                      <Input placeholder="请输入席位名称" />
                    </Form.Item>
                  </div>
                </div>
              </div>
            </Form>
          </div>
        </ContentWarp>

        <div className='ml20' style={{ height: 'auto', width: '30%', 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_aiC_jB mt30 mb30'>
        <div className='flex_aiC'>
          <ButtonComp style={{ marginRight: 20 }} text={'批量设备注册'} onClick={() => { }} />
          <ButtonComp style={{ marginRight: 20 }} text={'批量导入导出'} onClick={() => { }} />
          <ButtonComp text={'密钥分发平台设备导入'} onClick={() => { }} />
        </div>
        <div className='flex_aiC'>
          <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'修改'} onClick={() => { }} />
          <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'添加'} onClick={() => form.submit()} />
          <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'注销'} onClick={() => { }} />
          <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'恢复'} onClick={() => { }} />
          <ButtonComp type={'cancel'} text={'删除'} onClick={() => { }} />
        </div>
      </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>}

      {/* 选择管理盘 */}
      <SelectDiskDialog 
        visibility={selectDisk} 
        onCancel={() => setSelectDisk(false)}
        onOk={(e) => {form.setFieldValue('diskNumber', e)}} />
    </div>
  );
}