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

import { rowClassName } from '@/utils';
import ButtonComp from '@/components/ButtonComp';
import { testData } from './testData';
import { upholdArgsInfoDelOrRestore, upholdArgsInfoEditOrAdd, upholdArgsInfoList } from '@/services/sf';

export default function Page() {
  const [tableData, setTableData] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [form] = Form.useForm();
  const [visibility, setVisibility] = useState<boolean>(false);
  const [form1] = Form.useForm();
  const [visibility1, setVisibility1] = useState<boolean>(false);

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

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

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

  const columns: any = [
    {
      title: '序号', key: 'index', align: 'center', width: 80,
      render: (a: any, b: any, c: any) => {
        return <span>{(pageNumber - 1) * pageSize + c + 1}</span>;
      },
    },
    { title: '参数中文名称', dataIndex: 'argsCnName', key: 'argsCnName', align: 'center' },
    { title: '对应算法标识', dataIndex: 'algorithmId', key: 'algorithmId', align: 'center' },
    { title: '参数简称', dataIndex: 'argsShortName', key: 'argsShortName', align: 'center' },
    { title: '模式简称', dataIndex: 'modelShortName', key: 'modelShortName', align: 'center' },
    {
      title: '删除状态', dataIndex: 'delFlag', key: 'delFlag', align: 'center',
      render: (val: any) => { return <span>{val == 1 ? '已删除' : '未删除'}</span> }
    }
  ]

  const initForm = () => [
    form.setFieldsValue({
      deviceType: '',
      argsName: '',
      argsStyle: '',
      argsType: '',
    })
  ]

  const initForm1 = () => [
    form1.setFieldsValue({
      argsStyle: '一体化格式参数',
      argsType: '初始参数导入'
    })
  ]

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

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

  const sending = (delStatus: number) => {
    if (selectedRowKeys.length == 0) {
      message.info('请勾选数据');
      return
    }

    upholdArgsInfoDelOrRestore({ ids: selectedRowKeys, delStatus }).then((res) => {
      if (res?.result === "success") {
        message.success((delStatus == 1 ? '删除' : '还原') + '成功');
        pageNumber == 1 ? getList() : setPageNumber(1);
        setSelectedRowKeys([]);
      } else {
        message.error(res?.errorMsg);
      }
    });
  }

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

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

  const onFinish = (info: any) => {
    let promises = testData.map(async item => {
      item.argsStyle = info.argsStyle;
      item.argsType = info.argsType;
      const res = await upholdArgsInfoEditOrAdd(item);
      if (res?.result === "success") {
        updataList()
        return 1;
      } else {
        message.error(res?.errorMsg);
        return 0;
      }
    });

    Promise.all(promises).then(results => {
      let recordCount = results.reduce((acc: any, val: any) => acc + val, 0);
      if (recordCount === testData.length) {
        setVisibility(false)
        setVisibility1(true)
      } else {
        message.error('导入失败')
      }
    });
  }

  return (
    <div className={`${styles.params_warp}`}>
      <ButtonComp type={'special'} text={'算法参数信息维护'} />

      <div className='flex_aiC mt30 mb10'>
        <Form form={form} layout={'inline'} onFinish={updataList}>
          <Form.Item name="deviceType" label="设备型号" style={formItemSty}>
            <Input placeholder="请输入设备型号" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="argsName" label="参数名称" style={formItemSty}>
            <Input placeholder="请输入参数名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="argsStyle" label="参数格式" style={formItemSty}>
            <Select style={{ width: 200 }} placeholder="请选择参数格式"  onChange={(e) => { }} options={[
              { label: '全部', value: '' },
              { label: '一体化格式参数', value: '一体化格式参数' },
              { label: '统型完善格式参数', value: '统型完善格式参数' },
              { label: '体制统一格式参数', value: '体制统一格式参数' }
            ]} />
          </Form.Item>
          <Form.Item name="argsType" label="参数类型" style={formItemSty}>
            <Select style={{ width: 200 }} placeholder="请选择参数类型"  onChange={(e) => { }} options={[
              { label: '全部', value: '' },
              { label: '初始参数导入', value: '初始参数导入' },
              { label: '非初始参数导入', value: '非初始参数导入' }
            ]} />
          </Form.Item>
        </Form>
      </div>

      <Table
        scroll={tableData.length > 0 ? { y: 41 * 10 } : {}}
        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 className='flex_aiC_jB mt30'>
        <ButtonComp text={'导入参数'} onClick={() => setVisibility(true)} />
        <div className='flex_aiC_jB'>
          <ButtonComp style={{ marginRight: 20 }} text={'查询'} onClick={() => form.submit()} />
          <ButtonComp style={{ marginRight: 20 }} type={'delete'} text={'删除'} onClick={() => sending(1)} />
          <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'恢复'} onClick={() => sending(0)} />
          <ButtonComp type={'cancel'} text={'清理'} onClick={() => { }} />
        </div>
      </div>

      <Modal
        title="请选择导入参数类型"
        open={visibility}
        centered
        width={600}
        onCancel={() => setVisibility(false)}
        footer={null}
        maskClosable={false}
      >
        <Form form={form1} layout={'vertical'} onFinish={(e) => { onFinish(e) }}>
          <Form.Item name="argsStyle" label="参数格式类型选择" style={{ width: '100%', marginBottom: 20 }}>
            <Radio.Group>
              <Radio value={'一体化格式参数'}> 一体化格式参数 </Radio>
              <Radio value={'统型完善格式参数'}> 统型完善格式参数</Radio>
              <Radio value={'体制统一格式参数'}> 体制统一格式参数</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="argsType" label="参数类型选择" style={{ width: '100%', marginBottom: 20 }}>
            <Radio.Group>
              <Radio value={'初始参数导入'}> 初始参数导入</Radio>
              <Radio value={'非初始参数导入'}> 非初始参数导入</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>

        <div className='flex_jE mt20'>
          <ButtonComp style={{ marginRight: 20 }} text={'确定'} onClick={() => form1.submit()} />
          <ButtonComp type="cancel" text={'取消'} onClick={() => {
            initForm1();
            setVisibility(false)
          }} />
        </div>
      </Modal>

      <Modal
        title="二级单位一体化对称密码管理系统"
        open={visibility1}
        centered
        width={550}
        onCancel={() => setVisibility1(false)}
        footer={null}
        maskClosable={false}
      >
        <div>导入上级离线配发算法资源成功！</div>
        <div className='flex_jE mt20'>
          <ButtonComp style={{ marginRight: 20 }} text={'确定'} onClick={() => {
            setVisibility1(false);
          }} />
        </div>
      </Modal>
    </div>
  );
}