import React, { useEffect, useState } from "react";
import ProTable, { ProColumns, } from "@ant-design/pro-table";
import { Button, Card, message, Modal, Progress, Spin } from "antd";
import { getRoomId, } from '@/utils/session';
import { getList, jieMi, jmRate } from "./service";
import { ipassDecrypt } from "@/utils/IpassVerification";
import { AsymDecrypt } from "@/utils/zwPlugin";
const FileDecode: React.FC<{}> = () => {
  const [spin, spinSet] = useState<any>(false);
  const [dis, disSet] = useState<boolean>(false);
  const [count, countSet] = useState<number>(0);
  const [tdocId, tdocIdSet] = useState<any>('');//tdocId
  const [rateVis, handleRateVis] = useState<boolean>(false); //进度显隐
  const [rateCount, rateCountSet] = useState<number>(0); //查询进度启动器
  const [jmFileCount, jmFileCountSet] = useState<number>(0);//文件总数
  const [jmComplete, jmCompleteSet] = useState<number>(0);//已解密成功
  const [jm, jmSet] = useState<boolean>();//是否解密 控制解密按钮
  const [jmWait, jmWaitSet] = useState<number>(0);//未解密
  const [jmFail, jmFailSet] = useState<number>(0);//解密失败
  const [dataSource, dataSourceSet] = useState<any>([{}]);
  //页面加载
  useEffect(() => {
    if (!rateVis) {
      getPage();
      setTimeout(async () => {
        countSet(count + 1);
      }, 2000);
    }
  }, [count]);
  //查询进度
  useEffect(() => {
    if (rateVis) {
      queryRate();
      setTimeout(async () => {
        rateCountSet(rateCount + 1);
      }, 2000);
    }
  }, [rateCount]);
  //查页面数据
  async function getPage() {
    let tdocIdT = '';
    let jm = false;
    await getList({ assessRoomId: getRoomId(), type: 1 }).then((res) => {
      if (res?.code == 200 && res?.data != undefined) {
        dataSourceSet(res.data);
        jmSet(res.data[res.data.length - 1].decryptStatus);
        tdocIdT = res.data[res.data.length - 1].id;
      }
    })
    if (!rateVis) {
      let all: number, comp: number, fail: number, wait: number = 0;
      await jmRate({ tdocId: tdocIdT }).then((res) => {
        if (res?.code == 200) {
          let data = res.data;
          all = data['-1'] != undefined ? parseInt(data['-1']) : 0;
          comp = data['1'] != undefined ? parseInt(data['1']) : 0;
          fail = data['2'] != undefined ? parseInt(data['2']) : 0;
          wait = data['0'] != undefined ? parseInt(data['0']) : 0;
        }
        jmCompleteSet(comp);
        jmFailSet(fail);
        jmFileCountSet(all);
        jmWaitSet(wait);
      });
    }
    spinSet(false);
  }
  //查询解密进度
  async function queryRate() {
    let all: number, comp: number, fail: number, wait: number = 0;
    await jmRate({ tdocId: tdocId }).then((res) => {
      if (res?.code == 200) {
        let data = res.data;
        all = data['-1'] != undefined ? parseInt(data['-1']) : 0;
        comp = data['1'] != undefined ? parseInt(data['1']) : 0;
        fail = data['2'] != undefined ? parseInt(data['2']) : 0;
        wait = data['0'] != undefined ? parseInt(data['0']) : 0;
      }
      jmCompleteSet(comp);
      jmFailSet(fail);
      jmFileCountSet(all);
      jmWaitSet(wait);
    });
  }
  const columns: ProColumns<any>[] = [
    { title: '序号', dataIndex: 'index', valueType: 'index', width: 80 },
    {
      title: '应答轮次', width: 80,
      render: (_: any, record: any) => {
        if (JSON.stringify(record) == "{}") {
          return '';
        } else {
          return record?.registerInfoVOList[0].reviewTurnSort;
        }
      }
    },
    {
      title: '解密状态', width: 80,
      render: (_: any, record: any) => {
        if (JSON.stringify(record) == "{}") {
          return '';
        } else {
          const status = record?.quoteOrOther == "1" ? record?.registerInfoVOList[0].decryptOtherStatus : record?.registerInfoVOList[0].decryptStatus;
          if (status == null || status === '1') { return '未解密' }
          else if (status === '2') { return '解密成功' }
          else if (status === '3') { return '解密失败' }
          else { return '' }
        }
      }
    },
    { title: '解密截止时间', dataIndex: 'decryptEndDate', valueType: 'dateTime', width: 80 },
    {
      title: '解密时间', valueType: 'dateTime', width: 80,
      render: (_: any, record: any) => {
        if (JSON.stringify(record) == "{}") {
          return '';
        } else {
          const date = record?.registerInfoVOList[0].decryptTime;
          return date;
        }
      }
    },
    {
      title: '操作', width: 80,
      render: (_: any, record: any) => {
        if (JSON.stringify(record) !== "{}" && jm) {
          const status = record?.quoteOrOther == "1" ? record?.registerInfoVOList[0].decryptOtherStatus : record?.registerInfoVOList[0].decryptStatus;
          if (record?.decryptEndDate !== '' && record?.decryptEndDate !== null && status !== '2') {
            return <Button type='primary' disabled={dis} onClick={async () => {
              spinSet(true); disSet(true);
              tdocIdSet(record?.id)
              let secretKeyMap: any = {};
              if (record.tfileList.length > 0) {
                if (ipassDecrypt(record.tfileList[0].secretKey) != null) {
                  await record.tfileList.map((item: any) => {
                    secretKeyMap[item.id] = AsymDecrypt(item.secretKey);
                  })
                }
              } else {
                message.error('没有可以解密的文件！')
              }
              if (Object.keys(secretKeyMap).length > 0) {
                const success = await jieMi({ tdocId: record?.id, secretKeyMap: secretKeyMap }).then((res) => {//roomType: roomType
                  return res.success
                });
                if (success) {
                  handleRateVis(true);
                  rateCountSet(rateCount + 1);
                }
              }
              spinSet(false); disSet(false);
            }}>解密</Button>
          } else {
            if (status === '2') {
              return ''
            } else {
              return '请等待项目经理开启解密'
            }
          }
        } else { return '' }
      }
    },
  ];
  //解密进度
  const jmjd = () => {
    return (
      <Modal
        title="解密进度"
        width={'800px'}
        destroyOnClose
        centered
        bodyStyle={{ padding: '32px 40px 48px', overflowY: 'auto' }}
        visible={rateVis}
        footer={false}
        onCancel={() => { spinSet(true); countSet(count + 1); handleRateVis(false); }}
      >
        <Card bordered={false} style={{ textAlign: 'center', fontSize: '30px', }}>
          {jmComplete + jmFail == jmFileCount ? `解 密 结 束` : `正 在 解 密...`}
        </Card>
        <Progress percent={Math.floor((jmComplete / jmFileCount) * 100)} status="active" />
        <div style={{ textAlign: "center" }}>
          文件总数：<span style={{ fontSize: 30, color: 'rgb(0,144,255)' }}>{jmFileCount}</span> 个
        </div>
        <div style={{ textAlign: "center" }}>
          解密成功：<span style={{ fontSize: 30, color: 'rgb(61,169,92)' }}>{jmComplete}</span> 个,
          {/* 排队解密中：<span style={{ fontSize: 30, color: 'red' }}>{100 - rate}</span> 个, */}
          尚未解密：<span style={{ fontSize: 30, color: 'rgb(0,144,255)' }}>{jmWait}</span> 个,
          解密失败：<span style={{ fontSize: 30, color: 'red' }}>{jmFail}</span> 个
        </div>
      </Modal>
    )
  }
  return (
    <Card>
      <Spin spinning={spin}>
        {/* {ipassDecode ? <div key='jmsxTip' className='mR8 xsy-red floatLeft h32 ftSz20' hidden={endTimeVis}>投标人解密时限: {endTime}</div> : null} */}
        <ProTable
          columns={columns}//表格
          search={false}
          size={'small'}
          rowSelection={false}
          options={false}
          pagination={false}//默认显示条数
          dataSource={dataSource}
        />
        {jmjd()}
      </Spin>
    </Card>
  )
}
export default FileDecode;