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

import { rowClassName } from '@/utils';
import ButtonComp from '@/components/ButtonComp';
import { secretBodyImport, secretFormatList, secretList, secretUpdateSecret } from '@/services/my';
import { useParams } from 'umi';
import { fileStr, sysType, sysTypeStr } from '@/utils/sysType';
import ImportProgress from '@/components/ImportProgress';

export default function Page() {
  const [activeTab, setActiveTab] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [visibility, setVisibility] = useState(false);
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [fileInfo, setFileInfo] = useState(null);
  const [productNumber, setProductNumber] = useState('');
  const [speed, setSpeed] = useState(1);
  const [selectData, setSelectData] = useState<any>({
    keyType: [],
    productName: [],
    carrierType: [],
    carrierModel: [],
    net: []
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [allRowKeys, setAllRowKeys] = useState([]);

  const urlParams = useParams();
  const [form] = Form.useForm();

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

  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: 'productName', key: 'productName', align: 'center' },
    { title: '产品编号', dataIndex: 'productNum', key: 'productNum', align: 'center' },
    { title: '载体类型', dataIndex: 'carrierType', key: 'carrierType', align: 'center' },
    { title: '载体型号', dataIndex: 'applyModel', key: 'applyModel', align: 'center' },
    { title: '数量', dataIndex: 'number', key: 'number', align: 'center' },
    { title: '来源', dataIndex: 'source', key: 'source', align: 'center' },
    { title: '当前状态', dataIndex: 'currentStatus', key: 'currentStatus', align: 'center' },
    { title: '导入时间', dataIndex: 'importTime', key: 'importTime', align: 'center'},
  ]

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

  const initForm = () => {
  }

  // 获取下拉框数据
  const getSelect = () => {
    setSelectData({
      keyType: [
        { label: '密钥种类1', value: '密钥种类1' },
        { label: '密钥种类2', value: '密钥种类2' }
      ],
      productName: [
        { label: '产品名称1', value: '产品名称1' },
        { label: '产品名称2', value: '产品名称2' }
      ],
      carrierType: [
        { label: '软盘', value: '软盘' },
        { label: '移动盘', value: '移动盘' },
        { label: '全部', value: '全部' }
      ],
      carrierModel: [
        { label: '三寸', value: '三寸' },
        { label: '全部', value: '全部' }
      ],
      net: [
        { label: '来自产品1', value: '来自产品1' },
        { label: '来自产品2', value: '来自产品2' },
      ]
    })
  }

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

  // 获取密钥体列表 
  const getList = () => {
    secretList({ pageNumber, pageSize }).then((res) => {
      if (res?.result == "success") {
        res.data[0].list = res.data[0].list.filter((val: any) => {return val?.content != 'PMCS'})
        setTotal(res.data[0].total - 1)
        setTableData(res.data[0].list)
        const keys = res.data[0].list.map((item: any) => item?.id);
        setAllRowKeys(keys);
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

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

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

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

  const props: UploadProps = {
    maxCount: 1,
    beforeUpload: (file: any) => {
      console.log("file--",file)
      setFileInfo(file);
    }
  };

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

    let jg = false;
    tableData.forEach((item: any) => {
      selectedRowKeys.forEach(item2 => {
        if (item2 == item?.id && item?.currentStatus == '已使用') {
          jg = true;
        }
      })
    })

    if (jg) {
      message.info('当前状态为已使用的不能删除， 请先将已使用的'); return
    }

    let promises = selectedRowKeys.map(item => {
      return secretUpdateSecret({ id: item, type }).then((res) => {
        if (res?.result === "success") {
          return 1;
        } else {
          message.error(res?.errorMsg);
          return 0;
        }
      });
    });

    let str: any = { 1: '删除成功', 2: '还原成功', 3: '清理成功' }
    Promise.all(promises).then(results => {
      let recordCount = results.reduce((acc: any, val) => acc + val, 0);
      if (recordCount === selectedRowKeys.length) {
        message.success(`${str[type]}`);
        initForm();
        onFinish();
        setSelectedRowKeys([]);
      }
    });
  }

  const uploadFiles = () => {
    let data = form.getFieldsValue()
    let sysTypeName: string = sysType[urlParams?.fileType] + fileStr[urlParams?.fileType]

    const formData = new FormData();
    formData.append('file', fileInfo);
    formData.append('productNumber', `${productNumber}`);
    formData.append('keyType', `${data?.keyType}`);
    formData.append('productName', `${data?.productName}`);
    formData.append('carrierType', `${data?.carrierType}`);
    formData.append('carrierModel', `${data?.carrierModel}`);
    formData.append('net', `${data?.net}`);
    formData.append('sysType', `${sysTypeStr[sysTypeName]}`);
    secretBodyImport(formData).then((res) => {
      if (res?.result == "success") {
        setSpeed(4)
        setVisibility(false)
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

  return (
    <div className={`${styles.params_warp}`}>
      <TabsComp
        dataSource={[{ id: 1, name: '密钥体导入' }]}
        activeTab={activeTab}
        onChange={(e) => setActiveTab(e)} />

      <Form form={form} layout={'inline'} onFinish={onFinish} className='mt20'>
        <Form.Item name="keyType" label="密钥种类" style={formItemSty} rules={[{ required: true, message: '请选择密钥种类' }]}>
          <Select style={{ width: 260 }} placeholder="请选择密钥种类" options={selectData.keyType} />
        </Form.Item>
        <Form.Item name="productName" label="产品名称" style={formItemSty} rules={[{ required: true, message: '请选择产品名称' }]}>
          <Select style={{ width: 260 }} placeholder="请选择产品名称" options={selectData.productName} />
        </Form.Item>
        <Form.Item name="carrierType" label="载体类型" style={formItemSty} rules={[{ required: true, message: '请选择载体类型' }]}>
          <Select style={{ width: 260 }} placeholder="请选择载体类型" options={selectData.carrierType} />
        </Form.Item>
        <Form.Item name="carrierModel" label="载体型号" style={formItemSty} rules={[{ required: true, message: '请选择载体型号' }]}>
          <Select style={{ width: 260 }} placeholder="请选择载体型号" options={selectData.carrierModel} />
        </Form.Item>
        <Form.Item name="net" label="来源" style={{ ...formItemSty, marginLeft: 30 }} rules={[{ required: true, message: '请选择来源' }]}>
          <Select style={{ width: 260 }} placeholder="请选择来源" options={selectData.net} />
        </Form.Item>
      </Form>

      <div className='flex_jE' style={{ marginBottom: 30 }}>
        <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'导入'} onClick={() => {
          form.validateFields().then(() => {
            setSpeed(1);
            setFileInfo(null);
            setProductNumber('B211练');
            setVisibility(true)
          })
        }} />
        <ButtonComp text={'查询'} onClick={() => onFinish()} />
      </div>

      <div className='mb20 flex_aiC_jB'>
        <div>密钥体列表</div>
        <ButtonComp type={'cancel'} text={'全部'} onClick={() => setSelectedRowKeys(allRowKeys)} />
      </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_jE mt20'>
        <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'删除'} onClick={() => sending(1)} />
        <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'还原'} onClick={() => sending(2)} />
        <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'清理'} onClick={() => sending(3)} />
        <ButtonComp type={'cancel'} text={'载体输出'} onClick={() => { message.info('建设中') }} />
      </div>

      <Modal
        title="请确认或者输入产品编号"
        open={visibility}
        centered
        width={speed != 2 ? 425 : 515}
        onCancel={() => setVisibility(false)}
        footer={null}
        maskClosable={false}
        >
        <div>
          {
            speed == 1 &&
            <div className='mb20 mt10'>
              <div>
                <span style={{ marginRight: 4, color: 'red' }}>*</span>产品编号
                <Input placeholder="请输入产品编号" style={{ width: 300, marginLeft: 16 }}
                  value={productNumber}
                  disabled
                  onChange={(e) => setProductNumber(e.target.value)}
                />
              </div>
            </div>
          }
          {
            speed == 2 &&
            <div className='mb30'>
              <div className='mb10'>请选择载体的输入路径</div>
              <div className='flex_aiC'>
                <span style={{ marginRight: 4, color: 'red' }}>*</span>文件路径
                <Input style={{ width: 300, marginLeft: 16 }} value={fileInfo?.name || ''} disabled={true} />
                <Upload {...props} showUploadList={false}>
                  <ButtonComp style={{ marginLeft: 20 }} text={'选择'} />
                </Upload>
              </div>
            </div>
          }
          {speed == 3 && <div>是否到密钥体？</div>}
          {speed == 5 && <div>导入密钥体成功！</div>}
          {speed == 6 && <div>导入密钥体失败！</div>}
        </div>
        <div className='flex_jE mt20'>
          <ButtonComp style={{ marginRight: 20 }} text={'确定'} onClick={() => {
            switch (speed) {
              case 1:
                if (!productNumber.trim()) { message.error('请输入产品编号'); return }
                setSpeed(2)
                break;
              case 2:
                if (!fileInfo) { message.error('请选择文件路径'); return }
                setSpeed(3)
                break;
              case 3:
                uploadFiles()
                break;
              case 5:
                onFinish()
                setVisibility(false)
                break;
            }
          }} />
          <ButtonComp type='cancel' text={'取消'} onClick={() => setVisibility(false)} />
        </div>
      </Modal>

      {speed == 4 && <ImportProgress show={speed == 4 ? true : false} onoK={() => {
        setVisibility(true)
        setSpeed(5)
      }}/>}
    </div>
  );
}