import styles from '../../../GLQ/index.less';
import { useEffect, useState } from 'react';
import { ConfigProvider, DatePicker, Form, Modal, Pagination, Radio, Select, Table, message } from 'antd';

import { rowClassName } from '@/utils';
import ButtonComp from '@/components/ButtonComp';
import moment from 'moment';
import { secretKey, secretList } from '@/services/my';
import { managerSysDataList } from '@/services/register';
import { sysTypeStr } from '@/utils/sysType';

export default function Page() {
  const [tableData, setTableData] = useState([]);
  const [tableData1, setTableData1] = useState<any>([]);
  const [visibility, setVisibility] = useState(false);
  const [form] = Form.useForm();
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRowKeys1, setSelectedRowKeys1] = useState([]);
  const [selectedData, setSelectedData] = useState();

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

  const columns: any = [
    {
      title: '产品名称', dataIndex: 'productName', key: 'productName', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '产品编号', dataIndex: 'productNum', key: 'productNum', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '装配情况', dataIndex: 'assemblySituation', key: 'assemblySituation', align: 'center', render: (text: any) => { return <span>{text || '--'}</span> },
    }
  ]

  const columns1: any = [
    {
      title: '序号', key: 'index', align: 'center', width: 80,
      render: (a: any, b: any, c: any) => { return <span>{c + 1}</span> },
    }, {
      title: '设备名称', dataIndex: 'deviceName', key: 'deviceName', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '管理实体标识', dataIndex: 'managerModelId', key: 'managerModelId', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '310标识', dataIndex: 'deviceMarkId', key: 'deviceMarkId', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '产品名称', dataIndex: 'productName', key: 'productName', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '产品编号', dataIndex: 'productNum', key: 'productNum', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '安装方式', dataIndex: 'installMethod', key: 'installMethod', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '分发状态', dataIndex: 'distType', key: 'distType', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '启用日期', dataIndex: 'activeDate', key: 'activeDate', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '终止日期', dataIndex: 'endDate', key: 'endDate', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '密钥套号', dataIndex: 'setNumber', key: 'setNumber', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '载体类型', dataIndex: 'carrierType', key: 'carrierType', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '输出日期', dataIndex: 'name', key: 'name', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }, {
      title: '协同管理标志', dataIndex: 'managementFlag', key: 'managementFlag', align: 'center',
      render: (text: any) => { return <span>{text || '--'}</span> },
    }
  ]

  const formItemSty = { width: 'auto', marginBottom: 20, marginRight: 30 };

  const initForm = () => {
    form.setFieldsValue({
      keyType: null,
      web: null,
      activeDate: null,
      endDate: null
    })
  }

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

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

  // 获取密钥体列表 
  const getList = () => {
    secretList({ pageNumber, pageSize }).then((res) => {
      if (res?.result == "success") {
        res.data[0].list = res.data[0].list.filter((val: any) => {
          return (['PT5',].includes(val?.content))
        })
        setTotal(res.data[0].list.length)
        setTableData(res.data[0].list)

        let arr: any = []
        arr = res.data[0].list.filter((val: any) => {
          return val?.assemblySituation == '未装配'
        })
        setTableData1([...arr])
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

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

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

  const disabledDate = (current: any) => {
    return current && current < moment().startOf('day');
  };

  // 校验是否少了步骤
  const onRules = async () => {
    // 校验管理系统管理盘数据维护列表是否有数据
    let stop = false
    await managerSysDataList({ pageNumber: 1, pageSize: 10 }).then((res) => {
      if (res?.result == "success") {
        if (res.data[0].length == 0) { stop = true }
      } else {
        message.error(res?.errorMsg);
      }
    })

    if (stop) {
      message.info('请先完成管理系统管理盘数据维护--数据导入！')
      return
    }

    if (selectedRowKeys1.length == 0) {
      message.info('请选择一条可装配的密钥体！')
      return
    }

    form.validateFields().then(() => {
      tableData1.forEach(e => {
        if (e.id == selectedRowKeys1[0]) { setSelectedData(e) }
      });
      setVisibility(true)
    })
  }

  // 过滤可装配列表
  const onchange = () => {
    let info = form.getFieldsValue();
    setSelectedRowKeys([])
    let arr: any = []
    arr = tableData.filter((item) => {
      if (item?.assemblySituation == '已装配') return

      if (info?.keyType && info?.web) {
        return (item?.keyType == info?.keyType && item?.web == info?.web)
      } else if (info?.keyType) {
        return item?.keyType == info?.keyType
      } else if (info?.web) {
        return item?.web == info?.web
      }
    })
    setTableData1([...arr])
  }

  // 提交装配
  const submit = () => {
    const searchParams = new URLSearchParams(location.search);
    const sysType = searchParams.get('sysType');
    let info = form.getFieldsValue();
    const formData = new FormData();
    formData.append('activeDate', info.activeDate.format('YYYY-MM-DD'));
    formData.append('endDate', moment().format('YYYY-MM-DD'));
    formData.append('secretImportId', selectedRowKeys1[0]);
    formData.append('sysType', sysTypeStr[sysType]);
    formData.append('type', '2');
    secretKey(formData).then((res) => {
      if (res?.result == "success") {
        initForm()
        onFinish()
        setSelectedRowKeys([])
        message.success('装配成功！')
        setVisibility(false)
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

  return (
    <div className={`${styles.params_warp}`}>
      <ButtonComp type={'special'} text={'用户密钥装配'} onClick={() => { }} />

      <Form form={form} layout={'inline'} onFinish={onFinish} className='mt20'>
        <Form.Item name="keyType" label="密钥类型" style={formItemSty}>
          <Select style={{ width: 260, marginRight: 16 }}
            onChange={(e) => onchange()}
            placeholder={'请选择密钥类型'}
            allowClear
            options={[
              { label: '密钥种类1', value: '密钥种类1' },
              { label: '密钥种类2', value: '密钥种类2' }
            ]} />
        </Form.Item>
        <Form.Item name="web" label="所属网络" style={formItemSty}>
          <Select style={{ width: 260, marginRight: 16 }}
            onChange={(e) => onchange()}
            placeholder={'请选择所属网络'}
            allowClear
            options={[
              { label: '离线', value: '离线' },
              { label: '指挥专网', value: '指挥专网' },
              { label: '军事综合信息网', value: '军事综合信息网' },
              { label: '资源管理网', value: '资源管理网' }
            ]} />
        </Form.Item>
        <Form.Item name="activeDate" label="启用日期" style={formItemSty} rules={[{ required: true, message: '请选择启用日期' }]}>
          <DatePicker
            style={{ width: 260 }}
            disabledDate={disabledDate}
            format="YYYY-MM-DD" />
        </Form.Item>
        <Form.Item name="endDate" label="终止日期" style={formItemSty} rules={[{ required: true, message: '请选择启用日期' }]}>
          <DatePicker
            style={{ width: 260 }}
            disabledDate={disabledDate}
            format="YYYY-MM-DD" />
        </Form.Item>
        <Form.Item name="system" label="应用系统" style={formItemSty}>
          <Select style={{ width: 260, marginRight: 16 }}
            onChange={(e) => onchange()}
            placeholder={'请选择应用系统'}
            allowClear
            options={[
              { label: '全部', value: '全部' }
            ]} />
        </Form.Item>
      </Form>

      <div className='mb10'>可装配的密钥体列表</div>
      <Table
        scroll={tableData1.length > 0 ? { y: 41 * 5 } : {}}
        pagination={false}
        bordered
        columns={columns}
        dataSource={tableData1}
        rowKey={(record: any) => record?.id}
        rowClassName={rowClassName}
        rowSelection={tableData1.length > 0 ? {
          type: 'radio',
          selectedRowKeys1,
          onChange: (selectedKeys: any) => {
            setSelectedRowKeys1(selectedKeys);
          }
        } : null}
      />

      <div className='flex_jE mt20'>
        <ButtonComp text={'装配'} onClick={() => onRules()} />
      </div>

      <div className='mb10 mt30'>用户密钥装配列表</div>

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

      {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 className='flex_jE mt20'>
        <ButtonComp type='cancel' style={{ marginRight: 20 }} text={'过滤'} onClick={() => { }} />
        <ButtonComp type='cancel' style={{ marginRight: 20 }} text={'载体输出'} onClick={() => {
          if (selectedRowKeys.length == 0) {
            message.info('请在用户密钥装配列表中选择一条数据！');
            return
          }
          onFinish()
          message.success('载体输出成功！')
        }} />
        <ButtonComp type='cancel' text={'下载到邮箱'} onClick={() => { }} />
      </div>

      <Modal
        title="xx部一体化对称密码管理系统"
        open={visibility}
        centered
        width={450}
        onCancel={() => setVisibility(false)}
        footer={null}
        maskClosable={false}>
        <div>
          {selectedData && <div className='mb20'>
            <div className='mb10' style={{ fontWeight: 'bold' }}>装配信息:</div>
            <div className='ml30'>产品名称：{selectedData?.productName} ,</div>
            <div className='ml30 mt10 mb10'>产品编号：{selectedData?.productNum} ,</div>
            <div className='ml30 mb10'>启用日期：{form.getFieldValue('activeDate') && form.getFieldValue('activeDate').format('YYYY-MM-DD')}</div>
            <div className='ml30'>终止日期：{form.getFieldValue('endDate') && form.getFieldValue('endDate').format('YYYY-MM-DD')}</div>
          </div>}
          {/* <div>类型判断2： 没有需要装配管理密钥的密码设备！</div> */}
        </div>
        <div className='flex_jE mt20'>
          <ButtonComp text={'确定'} style={{ marginRight: 20 }} onClick={() => submit()} />
          <ButtonComp type='cancel' text={'取消'} onClick={() => setVisibility(false)} />
        </div>
      </Modal>
    </div>
  );
}